Example #1
0
int wpdu::convert_vb_to_smival( Vb &tempvb, SmiVALUE *smival )
{
  smival->syntax = tempvb.get_syntax();

  switch ( smival->syntax ) {

  case sNMP_SYNTAX_NULL:
    break;

    // case sNMP_SYNTAX_INT32:
  case sNMP_SYNTAX_INT:
    {
      SnmpInt32 tmp;
      tempvb.get_value(tmp);
      smival->value.sNumber = tmp;
    }
    break;

    //    case sNMP_SYNTAX_UINT32:
  case sNMP_SYNTAX_GAUGE32:
  case sNMP_SYNTAX_CNTR32:
  case sNMP_SYNTAX_TIMETICKS:
    {
      SnmpUInt32 tmp;
      tempvb.get_value(tmp);
      smival->value.uNumber = tmp;
    }
    break;

    // case Counter64
  case sNMP_SYNTAX_CNTR64:
    {
      Counter64 c64;
      tempvb.get_value(c64);
      smival->value.hNumber.hipart = c64.high();
      smival->value.hNumber.lopart = c64.low();
    }
    break;

   // OID syntax
  case sNMP_SYNTAX_OID:
    {
      Oid tmpoid;
      tmpoid.oidval();
      tempvb.get_value(tmpoid);
      SmiLPOID smi = tmpoid.oidval();
      smival->value.oid.len = tmpoid.length();
      ACE_NEW_RETURN(smival->value.oid.ptr,
                SmiUINT32 [smival->value.oid.len], 1);
      ACE_OS::memcpy(smival->value.oid.ptr, smi->ptr,
                     smival->value.oid.len *sizeof(SmiUINT32));
    }
    break;

  case sNMP_SYNTAX_BITS:
  case sNMP_SYNTAX_OCTETS:
  case sNMP_SYNTAX_IPADDR:
    {
      OctetStr os;
      tempvb.get_value(os);
      smival->value.string.ptr = 0;
      smival->value.string.len = os.length();
      if ( smival->value.string.len > 0 ) {
        ACE_NEW_RETURN(smival->value.string.ptr,
                SmiBYTE [smival->value.string.len], 1);
        if ( smival->value.string.ptr )  {
          for (int i=0; i<(int) smival->value.string.len ; i++)
            smival->value.string.ptr[i] = os[i];
        }
        else   {
          smival->syntax = sNMP_SYNTAX_NULL;  // invalidate the smival
          return SNMP_CLASS_RESOURCE_UNAVAIL;
        }
      }
    }
    break;

    default:
     ACE_DEBUG((LM_DEBUG, "wpdu::convert_vb_to_smival did not convert vb\n"));
     // ACE_ASSERT(0);
  } // switch

  return 0;
}
Example #2
0
int CSVBaseSNMP::GetRequest(MonitorResult &ResultList)
{
	WriteLog("\n\n*****************************");
	WriteLog("GetRequest!");

    int nResult = 0;
    Pdu pdu;                                                    // construct a Pdu object
    Vb vb;                                                      // construct a Vb object
    vb.set_oid( oid);                                           // set the Oid portion of the Vb
    pdu += vb;                                                  // add the vb to the Pdu

    SnmpTarget *target;
    if(version == version3)
    {//If SNMP Version Is 3
        nResult = InitUTarget();                                //Init UTarget
        pdu.set_security_level( m_lSecurityLevel);              //Set the Security Level portion of Pdu
        pdu.set_context_name(m_szContextName);                  //Set the Context Name portion of Pdu
        pdu.set_context_engine_id(m_szContextEngineID);         //Set the Context Engine ID portion of Pdu
        target = &m_Utarget;                                    //Set SNMP Target
    }
    else
    {
        target = &m_Ctarget;                                    //Set SNMP Target
    }

    try
    {
        //cout << address << endl;
        //cout << oid.get_printable() << endl;
        if(m_pSnmp)
        {
            nResult = m_pSnmp->get( pdu,*target);               //Get Reques
            if(nResult != 0)
            {//当有错误发生时候
                m_szErrorMsg =  m_pSnmp->error_msg(nResult);
                return nResult;
            }
            for ( int i = 0; i < pdu.get_vb_count(); i ++)
            {
                pdu.get_vb(vb, i);
                if (pdu.get_type() == REPORT_MSG) 
                {
                    Oid tmp;
                    vb.get_oid(tmp);
                    return -5;
                }
                // look for var bind exception, applies to v2 only   
                if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW)
                {
                    SNMP_Monitor_Result result;
                    result.m_szOID = vb.get_printable_oid();
                    result.m_szValue = vb.get_printable_value();
                    size_t nPosition = result.m_szOID.rfind(".");
                    if(nPosition > 0)
                    {
                        result.m_szIndex = result.m_szOID.substr(nPosition);
                        result.m_szOID = result.m_szOID.substr(0, nPosition - 1);
                    }

					WriteLog(result.m_szIndex.c_str());
					WriteLog(result.m_szValue.c_str());

                    ResultList[i] = result;
                }
                else 
                {
                    m_szErrorMsg =  "End of MIB Reached";
                    return -4;
                }
            }
        }
    }
    catch(...)
    {
        DWORD dwError = GetLastError();
        char szMsg[512] = {0};
        int nlen = sprintf(szMsg, "Error Number is %08X --*GetRequest*---", dwError);
        DumpLog("snmpmonitor-request", szMsg, nlen);
    }
    return nResult;
}
Example #3
0
int CSVBaseSNMP::GetBulkRequest(MonitorResult &ResultList)
{
	
	WriteLog("\n\n*****************************");
	WriteLog("GetBulkRequest!");

    static const int BULK_BUFF = 10;
    int nResult = 0;
    char chPrvOID[MAX_BUFF_LEN] = {0};
    bool bEnd = false;
    Pdu pdu;                                                // construct a Pdu object
    Vb vb;                                                  // construct a Vb object
    vb.set_oid( oid);                                       // set the Oid portion of the Vb
    pdu += vb;                                              // add the vb to the Pdu

    SnmpTarget *target;
    if(version ==version3)
    {//If SNMP Version Is 3
        nResult = InitUTarget();                            //Init UTarget
        pdu.set_security_level( m_lSecurityLevel);          //Set the Security Level portion of Pdu
        pdu.set_context_name (m_szContextName);             //Set the Context Name portion of Pdu
        pdu.set_context_engine_id(m_szContextEngineID);     //Set the Context Engine ID portion of Pdu
        target = &m_Utarget;                                //Set SNMP Target
    }
    else
    {
        target = &m_Ctarget; //Set SNMP Target
    }
    
    try
    {
        if(m_pSnmp)
        {
            int nIndex = 0, i = 0;
            while (( nResult = m_pSnmp->get_bulk(pdu, *target, 0, BULK_BUFF)) == SNMP_CLASS_SUCCESS) 
            {
                if(bEnd)
                    break;
                for (i = 0; i < pdu.get_vb_count(); i ++) 
                {
                    pdu.get_vb( vb, i);
                    if (pdu.get_type() == REPORT_MSG) 
                    {
                        Oid tmp;
                        vb.get_oid(tmp);
                        return -5;
                    }
                    // look for var bind exception, applies to v2 only   
                    if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW)
                    {
                        string szOID =  vb.get_printable_oid();
						WriteLog(szOID.c_str());
                        int nPosition = static_cast<int>(szOID.find(m_szStartID));
                        if(nPosition < 0)
                        {
                            bEnd = true;
                            break;
                        }
                        if(static_cast<int>(strlen(chPrvOID)) > 0)
                        {//如果上次OID不为空
                            if(strcmp(vb.get_printable_oid(), chPrvOID) == 0)
                            {//比较OID名称是否相同,相同则退出循环
                                bEnd = true;
                                break;
                            }
                        }
				        //结果赋值
                        if(static_cast<int>(strlen(vb.get_printable_oid())) < MAX_BUFF_LEN)
                            strcpy(chPrvOID, vb.get_printable_oid());

						
                        SNMP_Monitor_Result result;
						result.m_szOID = vb.get_printable_oid();
						if(strcmp(result.m_szOID.substr(0,19).c_str(),"1.3.6.1.2.1.2.2.1.2")==0)
						{
							char str[100];
							vb.get_value(str);
							result.m_szValue=str;
							WriteLog(str);
						}
						else
							result.m_szValue = vb.get_printable_value();
        
                        //nPosition = static_cast<int>(result.m_szOID.find(m_szStartID.c_str()) + m_szStartID.length());
                        //if(nPosition > 0)
                        //{
                        result.m_szIndex = result.m_szOID.substr(m_szStartID.length() + 1);
                        result.m_szOID = result.m_szOID.substr(0, m_szStartID.length());
                        //PrintDebugString("index is " + result.m_szIndex);
                        //}
						WriteLog(result.m_szIndex.c_str());
						WriteLog(result.m_szValue.c_str());

                        ResultList[nIndex] = result;
                        nIndex ++;
                    }
                    else 
                    {
                        m_szErrorMsg = "End of MIB Reached";
                        return -4;
                    }
                }
                // last vb becomes seed of next rquest
                pdu.set_vblist(&vb, 1);
            }
        }
    }
    catch(...)
    {
        DWORD dwError = GetLastError();
        char szMsg[512] = {0};
        int nlen = sprintf(szMsg, "Error Number is %08X --*GetBulkRequest*---", dwError);
        DumpLog("snmpmonitor-bulk.log", szMsg, nlen);
    }

    if(nResult == SNMP_ERROR_NO_SUCH_NAME)
    {
        nResult = 0;
    }
	return nResult;
}
Example #4
0
/////////////////////////////////////////////////////////////////////////////
// 函数:GetBulkRequest                                                    //
// 说明:得到表格变量的结果                                                //
// 参数:无                                                                //
// 返回值:                                                                //
//      成功返回0,否则返回一个非0 值                                      //
/////////////////////////////////////////////////////////////////////////////
int BasicSNMP::GetBulkRequest()
{
	//puts("BasicSNMP::GetBulkRequest");
	int nResult = 0;
	char chPrvOID[MAX_BUFF_LEN] = {0};
	bool bEnd = false;
	Pdu pdu;                               // construct a Pdu object
	Vb vb;                                 // construct a Vb object
	vb.set_oid( oid);                      // set the Oid portion of the Vb
	pdu += vb;                             // add the vb to the Pdu

	DestroyResultList();

	SnmpTarget *target;// = &ctarget;
	if(version ==version3)
	{//If SNMP Version Is 3
		nResult = InitUTarget();//Init UTarget
		pdu.set_security_level( m_nSecurityLevel);//Set the Security Level portion of Pdu
		pdu.set_context_name (contextName);//Set the Context Name portion of Pdu
		pdu.set_context_engine_id(contextEngineID);//Set the Context Engine ID portion of Pdu
		target = &utarget; //Set SNMP Target
	}
	else
	{
		target = &ctarget; //Set SNMP Target
	}

	OIDResult *pTemp = new OIDResult();
	OIDResult *pPrevResult = pTemp;
	//pTemp->pNext = NULL;
	pResult = pTemp;
    
    try
    {
	//SnmpTarget *target = &ctarget;
	while (( nResult = pSnmp->get_next(pdu, *target))== SNMP_CLASS_SUCCESS) 
	{
		if(bEnd)
		{
			break;
		}
		for ( int z=0;z<pdu.get_vb_count(); z++) 
		{
			pdu.get_vb( vb,z);
			if (pdu.get_type() == REPORT_MSG) 
			{
				Oid tmp;
				vb.get_oid(tmp);
				return -5;
			}
			// look for var bind exception, applies to v2 only   
			if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW)
			{
				char chOID[MAX_BUFF_LEN] = {0};
				sprintf(chOID, "%s", vb.get_printable_oid());
				char *pDest = strstr(chOID, chOIDStart);
				if(pDest == NULL)
				{//OID名称是否包含开始OID
					bEnd = true;
					break;
				}
				if(strlen(chPrvOID)>0)
				{//如果上次OID不为空
					if(strcmp(vb.get_printable_oid(), chPrvOID) == 0)
					{//比较OID名称是否相同,相同则退出循环
						bEnd = true;
						break;
					}
				}
				//结果赋值
				strcpy(chPrvOID, vb.get_printable_oid());				
				strcpy(pTemp->chOID, vb.get_printable_oid());
				strcpy(pTemp->chValue,vb.get_printable_value());
				
				char *pIndex;
				pIndex=pTemp->chOID+strlen(oid.get_printable())+1;

				//pTemp->nLen = static_cast<int>(strlen(pTemp->chValue));
				//char *pdest = strrchr(pTemp->chOID, '.');
				//int nLast = (int)(pdest - pTemp->chOID + 1);
				//memcpy(pTemp->chIndex, (pTemp->chOID)+nLast, strlen(pTemp->chOID) - nLast);
				strcpy(pTemp->chIndex,pIndex);
				//pTemp->chIndex[strlen(pTemp->chOID) - nLast] = '\0';
				
			}
			else 
			{
				memset(chErrMsg, 0 , MAX_BUFF_LEN);
				strcpy(chErrMsg, "End of MIB Reached");
				return -4;
			}
			if(pTemp->pNext == NULL)
			{
				pPrevResult = pTemp;
				pTemp->pNext = new OIDResult();
                if(pTemp->pNext)
				    pTemp = pTemp->pNext;
				//pTemp->pNext = NULL;
			}
		}
		// last vb becomes seed of next rquest
		pdu.set_vblist(&vb, 1);
	}
    if(nResult == 0)
    {
	    if(pTemp->pNext == NULL)
	    {	
            free(pTemp);
		    pTemp = NULL;
		    pPrevResult->pNext = NULL;
	    }
    }
    }
    catch(...)
    {
        DWORD dwError = GetLastError();
        char szMsg[512] = {0};
        int nlen = sprintf(szMsg, "Error Number is %08X --*GetBulkRequest*---", dwError);
        DumpLog("snmpmonitor-bulk.log", szMsg, nlen);
        //cout << "Error Number is " << dwError << "---*GetRequest*---" << endl;
    }
    if(nResult == SNMP_ERROR_NO_SUCH_NAME)
    {
        nResult = 0;
        pPrevResult->pNext = NULL;
    }
	return nResult;
}
Example #5
0
int snmpget(char *ipaddr, char *oid_in)
{
	Snmp::socket_startup();  // Initialize socket subsystem

	UdpAddress address(ipaddr);// make a SNMP++ Generic address
	if (!address.valid())
	{           // check validity of address
		cout << "Invalid Address or DNS Name, " << ipaddr << "\n";
		//	  usage();
	}
	snmp_version version = version1;                  // default is v1
	int retries = 1;                                  // default retries is 1
	int timeout = 100;                                // default is 1 second
	u_short port = 161;                               // default snmp port is 161
	OctetStr community("public");                   // community name

	int status;

	Snmp snmp(status, 0, (address.get_ip_version() == Address::version_ipv6));

	if (status != SNMP_CLASS_SUCCESS) {
		cout << "SNMP++ Session Create Fail, " << snmp.error_msg(status) << "\n";
		return 1;
	}
	Oid oid("1.3.6.1.2.1.1.1.0");      // default is sysDescr
	Pdu pdu;
	Vb  vb;
	oid = oid_in;
	if (!oid.valid()){
		cout << "Oid " << oid_in << " is not valid" << endl;
		return 1;
	}
	vb.set_oid(oid);                       // set the Oid portion of the Vb
	pdu += vb;                             // add the vb to the Pdu

	address.set_port(port);
	CTarget ctarget(address);             // make a target using the address
	ctarget.set_version(version);         // set the SNMP version SNMPV1 or V2
	ctarget.set_retry(retries);           // set the number of auto retries
	ctarget.set_timeout(timeout);         // set timeout
	ctarget.set_readcommunity(community); // set the read community name



	SnmpTarget *target;
	target = &ctarget;
	status = snmp.get(pdu, *target);

	if (status == SNMP_CLASS_SUCCESS)
	{
		for (int i = 0; i < pdu.get_vb_count(); i++)
		{
			pdu.get_vb(vb, i);
			cout << "**************************" << endl;
			cout << "VB nr: " << i << endl;
			cout << "Oid = " << vb.get_printable_oid() << endl
				<< "Value = " << vb.get_printable_value() << endl;
			cout << "Syntax = " << vb.get_syntax() << endl;

			if ((vb.get_syntax() == sNMP_SYNTAX_ENDOFMIBVIEW) ||
				(vb.get_syntax() == sNMP_SYNTAX_NOSUCHINSTANCE) ||
				(vb.get_syntax() == sNMP_SYNTAX_NOSUCHOBJECT))
				cout << "Exception: " << vb.get_syntax() << " occured." << endl;
		}
	}
	else
	{
		cout << "SNMP++ Get Error, " << snmp.error_msg(status)
			<< " (" << status << ")" << endl;
	}
	Snmp::socket_cleanup();  // Shut down socket subsystem
	return 0;
}
Example #6
0
/////////////////////////////////////////////////////////////////////////////
// 函数:GetRequest                                                        //
// 说明:得到简单变量的结果                                                //
// 参数:无                                                                //
// 返回值:                                                                //
//      成功返回0,否则返回一个非0 值                                      //
/////////////////////////////////////////////////////////////////////////////
int BasicSNMP::GetRequest()
{
    static const char chFile[] = "smmpmonitor.log";
    int nResult = 0;
	Pdu pdu;                               // construct a Pdu object
	Vb vb;                                 // construct a Vb object
	vb.set_oid( oid);                      // set the Oid portion of the Vb
	pdu += vb;                             // add the vb to the Pdu
    
	DestroyResultList();

	SnmpTarget *target;// = &ctarget;
	if(version ==version3)
	{//If SNMP Version Is 3
		nResult = InitUTarget();//Init UTarget
		pdu.set_security_level( m_nSecurityLevel);//Set the Security Level portion of Pdu
		pdu.set_context_name (contextName);//Set the Context Name portion of Pdu
		pdu.set_context_engine_id(contextEngineID);//Set the Context Engine ID portion of Pdu
		target = &utarget; //Set SNMP Target
	}
	else
	{
		target = &ctarget; //Set SNMP Target
	}

	OIDResult *pTemp = new OIDResult();//construct OIDResult Struct
	pTemp->pNext = NULL;
	pResult = pTemp;

    try
    {
		nResult = pSnmp->get( pdu,*target);//Get Reques
		if(nResult != 0)
		{//当有错误发生时候
			strcpy(chErrMsg, pSnmp->error_msg(nResult));
			return nResult;
		}
		for ( int z = 0; z < pdu.get_vb_count(); z++)
		{
			pdu.get_vb( vb,z);
			if (pdu.get_type() == REPORT_MSG) 
			{
				Oid tmp;
				vb.get_oid(tmp);
				return -5;
			}
			// look for var bind exception, applies to v2 only   
			if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW)
			{
				//Set OIDResult Value
                if(static_cast<int>(strlen(vb.get_printable_oid())) < MAX_BUFF_LEN)
				    strcpy(pTemp->chOID,  vb.get_printable_oid());

                if(static_cast<int>(strlen(vb.get_printable_value())) < MAX_BUFF_LEN)
                {
				    strcpy(pTemp->chValue, vb.get_printable_value());
				    //pTemp->nLen = static_cast<int>(strlen(pTemp->chValue));
                }
                char *pdest = strrchr(pTemp->chOID, '.');
                if(pdest)
                {
                    (*pdest) = '\0';
                    pdest ++;
                    strcpy(pTemp->chIndex, pdest);
                }
                //if(pdest)
                //{
                //    int nLast = (int)(pdest - pTemp->chOID + 1);
                //    memcpy(pTemp->chIndex, (pTemp->chOID)+nLast, strlen(pTemp->chOID) - nLast);
                //    pTemp->chIndex[strlen(pTemp->chOID) - nLast] = '\0';
                //}
			}
			else 
			{
				memset(chErrMsg, 0 , MAX_BUFF_LEN);
				strcpy(chErrMsg, "End of MIB Reached");
				return -4;
			}
		}	
    }
    catch(...)
    {
        DWORD dwError = GetLastError();
        char szMsg[512] = {0};
        int nlen = sprintf(szMsg, "Error Number is %08X --*GetRequest*---", dwError);
        DumpLog(chFile, szMsg, nlen);
        //cout << "Error Number is " << dwError << "---*GetRequest*---" << endl;
    }
    return nResult;
}
Example #7
0
/////////////////////////////////////////////////////////////////////////////
// 函数:GetNextRequest                                                    //
// 说明:以当前OID变量为开始,得到下一个简单变量的结果                     //
// 参数:无                                                                //
// 返回值:                                                                //
//      成功返回0,否则返回一个非0 值                                      //
/////////////////////////////////////////////////////////////////////////////
int BasicSNMP::GetNextRequest()
{
	int nResult = 0;
	Pdu pdu;                               // construct a Pdu object
	Vb vb;                                 // construct a Vb object
	vb.set_oid( oid);                      // set the Oid portion of the Vb
	pdu += vb;                             // add the vb to the Pdu

	DestroyResultList();

	SnmpTarget *target;// = &ctarget;
	if(version ==version3)
	{//If SNMP Version Is 3
		nResult = InitUTarget();//Init UTarget
		pdu.set_security_level( m_nSecurityLevel);//Set the Security Level portion of Pdu
		pdu.set_context_name (contextName);//Set the Context Name portion of Pdu
		pdu.set_context_engine_id(contextEngineID);//Set the Context Engine ID portion of Pdu
		target = &utarget; //Set SNMP Target
	}
	else
	{
		target = &ctarget; //Set SNMP Target
	}


	OIDResult *pTemp = new OIDResult();
	pTemp->pNext = NULL;
	pResult = pTemp;

	//SnmpTarget *target = &ctarget;
	nResult = pSnmp->get_next( pdu,*target);
	if(nResult != 0)
	{//当有错误发生时候
		strcpy(chErrMsg, pSnmp->error_msg(nResult));
	}
	for ( int z=0;z<pdu.get_vb_count(); z++) 
	{
		pdu.get_vb( vb,z);
		if (pdu.get_type() == REPORT_MSG) 
		{
			Oid tmp;
			vb.get_oid(tmp);
			return -5;
		}
		// look for var bind exception, applies to v2 only   
		if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW)
		{
			strcpy(pTemp->chOID, vb.get_printable_oid());
			strcpy(pTemp->chValue,vb.get_printable_value());
			//pTemp->nLen = static_cast<int>(strlen(pTemp->chValue));
			char *pdest = strrchr(pTemp->chOID, '.');
			int nLast = (int)(pdest - pTemp->chOID + 1);
			memcpy(pTemp->chIndex, (pTemp->chOID)+nLast, strlen(pTemp->chOID) - nLast);
			pTemp->chIndex[strlen(pTemp->chOID) - nLast] = '\0';
			oid = pTemp->chOID;
		}
		else 
		{
//			memset(chErrMsg, 0 , MAX_BUFF_LEN);
//			strcpy(chErrMsg, "End of MIB Reached");
			return -4;
		}
	}
	return nResult;
}
Example #8
0
int main_bulk_jun( int argc, char **argv)
{
	{
	  cout << "Usage:\n";
	  cout << "snmpBulk IpAddress | DNSName [Oid [Oid...]] [options]\n";
	  cout << "Oid: sysDescr object is default\n";
	  cout << "options: -v1 , use SNMPV1, default\n";
	  cout << "         -v2 , use SNMPV2\n";
#ifdef _SNMPv3
          cout << "         -v3 , use SNMPV3\n";
#endif
	  cout << "         -pPort , remote port to use\n";
	  cout << "         -CCommunity_name, specify community default is 'public' \n";
	  cout << "         -rN , retries default is N = 1 retry\n";
	  cout << "         -tN , timeout in hundredths of seconds; default is N = 100\n";
	  cout << "         -nN , non-repeaters default is N = 0\n";
	  cout << "         -mN , max-repetitions default is  N = 1\n";
#ifdef _SNMPv3
          cout << "         -snSecurityName, " << endl;
          cout << "         -slN , securityLevel to use, default N = 3 = authPriv" << endl;
          cout << "         -smN , securityModel to use, only default N = 3 = USM possible\n";
          cout << "         -cnContextName, default """"" << endl;
          cout << "         -ceContextEngineID, default """"" << endl;
          cout << "         -md5 , use MD5 authentication protocol\n";
          cout << "         -sha , use SHA authentication protocol\n";
          cout << "         -des , use DES privacy protocol\n";
          cout << "         -idea, use IDEA privacy protocol\n";
          cout << "         -aes128, use AES128 privacy protocol\n";
          cout << "         -aes192, use AES192 privacy protocol\n";
          cout << "         -aes256, use AES256 privacy protocol\n";
          cout << "         -uaAuthPassword\n";
          cout << "         -upPrivPassword\n";
#endif
	}
   //---------[ check the arg count ]----------------------------------------
   if ( argc < 2) {
	  
	  return 1;
   }

   Snmp::socket_startup();  // Initialize socket subsystem

   //---------[ make a GenAddress and Oid object to retrieve ]---------------
   UdpAddress address( argv[1]);      // make a SNMP++ Generic address
   if ( !address.valid()) {           // check validity of address
	  cout << "Invalid Address or DNS Name, " << argv[1] << "\n";
	  return 1;
   }
   Pdu pdu;                              // construct a Pdu object
   Vb vb;                                // construct a Vb object
   if ( argc >= 3) {                  // if 3 args, then use the callers Oid
	int i=2;
	while ((strstr(argv[i],"-")==0) && (i<argc)) {
		Oid oid(argv[i]);
		if ( !oid.valid()) {            // check validity of user oid
			cout << "Invalid Oid, " << argv[2] << "\n";
			return -2;
		}
		vb.set_oid(oid);
		pdu += vb;
		i++;
	}
   }
   else {
     Oid oid("1.3.6.1.2.1.1.1");      // default is sysDescr
     vb.set_oid(oid);
     pdu += vb;                            // add the vb to the Pdu
   }

   //jun add
   {
		Oid oid ("1.3.6.1.2.1.1.6.0");
		vb.set_oid(oid);
		pdu += vb;
		Oid oid2("1.3.6.1.2.1.1.3.0");
		vb.set_oid(oid2);
		pdu += vb;
		Oid oid3("1.3.6.1.2.1.1.5.0");
		vb.set_oid(oid3);
		pdu += vb;
		Oid oidx("1.3.6.1.2.1.1.5");
		vb.set_oid(oidx);
		pdu += vb;
		Oid oid4("1.3.6.1.2.1.25.5.1.1");
		vb.set_oid(oid4);
		pdu += vb;
   }
   //---------[ determine options to use ]-----------------------------------
   snmp_version version=version1;                  // default is v1
   int retries=1;                                  // default retries is 1
   int timeout=100;                                // default is 1 second
   u_short port=161;                               // default snmp port is 161
   OctetStr community("public");                   // community name
   int non_reps=2;                                 // non repeaters default is 0
   int max_reps=20;                                 // maximum repetitions default is 1

#ifdef _SNMPv3
   OctetStr privPassword("");
   OctetStr authPassword("");
   OctetStr securityName("");
   int securityModel = SecurityModel_USM;
   int securityLevel = SecurityLevel_authPriv;
   OctetStr contextName("");
   OctetStr contextEngineID("");
   long authProtocol = SNMPv3_usmNoAuthProtocol;
   long privProtocol = SNMPv3_usmNoPrivProtocol;
   v3MP *v3_MP;
#endif

   char *ptr;

   for(int x=1;x<argc;x++) {                           // parse for version
     if ( strstr( argv[x],"-v2")!= 0) {
       version = version2c;
       continue;
     }
     if ( strstr( argv[x],"-r")!= 0) {                 // parse for retries
       ptr = argv[x]; ptr++; ptr++;
       retries = atoi(ptr);
       if (( retries<0)|| (retries>5)) retries=1; 
       continue;
     }
     if ( strstr( argv[x], "-t")!=0) {                 // parse for timeout
       ptr = argv[x]; ptr++; ptr++;
       timeout = atoi( ptr);
       if (( timeout < 100)||( timeout>500)) timeout=100;
       continue;
     }
     if ( strstr( argv[x],"-n")!=0) {                 // parse for non repeaters
       ptr = argv[x];ptr++;ptr++;
       non_reps=atoi( ptr);
       if (( non_reps < 0)||( non_reps>10)) non_reps=0;
     }
     if ( strstr( argv[x],"-m")!=0) {                 // parse for max repetitions 
       ptr = argv[x];ptr++;ptr++;
       max_reps=atoi( ptr);
       if ( max_reps < 0) max_reps=1;
     }
     if ( strstr( argv[x],"-C")!=0) {
       ptr = argv[x]; ptr++; ptr++;
       community = ptr;
       continue;
     }
     if ( strstr( argv[x],"-p")!=0) {
       ptr = argv[x]; ptr++; ptr++;
       sscanf(ptr, "%hu", &port);
       continue;
     }

#ifdef _SNMPv3
     if ( strstr( argv[x],"-v3")!= 0) {
       version = version3;
       continue;
     }
     if ( strstr( argv[x],"-idea") != 0) {
       ptr = argv[x]; ptr++; ptr++;
       privProtocol = SNMPv3_usmIDEAPrivProtocol;
       continue;
     }
     if ( strstr( argv[x],"-aes128") != 0) {
       ptr = argv[x]; ptr++; ptr++;
       privProtocol = SNMPv3_usmAES128PrivProtocol;
       continue;
     }
     if ( strstr( argv[x],"-aes192") != 0) {
       ptr = argv[x]; ptr++; ptr++;
       privProtocol = SNMPv3_usmAES192PrivProtocol;
       continue;
     }
     if ( strstr( argv[x],"-aes256") != 0) {
       ptr = argv[x]; ptr++; ptr++;
       privProtocol = SNMPv3_usmAES256PrivProtocol;
       continue;
     }
     if ( strstr( argv[x],"-sha") != 0) {
       ptr = argv[x]; ptr++; ptr++;
       authProtocol = SNMPv3_usmHMACSHAAuthProtocol;
       continue;
     }
     if ( strstr( argv[x],"-des") != 0) {
       ptr = argv[x]; ptr++; ptr++;
       privProtocol = SNMPv3_usmDESPrivProtocol;
       continue;
     }
     if ( strstr( argv[x],"-md5") != 0) {
       ptr = argv[x]; ptr++; ptr++;
       authProtocol = SNMPv3_usmHMACMD5AuthProtocol;
       continue;
     }
     if ( strstr( argv[x],"-sn")!=0) {
       ptr = argv[x]; ptr+=3;
       securityName = ptr;
       continue;
      }
     if ( strstr( argv[x], "-sl")!=0) {
       ptr = argv[x]; ptr+=3;
       securityLevel = atoi( ptr);
       if (( securityLevel < SecurityLevel_noAuthNoPriv) ||
           ( securityLevel > SecurityLevel_authPriv))
         securityLevel = SecurityLevel_authPriv;
       continue;
     }
     if ( strstr( argv[x], "-sm")!=0) {
       ptr = argv[x]; ptr+=3;
       securityModel = atoi( ptr);
       if (( securityModel < SecurityModel_v1) ||
           ( securityModel > SecurityModel_USM))
         securityModel = SecurityModel_USM;
       continue;
     }
     if ( strstr( argv[x],"-cn")!=0) {
       ptr = argv[x]; ptr+=3;
       contextName = ptr;
       continue;
     }
     if ( strstr( argv[x],"-ce")!=0) {
       ptr = argv[x]; ptr+=3;
       contextEngineID = ptr;
       continue;
     }
     if ( strstr( argv[x],"-ua")!=0) {
       ptr = argv[x]; ptr+=3;
       authPassword = ptr;
       continue;
     }
     if ( strstr( argv[x],"-up")!=0) {
       ptr = argv[x]; ptr+=3;
       privPassword = ptr;
       continue;
     }
#endif
  }

   //----------[ create a SNMP++ session ]-----------------------------------
   int status;
   // bind to any port and use IPv6 if needed
   Snmp snmp(status, 0, (address.get_ip_version() == Address::version_ipv6));

   if ( status != SNMP_CLASS_SUCCESS) {
      cout << "SNMP++ Session Create Fail, " << snmp.error_msg(status) << "\n";
      return 1;
   }

   //---------[ init SnmpV3 ]--------------------------------------------
#ifdef _SNMPv3
   if (version == version3) {
     char *engineId = "snmpBulk";
     char *filename = "snmpv3_boot_counter";
     unsigned int snmpEngineBoots = 0;
     int status;

     status = getBootCounter(filename, engineId, snmpEngineBoots);
     if ((status != SNMPv3_OK) && (status < SNMPv3_FILEOPEN_ERROR))
     {
       cout << "Error loading snmpEngineBoots counter: " << status << endl;
       return 1;
     }
     snmpEngineBoots++;
     status = saveBootCounter(filename, engineId, snmpEngineBoots);
     if (status != SNMPv3_OK)
     {
       cout << "Error saving snmpEngineBoots counter: " << status << endl;
       return 1;
     }

     int construct_status;
     v3_MP = new v3MP(engineId, snmpEngineBoots, construct_status);

     USM *usm = v3_MP->get_usm();
     usm->add_usm_user(securityName,
		       authProtocol, privProtocol,
		       authPassword, privPassword);
   }
   else
   {
     // MUST create a dummy v3MP object if _SNMPv3 is enabled!
     int construct_status;
     v3_MP = new v3MP("dummy", 0, construct_status);
   }
#endif

   //--------[ build up SNMP++ object needed ]-------------------------------
   address.set_port(port);
   CTarget ctarget( address);             // make a target using the address
#ifdef _SNMPv3
   UTarget utarget( address);

   if (version == version3) {
     utarget.set_version( version);          // set the SNMP version SNMPV1 or V2 or V3
     utarget.set_retry( retries);            // set the number of auto retries
     utarget.set_timeout( timeout);          // set timeout
     utarget.set_security_model( securityModel);
     utarget.set_security_name( securityName);
     pdu.set_security_level( securityLevel);
     pdu.set_context_name (contextName);
     pdu.set_context_engine_id(contextEngineID);
   }
   else {
#endif
     ctarget.set_version( version);         // set the SNMP version SNMPV1 or V2
     ctarget.set_retry( retries);           // set the number of auto retries
     ctarget.set_timeout( timeout);         // set timeout
     ctarget.set_readcommunity( community); // set the read community name
#ifdef _SNMPv3
   }
#endif

   //-------[ issue the request, blocked mode ]-----------------------------
   cout << "SNMP++ GetBulk to " << argv[1] << " SNMPV" 
#ifdef _SNMPv3
        << ((version==version3) ? (version) : (version+1))
#else
        << (version+1)
#endif
        << " Retries=" << retries
	<< " Timeout=" << timeout << "ms"
	<< " Non Reptrs=" << non_reps
	<< " Max Reps=" << max_reps << endl;
#ifdef _SNMPv3
   if (version == version3)
     cout << endl
          << "securityName= " << securityName.get_printable()
          << ", securityLevel= " << securityLevel
          << ", securityModel= " << securityModel << endl
          << "contextName= " << contextName.get_printable()
          << ", contextEngineID= " << contextEngineID.get_printable()
          << endl;
   else
#endif
     cout << " Community=" << community.get_printable() << endl << flush;

   SnmpTarget *target;
#ifdef _SNMPv3
   if (version == version3)
     target = &utarget;
   else
#endif
     target = &ctarget;
   Pdu pdu2 = pdu;

   if (( status = snmp.get_bulk( pdu,*target,non_reps,max_reps))== SNMP_CLASS_SUCCESS) {
     for ( int z=0;z<pdu.get_vb_count();z++) {
       pdu.get_vb( vb,z);
#ifdef _SNMPv3
       if (pdu.get_type() == REPORT_MSG) {
         Oid tmp;
         vb.get_oid(tmp);
         cout << "Received a reportPdu: "
              << snmp.error_msg( tmp) 
              << endl
              << vb.get_printable_oid() << " = "
              << vb.get_printable_value() << endl;
       }
#endif
       cout << "Oid = " << vb.get_printable_oid() << "\n";
       if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW) {
	 cout << "Value = " << vb.get_printable_value() << "\n\n";
       }
       else {
	 cout << "End of MIB view.\n\n";
       }
     }
   }
   else
     cout << "SNMP++ GetBulk Error, " << snmp.error_msg( status) << "\n";

   pdu = pdu2;
