Esempio n. 1
0
/////////////////////////////////////////////////////////////////////////////
// 函数:SetRequest                                                        //
// 说明:设置简单变量的结果                                                //
// 参数:无                                                                //
// 返回值:                                                                //
//      成功返回0,否则返回一个非0 值                                      //
/////////////////////////////////////////////////////////////////////////////
int BasicSNMP::SetRequest()
{
	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
	vb.set_value(m_nOIDValue);                      // set the Oid portion of the Vb
	pdu += vb;   

	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
	}

	nResult = pSnmp->set(pdu,*target);//Get Reques

	return nResult;
}
Esempio n. 2
0
// issue a GET-NEXT request
void MainWindow::push_button_get_next_clicked()
{
  int status;

  if (!snmp)
    return;

  push_button_get_next->setEnabled(false);

  // Create a Oid and a address object from the entered values
  Oid oid(line_edit_obj_id->text());
  UdpAddress address(line_edit_target->text());

  // check if the address is valid
  // One problem here: if a hostname is entered, a blocking DNS lookup
  // is done by the address object.
  if (!address.valid())
  {
    QString err = QString("\nInvalid Address or DNS Name: %1\n")
                .arg(line_edit_target->text());
    text_edit_output->append(err);
    push_button_get_next->setEnabled(true);
    return;
  }

  Pdu pdu; // empty Pdu
  Vb vb;   // empty Vb
  SnmpTarget *target; // will point to a CTarget(v1/v2c) or UTarget (v3)

  // Set the Oid part of the Vb
  vb.set_oid(oid);

  // Add the Vb to the Pdu
  pdu += vb;

  // Get retries and timeout values
  int retries = spin_box_retries->value();
  int timeout = 100 * spin_box_timeout->value();
  
  if (radio_button_v3->isChecked())
  {
    // For SNMPv3 we need a UTarget object
    UTarget *utarget = new UTarget(address);

    utarget->set_version(version3);

    utarget->set_security_model(SNMP_SECURITY_MODEL_USM);
    utarget->set_security_name(combo_box_sec_name->currentText());
    
    target = utarget;

    // set the security level to use
    if (combo_box_sec_level->currentText() == "noAuthNoPriv")
      pdu.set_security_level(SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV);
    else if (combo_box_sec_level->currentText() == "authNoPriv")
      pdu.set_security_level(SNMP_SECURITY_LEVEL_AUTH_NOPRIV);
    else
      pdu.set_security_level(SNMP_SECURITY_LEVEL_AUTH_PRIV);

    // Not needed, as snmp++ will set it, if the user does not set it
    pdu.set_context_name(line_edit_context_name->text());
    pdu.set_context_engine_id(line_edit_context_engine_id->text());
  }
  else
  {
    // For SNMPv1/v2c we need a CTarget
    CTarget *ctarget = new CTarget(address);

    if (radio_button_v2->isChecked())
      ctarget->set_version(version2c);
    else
      ctarget->set_version(version1);

    // set the community
    ctarget->set_readcommunity( line_edit_community->text());

    target = ctarget;
  }

  target->set_retry(retries);            // set the number of auto retries
  target->set_timeout(timeout);          // set timeout

  // Now do an async get_next
  status = snmp->get_next(pdu, *target, callback, this);

  // Could we send it?
  if (status == SNMP_CLASS_SUCCESS)
  {
    timer.start(100);
  }
  else
  {
    QString err = QString("\nCould not send async GETNEXT request: %1\n")
                         .arg(Snmp::error_msg(status));
    text_edit_output->append(err);
    push_button_get_next->setEnabled(true);
  }

  // the target is no longer needed
  delete target;
}
Esempio n. 3
0
int main(int argc, char **argv)
{
    //---------[ check the arg count ]----------------------------------------
    if ( argc < 2) {
        cout << "Usage:\n";
        cout << argv[0] << " IpAddress | DNSName [Oid] [options]\n";
        cout << "Oid: sysDescr object is default\n";
        cout << "options: -vN , use SNMP version 1, 2 or 3, default is 1\n";
        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";
#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 empty string" << endl;
        cout << "         -ceContextEngineID, as hex e.g. 800007E580, default empty string" << endl;
        cout << "         -authPROT, use authentication protocol NONE, SHA or MD5\n";
        cout << "         -privPROT, use privacy protocol NONE, DES, 3DESEDE, IDEA, AES128, AES192 or AES256\n";
        cout << "         -uaAuthPassword\n";
        cout << "         -upPrivPassword\n";
#endif
        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;
    }
    Oid oid("1.3.6.1.2.1.1.1");      // default is sysDescr
    if ( argc >= 3) {                  // if 3 args, then use the callers Oid
        if ( strstr( argv[2],"-")==0) {
            oid = argv[2];
            if ( !oid.valid()) {            // check validity of user oid
                cout << "Invalid Oid, " << argv[2] << "\n";
                return 1;
            }
        }
    }

    //---------[ 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

#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],"-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],"-auth") != 0) {
            ptr = argv[x];
            ptr+=5;
            if (strcasecmp(ptr, "SHA") == 0)
                authProtocol = SNMP_AUTHPROTOCOL_HMACSHA;
            else if (strcasecmp(ptr, "MD5") == 0)
                authProtocol = SNMP_AUTHPROTOCOL_HMACMD5;
            else
                authProtocol = SNMP_AUTHPROTOCOL_NONE;
            continue;
        }
        if ( strstr( argv[x],"-priv") != 0) {
            ptr = argv[x];
            ptr+=5;
            if (strcasecmp(ptr, "DES") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_DES;
            else if (strcasecmp(ptr, "3DESEDE") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_3DESEDE;
            else if (strcasecmp(ptr, "IDEA") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_IDEA;
            else if (strcasecmp(ptr, "AES128") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_AES128;
            else if (strcasecmp(ptr, "AES192") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_AES192;
            else if (strcasecmp(ptr, "AES256") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_AES256;
            else
                privProtocol = SNMP_PRIVPROTOCOL_NONE;
            printf("\n\nPrivProt : %ld\n", privProtocol);
            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 = OctetStr::from_hex_string(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 = "snmpNextAsync";
        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 ]-------------------------------
    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

    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++ GetNext to " << argv[1] << " SNMPV"
#ifdef _SNMPv3
         << ((version==version3) ? (version) : (version+1))
#else
         << (version+1)
#endif
         << " Retries=" << retries
         << " Timeout=" << timeout * 10 <<"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;

    status = snmp.get_next( pdu, *target, callback,NULL);

    if (status == SNMP_CLASS_SUCCESS)
    {
        cout << "Async GetNext Request sent." << endl;
    }
    else
        cout << "SNMP++ GetNext Error, " << snmp.error_msg( status)
             << " (" << status <<")" << endl ;

    for (int t=1; t<=10; t++)
    {
        snmp.eventListHolder->SNMPProcessPendingEvents();
#ifdef WIN32
        Sleep(1000);
#else
        sleep(1);
#endif
    }

    Snmp::socket_cleanup();  // Shut down socket subsystem
}
Esempio n. 4
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;
}
Esempio n. 5
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;
}
Esempio n. 6
0
int main(int argc, char **argv)
{
   //---------[ check the arg count ]----------------------------------------
   if ( argc < 4 )
     usage();
   if ( strstr( argv[1],"-h") != 0 )
     help();
   if ( strstr( argv[1],"-?") != 0 )
     usage();

#if !defined(_NO_LOGGING) && !defined(WITH_LOG_PROFILES)
   // Set filter for logging
   DefaultLog::log()->set_filter(ERROR_LOG, 7);
   DefaultLog::log()->set_filter(WARNING_LOG, 7);
   DefaultLog::log()->set_filter(EVENT_LOG, 7);
   DefaultLog::log()->set_filter(INFO_LOG, 7);
   DefaultLog::log()->set_filter(DEBUG_LOG, 7);
#endif

   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";
	  usage();
   }

   OctetStr newUser, newPassword;
   if (((strstr( argv[2],"-")==0) && (strstr( argv[3],"-")==0))) {
	newUser = argv[2];
	newPassword = argv[3];
   }
   else
   {
     cout << "wrong parameters..." << endl;
     return 1;
   }

   //---------[ 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

   OctetStr privPassword("");
   OctetStr authPassword("");
   OctetStr securityName("");
   int securityModel = SNMP_SECURITY_MODEL_USM;
   int securityLevel = SNMP_SECURITY_LEVEL_AUTH_PRIV;
   OctetStr contextName("");
   OctetStr contextEngineID("");
   long authProtocol = SNMP_AUTHPROTOCOL_NONE;
   long privProtocol = SNMP_PRIVPROTOCOL_NONE;
   OctetStr engineID;
   v3MP *v3_MP;

   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],"-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 WITH_LOG_PROFILES
     if ( strstr( argv[x], "-L" ) != 0 ) {
       ptr = argv[x]; ptr++; ptr++;
       DefaultLog::log()->set_profile(ptr);
     }
#endif

     if ( strstr( argv[x],"-v3")!= 0) {
       version = version3;
       continue;
     }
     if ( strstr( argv[x],"-auth") != 0) {
       ptr = argv[x]; ptr+=5;
       if (strcasecmp(ptr, "SHA") == 0)
	 authProtocol = SNMP_AUTHPROTOCOL_HMACSHA;
       else if (strcasecmp(ptr, "MD5") == 0)
	 authProtocol = SNMP_AUTHPROTOCOL_HMACMD5;
       else if (strcasecmp(ptr, "NONE") == 0)
	 authProtocol = SNMP_AUTHPROTOCOL_NONE;
       else
	 cout << "Warning: ignoring unknown auth protocol: " << ptr << endl;
       continue;
     }
     if ( strstr( argv[x],"-priv") != 0) {
       ptr = argv[x]; ptr+=5;
       if (strcasecmp(ptr, "DES") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_DES;
       else if (strcasecmp(ptr, "3DESEDE") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_3DESEDE;
       else if (strcasecmp(ptr, "IDEA") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_IDEA;
       else if (strcasecmp(ptr, "AES128") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_AES128;
       else if (strcasecmp(ptr, "AES192") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_AES192;
       else if (strcasecmp(ptr, "AES256") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_AES256;
       else if (strcasecmp(ptr, "NONE") == 0)
	   privProtocol = SNMP_PRIVPROTOCOL_NONE;
       else
	 cout << "Warning: ignoring unknown priv protocol: " << ptr << endl;
       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 < SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV) ||
           ( securityLevel > SNMP_SECURITY_LEVEL_AUTH_PRIV))
         securityLevel = SNMP_SECURITY_LEVEL_AUTH_PRIV;
       continue;
     }
     if ( strstr( argv[x], "-sm")!=0) {
       ptr = argv[x]; ptr+=3;
       securityModel = atoi( ptr);
       if (( securityModel < SNMP_SECURITY_MODEL_V1) ||
           ( securityModel > SNMP_SECURITY_MODEL_USM))
         securityModel = SNMP_SECURITY_MODEL_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 = OctetStr::from_hex_string(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;
     }
     if ( strstr( argv[x],"-e")!=0) {
       ptr = argv[x]; ptr+=2;
       engineID = OctetStr::from_hex_string(ptr);
       continue;
     }
   }

   //----------[ 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 ]--------------------------------------------
   if (version == version3) {
     OctetStr engineId = "snmpPasswd";
     const 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);
     if (construct_status != SNMPv3_MP_OK)
     {
       cout << "Error initializing v3MP: " << construct_status << endl;
       return 1;
     }

     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);
   }

   //--------[ build up SNMP++ object needed ]-------------------------------
   Pdu pdu;                               // construct a Pdu object
   Vb vb;                                 // construct a Vb object
   vb.set_oid(Oid("1.3.6.1.2.1.1.1.0"));  // 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
   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 {
     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
   }

   //-------[ issue the request, blocked mode ]-----------------------------
   cout << "SNMP++ Get to " << argv[1] << " SNMPV" 

        << ((version==version3) ? (version) : (version+1)) 
        << " Retries=" << retries
        << " Timeout=" << timeout * 10 <<"ms"; 
   if (version == version3)
     cout << endl
          << "securityName= " << securityName.get_printable()
          << ", securityLevel= " << securityLevel
          << ", securityModel= " << securityModel << endl
          << "contextName= " << contextName.get_printable()
          << ", contextEngineID= " << contextEngineID.get_printable()
          << endl;
   else
     cout << " Community=" << community.get_printable() << endl << flush;

   SnmpTarget *target;
   if (version == version3)
     target = &utarget;
   else
     target = &ctarget;
   Pdu pduKeyChange;
   if (version == version3) {
     pduKeyChange.set_security_level( securityLevel);
     pduKeyChange.set_context_name (contextName);
     pduKeyChange.set_context_engine_id(contextEngineID);
   }
   
   snmp.get( pdu, *target);

   KeyChange(&snmp, pduKeyChange, newUser, newPassword, *target, AUTHKEY);

   Snmp::socket_cleanup();  // Shut down socket subsystem
} 
Esempio n. 7
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;
}
Esempio n. 8
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;
}
Esempio n. 9
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;
}
Esempio n. 10
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
}
Esempio n. 11
0
// unload the data into SNMP++ objects
int SnmpMessage::unload(Pdu &pdu,                 // Pdu object
			OctetStr &community,      // community object
			snmp_version &version,    // SNMP version #
                        OctetStr *engine_id,      // optional v3
                        OctetStr *security_name,  // optional v3
                        long int *security_model,
                        UdpAddress *from_addr,
                        Snmp *snmp_session)
{
  pdu.clear();

  if (!valid_flag)
    return SNMP_CLASS_INVALID;

  snmp_pdu *raw_pdu;
  raw_pdu = snmp_pdu_create(0); // do a "snmp_free_pdu( raw_pdu)" before return

  int status;

#ifdef _SNMPv3
  OctetStr context_engine_id;
  OctetStr context_name;
  long int security_level = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV;

  if ((security_model) && (security_name) && (engine_id) && (snmp_session)) {
    status = v3MP::I->snmp_parse(snmp_session, raw_pdu,
                         databuff, (int)bufflen, *engine_id,
                         *security_name, context_engine_id, context_name,
                         security_level, *security_model, version, *from_addr);
    if (status != SNMPv3_MP_OK) {
      pdu.set_request_id( raw_pdu->reqid);
      pdu.set_type( raw_pdu->command);
      snmp_free_pdu( raw_pdu);
      return status;
    }
    pdu.set_context_engine_id(context_engine_id);
    pdu.set_context_name(context_name);
    pdu.set_security_level(security_level);
    pdu.set_message_id(raw_pdu->msgid);
    pdu.set_maxsize_scopedpdu(raw_pdu->maxsize_scopedpdu);
  }
  else {
#endif
    unsigned char community_name[MAX_LEN_COMMUNITY + 1];
    int           community_len = MAX_LEN_COMMUNITY + 1;

    status = snmp_parse(raw_pdu, databuff, (int) bufflen,
                        community_name, community_len, version);
    if (status != SNMP_CLASS_SUCCESS) {
      snmp_free_pdu(raw_pdu);
      return status;
    }
    community.set_data( community_name, community_len);

#ifdef _SNMPv3
  }
#endif
  // load up the SNMP++ variables
  pdu.set_request_id(raw_pdu->reqid);
  pdu.set_error_status((int) raw_pdu->errstat);
  pdu.set_error_index((int) raw_pdu->errindex);
  pdu.set_type( raw_pdu->command);

  // deal with traps a little different
  if ( raw_pdu->command == sNMP_PDU_V1TRAP) {
    // timestamp
    TimeTicks timestamp;
    timestamp = raw_pdu->time;
    pdu.set_notify_timestamp( timestamp);

    // set the agent address
    IpAddress agent_addr(inet_ntoa(raw_pdu->agent_addr.sin_addr));
    if (agent_addr != "0.0.0.0")
    {
      pdu.set_v1_trap_address(agent_addr);

      LOG_BEGIN(DEBUG_LOG | 4);
      LOG("SNMPMessage: Trap address of received v1 trap");
      LOG(agent_addr.get_printable());
      LOG_END;
    }

    // set enterprise, notifyid
    Oid enterprise;

    if (raw_pdu->enterprise_length >0) {
      for (int i=0; i< raw_pdu->enterprise_length; i++) {
        enterprise += (int) (raw_pdu->enterprise[i]);
      }
      pdu.set_notify_enterprise(enterprise);
    }
    switch (raw_pdu->trap_type) {
    case 0:
      pdu.set_notify_id(coldStart);
      break;

    case 1:
      pdu.set_notify_id(warmStart);
      break;

    case 2:
      pdu.set_notify_id(linkDown);
      break;

    case 3:
      pdu.set_notify_id(linkUp);
      break;

    case 4:
      pdu.set_notify_id(authenticationFailure);
      break;

    case 5:
      pdu.set_notify_id(egpNeighborLoss);
      break;

    case 6: { // enterprise specific
      // base id + specific #
      Oid eOid = enterprise;
      eOid += 0ul;
      eOid += raw_pdu->specific_type;
      pdu.set_notify_id( eOid);
      break;
      }
    default:
      {
	LOG_BEGIN(WARNING_LOG | 3);
	LOG("SNMPMessage: Received trap with illegal trap type");
	LOG(raw_pdu->trap_type);
	LOG_END;
      }
    }
  }

  // vbs
  Vb tempvb;
  Oid tempoid;
  struct   variable_list *vp;
  int vb_nr = 1;

  for(vp = raw_pdu->variables; vp; vp = vp->next_variable, vb_nr++) {

    // extract the oid portion
    tempoid.set_data( (unsigned long *)vp->name,
                      ( unsigned int) vp->name_length);
    tempvb.set_oid( tempoid);

    // extract the value portion
    switch(vp->type){

      // octet string
    case sNMP_SYNTAX_OCTETS:
      {
	OctetStr octets( (unsigned char *) vp->val.string,
			 (unsigned long) vp->val_len);
	tempvb.set_value( octets);
      }
      break;
    case sNMP_SYNTAX_OPAQUE:
      {
	OpaqueStr octets( (unsigned char *) vp->val.string,
		          (unsigned long) vp->val_len);
	tempvb.set_value( octets);
      }
      break;

      // object id
    case sNMP_SYNTAX_OID:
      {
	Oid oid( (unsigned long*) vp->val.objid,
		 (int) vp->val_len);
	tempvb.set_value( oid);
        if ((vb_nr == 2) &&
            ((raw_pdu->command == sNMP_PDU_TRAP) ||
             (raw_pdu->command == sNMP_PDU_INFORM)) &&
            (tempoid == SNMP_MSG_OID_TRAPID))
        {
          // set notify_id
          pdu.set_notify_id(oid);
	  continue; // don't add vb to pdu
        }
      }
      break;

      // timeticks
    case sNMP_SYNTAX_TIMETICKS:
      {
	TimeTicks timeticks( (unsigned long) *(vp->val.integer));
	tempvb.set_value( timeticks);
        if ((vb_nr == 1) &&
            ((raw_pdu->command == sNMP_PDU_TRAP) ||
             (raw_pdu->command == sNMP_PDU_INFORM)) &&
            (tempoid == SNMP_MSG_OID_SYSUPTIME))
        {
          // set notify_timestamp
          pdu.set_notify_timestamp( timeticks);
	  continue; // don't add vb to pdu
        }
      }
      break;

      // 32 bit counter
    case sNMP_SYNTAX_CNTR32:
      {
	Counter32 counter32( (unsigned long) *(vp->val.integer));
	tempvb.set_value( counter32);
      }
      break;

      // 32 bit gauge
    case sNMP_SYNTAX_GAUGE32:
      {
	Gauge32 gauge32( (unsigned long) *(vp->val.integer));
	tempvb.set_value( gauge32);
      }
      break;

      // ip address
    case sNMP_SYNTAX_IPADDR:
      {
	char buffer[42];

	if (vp->val_len == 16)
	  sprintf( buffer, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
		   "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
		   vp->val.string[ 0], vp->val.string[ 1], vp->val.string[ 2],
		   vp->val.string[ 3], vp->val.string[ 4], vp->val.string[ 5],
		   vp->val.string[ 6], vp->val.string[ 7], vp->val.string[ 8],
		   vp->val.string[ 9], vp->val.string[10], vp->val.string[11],
		   vp->val.string[12], vp->val.string[13], vp->val.string[14],
		   vp->val.string[15]);
	else
	  sprintf( buffer,"%d.%d.%d.%d",
		   vp->val.string[0], vp->val.string[1],
		   vp->val.string[2], vp->val.string[3]);
	IpAddress ipaddress( buffer);
	tempvb.set_value( ipaddress);
      }
      break;

      // 32 bit integer
    case sNMP_SYNTAX_INT:
      {
	SnmpInt32 int32( (long) *(vp->val.integer));
	tempvb.set_value( int32);
      }
      break;

      // 32 bit unsigned integer
/* Not distinguishable from Gauge32
    case sNMP_SYNTAX_UINT32:
      {
	SnmpUInt32 uint32( (unsigned long) *(vp->val.integer));
	tempvb.set_value( uint32);
      }
      break;
*/
      // v2 counter 64's
    case sNMP_SYNTAX_CNTR64:
      { // Frank Fock (was empty before)
	Counter64 c64(((counter64*)vp->val.counter64)->high,
		      ((counter64*)vp->val.counter64)->low);
	tempvb.set_value( c64);
	break;
      }
    case sNMP_SYNTAX_NULL:
	    tempvb.set_null();
	    break;
	
	    // v2 vb exceptions
    case sNMP_SYNTAX_NOSUCHOBJECT:
    case sNMP_SYNTAX_NOSUCHINSTANCE:
    case sNMP_SYNTAX_ENDOFMIBVIEW:
      tempvb.set_exception_status(vp->type);
      break;

    default:
      tempvb.set_null();

    } // end switch

    // append the vb to the pdu
    pdu += tempvb;
  }

  snmp_free_pdu( raw_pdu);

  return SNMP_CLASS_SUCCESS;
}
Esempio n. 12
0
int main(int argc, char **argv)
{
    //---------[ check the arg count ]----------------------------------------
    if ( argc < 2) {
        cout << "Usage:\n";
        cout << "snmpTraps IpAddress | DNSName [Id] [options]\n";
        cout << "Id = default is 1.3.6.1.6.3.1.1.5.1 = ColdStart";
        cout << "options: -vN , use SNMP version 1, 2 or 3, default is 1\n";
        cout << "         -PPort , remote port to use\n";
        cout << "         -CCommunity_name, specify community default is 'public' \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 empty string" << endl;
        cout << "         -ceContextEngineID, as hex e.g. 800007E580, default empty string" << endl;
        cout << "         -authPROT, use authentication protocol NONE, SHA or MD5\n";
        cout << "         -privPROT, use privacy protocol NONE, DES, 3DESEDE, IDEA, AES128, AES192 or AES256\n";
        cout << "         -uaAuthPassword\n";
        cout << "         -upPrivPassword\n";
#endif
        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;
    }
    Oid oid( COLDSTART);    // default is ColdStart
    if ( argc >= 3) {                  // if 3 args, then use the callers Oid
        if ( strstr( argv[2],"-")==0) {
            oid = argv[2];
            if ( !oid.valid()) {            // check validity of user oid
                cout << "Invalid Oid, " << argv[2] << "\n";
                return 1;
            }
        }
    }

    //---------[ determine options to use ]-----------------------------------
    snmp_version version=version1;                  // default is v1
    u_short port=161;                               // default snmp port is 161
    OctetStr community("public");                   // community name
    Oid ent(ENTERPRISE);                            // default enterprise

#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],"-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],"-auth") != 0) {
            ptr = argv[x];
            ptr+=5;
            if (strcasecmp(ptr, "SHA") == 0)
                authProtocol = SNMP_AUTHPROTOCOL_HMACSHA;
            else if (strcasecmp(ptr, "MD5") == 0)
                authProtocol = SNMP_AUTHPROTOCOL_HMACMD5;
            else
                authProtocol = SNMP_AUTHPROTOCOL_NONE;
            continue;
        }
        if ( strstr( argv[x],"-priv") != 0) {
            ptr = argv[x];
            ptr+=5;
            if (strcasecmp(ptr, "DES") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_DES;
            else if (strcasecmp(ptr, "3DESEDE") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_3DESEDE;
            else if (strcasecmp(ptr, "IDEA") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_IDEA;
            else if (strcasecmp(ptr, "AES128") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_AES128;
            else if (strcasecmp(ptr, "AES192") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_AES192;
            else if (strcasecmp(ptr, "AES256") == 0)
                privProtocol = SNMP_PRIVPROTOCOL_AES256;
            else
                privProtocol = SNMP_PRIVPROTOCOL_NONE;
            printf("\n\nPrivProt : %ld\n", privProtocol);
            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 = OctetStr::from_hex_string(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;
    Snmp *snmp;

    if (address.get_ip_version() == Address::version_ipv4)
        snmp = new Snmp(status, "0.0.0.0");
    else
        snmp = new Snmp(status, "::");

    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 = "TrapSender";
        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 ]-------------------------------
    Pdu pdu;                               // construct a Pdu object
    Vb vb;                                 // variable binding object to use
    vb.set_oid(PAYLOADID);                 // example oid for trap payload
    vb.set_value(PAYLOAD);                 // example string for payload
    pdu += vb;                             // append the vb to the pdu
    pdu.set_notify_id( oid);               // set the id of the trap
    pdu.set_notify_enterprise( ent);       // set up the enterprise of the trap
    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_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_readcommunity( community); // set the read community name
#ifdef _SNMPv3
    }
#endif

    //-------[ Send the trap  ]------------------------------------------------
    cout << "SNMP++ Trap to " << argv[1] << " SNMPV"
#ifdef _SNMPv3
         << ((version==version3) ? (version) : (version+1));
#else
         << (version+1);
Esempio n. 13
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