//--------------------
   if (( status = snmp.get_bulk( pdu,*target,non_reps,max_reps))== SNMP_CLASS_SUCCESS) {
     for ( int z=0;z<pdu.get_vb_count();z++) {
       pdu.get_vb( vb,z);
#ifdef _SNMPv3
       if (pdu.get_type() == REPORT_MSG) {
         Oid tmp;
         vb.get_oid(tmp);
         cout << "Received a reportPdu: "
              << snmp.error_msg( tmp) 
              << endl
              << vb.get_printable_oid() << " = "
              << vb.get_printable_value() << endl;
       }
#endif
       cout << "Oid = " << vb.get_printable_oid() << "\n";
       if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW) {
	 cout << "Value = " << vb.get_printable_value() << "\n\n";
	 
       }
       else {
	 cout << "End of MIB view.\n\n";
       }
     }
   }
   else
     cout << "SNMP++ GetBulk Error, " << snmp.error_msg( status) << "\n";
   //-------------


   Snmp::socket_cleanup();  // Shut down socket subsystem
}
//------------[ convert SNMP++ VB to WinSNMP smiVALUE ]----------------
int convertVbToSmival( const Vb &tempvb, SmiVALUE *smival )
{
  smival->syntax = tempvb.get_syntax();
  switch ( smival->syntax ) {

    // case sNMP_SYNTAX_NULL
  case sNMP_SYNTAX_NULL:
  case sNMP_SYNTAX_NOSUCHOBJECT:
  case sNMP_SYNTAX_NOSUCHINSTANCE:
  case sNMP_SYNTAX_ENDOFMIBVIEW:
    break;

    // case sNMP_SYNTAX_INT32:
  case sNMP_SYNTAX_INT:
    tempvb.get_value(smival->value.sNumber);
    break;

    //    case sNMP_SYNTAX_UINT32:
  case sNMP_SYNTAX_GAUGE32:
  case sNMP_SYNTAX_CNTR32:
  case sNMP_SYNTAX_TIMETICKS:
    //  case sNMP_SYNTAX_UINT32:
    tempvb.get_value(smival->value.uNumber);
    break;

    // case Counter64
  case sNMP_SYNTAX_CNTR64:
    {
      Counter64 c64;
      tempvb.get_value(c64);
      smival->value.hNumber.hipart = c64.high();
      smival->value.hNumber.lopart = c64.low();
    }
    break;

  case sNMP_SYNTAX_BITS:
  case sNMP_SYNTAX_OCTETS:
  case sNMP_SYNTAX_OPAQUE:
  case sNMP_SYNTAX_IPADDR:
    {
      OctetStr os;
      tempvb.get_value(os);
      smival->value.string.ptr = NULL;
      smival->value.string.len = os.len();
      if ( smival->value.string.len > 0 )
      {
        smival->value.string.ptr
          = (SmiLPBYTE) new  unsigned char [smival->value.string.len];
        if ( smival->value.string.ptr )
        {
          for (int i=0; i<(int) smival->value.string.len ; i++)
            smival->value.string.ptr[i] = os[i];
        }
        else
        {
          smival->syntax = sNMP_SYNTAX_NULL;  // invalidate the smival
          return SNMP_CLASS_RESOURCE_UNAVAIL;
        }
      }
    }
    break;

  case sNMP_SYNTAX_OID:
    {
      Oid oid;
      tempvb.get_value(oid);
      smival->value.oid.ptr = NULL;
      smival->value.oid.len = oid.len();
      if ( smival->value.oid.len > 0 )
      {
        smival->value.oid.ptr
          = (SmiLPUINT32) new unsigned long [ smival->value.oid.len];
        if ( smival->value.oid.ptr )
        {
          for (int i=0; i<(int)smival->value.oid.len ; i++)
            smival->value.oid.ptr[i] = oid[i];
        }
        else
        {
          smival->syntax = sNMP_SYNTAX_NULL;  // invalidate the smival
          return SNMP_CLASS_RESOURCE_UNAVAIL;
        }
      }
    }
    break;

  default:
    return SNMP_CLASS_INTERNAL_ERROR;
  }
  return SNMP_CLASS_SUCCESS;
}
Example #10
0
void* runable(void *data) {
  //--------[ build up SNMP++ object needed ]-------------------------------
  ssync.lock();
  printf("HELLO:%s\n", community.get_printable());
  int t = *((int*)data);
  Pdu pdu;                              // construct a Pdu object
  Vb vb;                                // construct a Vb object
  vb.set_oid("1");                     // set the Oid portion of the Vb
  pdu += vb;                            // add the vb to the Pdu
  CTarget ctarget(address[t]);            // make a target using the address
#ifdef _SNMPv3
  UTarget utarget(address[t]);

  if (version == version3) {
    utarget.set_version( version);          // set the SNMP version SNMPV1 or V2 or V3
    utarget.set_retry( retries);            // set the number of auto retries
    utarget.set_timeout( timeout);          // set timeout
    utarget.set_security_model( securityModel);
    utarget.set_security_name( securityName);
    pdu.set_security_level( securityLevel);
    pdu.set_context_name (contextName);
    pdu.set_context_engine_id(contextEngineID);
  }
  else {
#endif
    ctarget.set_version( version);          // set the SNMP version SNMPV1 or V2 or V3
    ctarget.set_retry( retries);            // set the number of auto retries
    ctarget.set_timeout( timeout);          // set timeout
    ctarget.set_readcommunity( community);  // set the read community to use
    ctarget.set_writecommunity( community);
#ifdef _SNMPv3
  }
#endif

  //-------[ issue the request, blocked mode ]-----------------------------
  cout << "(" << t << "): " 
       << "SNMP++ snmpWalk to " << address[t].get_printable() << " SNMPV" 
#ifdef _SNMPv3
       << ((version==version3) ? (version) : (version+1)) 
#else
       << (version+1) 
#endif
       << " Retries=" << retries
       << " Timeout=" << timeout <<"ms";
#ifdef _SNMPv3
  if (version == version3)
    cout << endl 
	 << "securityName= " << securityName.get_printable()
	 << ", securityLevel= " << securityLevel
	 << ", securityModel= " << securityModel << endl
	 << "contextName= " << contextName.get_printable()
	 << ", contextEngineID= " << contextEngineID.get_printable()
	 << endl;
  else
#endif
    cout << " Community=" << community.get_printable() << endl << flush;

  SnmpTarget *target;
#ifdef _SNMPv3
  if (version == version3)
    target = &utarget;
  else
#endif
    target = &ctarget;

  int status = 0;
  int requests = 0;
  int objects = 0;
  ssync.unlock();
  while (( status = snmp->get_bulk( pdu,*target,0,BULK_MAX))
	 == SNMP_CLASS_SUCCESS)
  {
    requests++;
    ssync.lock();
    for ( int z=0;z<pdu.get_vb_count(); z++) {
      pdu.get_vb( vb,z);
#ifdef _SNMPv3
      if (pdu.get_type() == REPORT_MSG) {
	Oid tmp;
	vb.get_oid(tmp);
	cout << "(" << t << "): " << "Received a reportPdu: "
	     << snmp->error_msg( tmp) 
	     << endl
	     << vb.get_printable_oid() << " = "
	     << vb.get_printable_value() << endl;
	ssync.unlock();
	return 0;
      }
#endif
      objects++;
      // look for var bind exception, applies to v2 only   
      if ( vb.get_syntax() != sNMP_SYNTAX_ENDOFMIBVIEW) {
	cout <<  "(" << t << "): " 
	     << vb.get_printable_oid() << " = ";
	cout << vb.get_printable_value() << "\n";
      }
      else {
	cout <<  "(" << t << "): " 
	     << "End of MIB Reached\n";
	cout <<  "(" << t << "): " 
	     << "Total # of Requests = " << requests << "\n";
	cout <<  "(" << t << "): "
	     << "Total # of Objects  = " << objects  << "\n";
	ssync.unlock();
	return 0;
      }
    }
    ssync.unlock();
    // last vb becomes seed of next rquest
    pdu.set_vblist(&vb, 1);
  }
  if ( status != SNMP_ERROR_NO_SUCH_NAME)
    cout <<  "(" << t << "): "
	 << "SNMP++ snmpWalk Error, " << snmp->error_msg( status) << "\n";
  cout <<  "(" << t << "): "
       << "Total # of Requests = " << requests << "\n";
  cout <<  "(" << t << "): "
       << "Total # of Objects  = " << objects  << "\n";
  return 0;
}  // end Walk