Exemple #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;
}
Exemple #2
0
void callback( int reason, Snmp *snmp, Pdu &pdu, SnmpTarget &target, void *cd)
{
    Vb nextVb;
    int pdu_error;

    cout << "reason: " << reason << endl
         << "msg: " << snmp->error_msg(reason) << endl;

    pdu_error = pdu.get_error_status();
    if (pdu_error) {
        cout << "Response contains error: "
             << snmp->error_msg(pdu_error)<< endl;
    }
    for (int i=0; i<pdu.get_vb_count(); i++)
    {
        pdu.get_vb(nextVb, i);

        cout << "Oid: " << nextVb.get_printable_oid() << endl
             << "Val: " <<  nextVb.get_printable_value() << endl;
    }

    if (pdu.get_type() == sNMP_PDU_INFORM) {
        cout << "pdu type: " << pdu.get_type() << endl;
        cout << "sending response to inform: " << endl;
        nextVb.set_value("This is the response.");
        pdu.set_vb(nextVb, 0);
        snmp->response(pdu, target);
    }
    cout << endl;
}
Exemple #3
0
int wpdu::load_vbs(snmp_pdu *raw_pdu, const Pdu& pdu)
{
  int status = 0;

   // load up the payload
   // for all Vbs in list, add them to the pdu
   int vb_count;
   Vb tempvb;
   Oid tempoid;
   SmiLPOID smioid;
   SmiVALUE smival;

   vb_count = pdu.get_vb_count();

   for (int z = 0; z < vb_count; z++) {
      pdu.get_vb( tempvb, z);
      tempvb.get_oid( tempoid);
      smioid = tempoid.oidval();
      // what are we trying to convert here (vb oid part or value part)
      status = convert_vb_to_smival( tempvb, &smival );
      if ( status != SNMP_CLASS_SUCCESS)
         return status;

      // add the var to the raw pdu
      cmu_snmp::add_var(raw_pdu, smioid->ptr, (int) smioid->len, &smival);
      free_smival_descriptor( &smival);
    }

  return status;
}
Exemple #4
0
void getapp::result(Snmp *, int rc)
{
    Vb vb;
    if (rc < 0)
    {
      const char *ptr = snmp_.error_string();
      cout << "ASNMP:ERROR: get command failed reason: " << ptr << endl;
    }
    else
    {
      // check to see if there are any errors
      if (pdu_.get_error_status())
      {
        cout << "ERROR: agent replied as follows\n";
        cout << pdu_.agent_error_reason() << endl;
      }
      else
      {
        VbIter iter(pdu_);
        while (iter.next(vb))
        {
          cout << "\tOid = " << vb.to_string_oid() << "\n";
          cout << "\tValue = " << vb.to_string_value() << "\n";
        }
      }
    }
    cout << "\nASNMP:INFO: command completed normally.\n"<< endl;
    ACE_Reactor::instance()->end_reactor_event_loop();
}
Exemple #5
0
walkapp::walkapp(int argc, char *argv[]): valid_(0)
{
   Oid req, def_oid("1.3.6.1.2.1.1.1.0"); // default begin walk with MIBII
   if ( argc < 2)
     return;

   address_ = argv[argc - 1];
   if ( !address_.valid()) {
      cout << "ERROR: Invalid IPv4 address or DNS hostname: " \
     << argv[argc] << "\n";
      return;
   }

   ACE_Argv_Type_Converter to_tchar (argc, argv);
   ACE_Get_Opt get_opt (argc,
                        to_tchar.get_TCHAR_argv (),
                        ACE_TEXT ("o:c:r:t:"));
   for (int c; (c = get_opt ()) != -1; )
     switch (c)
       {
       case 'o':
         req = ACE_TEXT_ALWAYS_CHAR (get_opt.opt_arg());
         if (req.valid() == 0)
         cout << "ERROR: oid value: "
              << ACE_TEXT_ALWAYS_CHAR (get_opt.opt_arg())
              << "is not valid. using default.\n";
         break;

       case 'c':
         community_ = ACE_TEXT_ALWAYS_CHAR (get_opt.opt_arg());
         target_.set_read_community(community_);
         break;

       case 'r':
         target_.set_retry(ACE_OS::atoi (get_opt.opt_arg()));
         break;

       case 't':
         target_.set_timeout(ACE_OS::atoi (get_opt.opt_arg()));
         break;

       default:
         break;
       }

  Vb vb;                                  // construct a Vb object
  if (req.valid())
     vb.set_oid( req);                    // set the Oid portion of the Vb
  else {
     vb.set_oid( def_oid);               // set the Oid portion of the Vb
  }
  pdu_ += vb;
  vb.get_oid(oid_); // store for later use
  valid_ = 1;
}
Exemple #6
0
int getapp::run()
{

   //----------[ create a ASNMP session ]-----------------------------------
   if ( snmp_.valid() != SNMP_CLASS_SUCCESS) {
      cout << "\nASNMP:ERROR:Create session failed: "<<
          snmp_.error_string()<< "\n";
      return 1;
   }

   //--------[ build up ASNMP object needed ]-------------------------------
   if (address_.get_port() == 0)
     address_.set_port(DEF_AGENT_PORT);
   target_.set_address( address_);         // make a target using the address

   //-------[ issue the request, blocked mode ]-----------------------------
   cout << "\nASNMP:INFO:SNMP Version " << (target_.get_version()+ 1) << \
       " GET SAMPLE PROGRAM \nOID: " << oid_.to_string() << "\n";
   target_.get_address(address_); // target updates port used
   int rc;
   const char *name = address_.resolve_hostname(rc);

   cout << "Device: " << address_ << " ";

   //FUZZ: disable check_for_lack_ACE_OS
   cout << (rc ? "<< did not resolve via gethostbyname() >>" : name) << "\n";
   //FUZZ: enable check_for_lack_ACE_OS

   cout << "[ Retries=" << target_.get_retry() << " \
        Timeout=" << target_.get_timeout() <<" ms " << "Community=" << \
         community_.to_string() << " ]"<< endl;

   if (snmp_.get( pdu_, target_) == SNMP_CLASS_SUCCESS) {
       Vb vb;
      // check to see if there are any errors
      if (pdu_.get_error_status()) {
        cout << "ERROR: agent replied as follows\n";
        cout << pdu_.agent_error_reason() << endl;
      }
      else {
        VbIter iter(pdu_);
        while (iter.next(vb)) {
 	  cout << "\tOid = " << vb.to_string_oid() << "\n";
 	  cout << "\tValue = " << vb.to_string_value() << "\n";
       }
     }
   }
   else {
    const char *ptr = snmp_.error_string();
    cout << "ASNMP:ERROR: get command failed reason: " << ptr << endl;
  }

  cout << "\nASNMP:INFO: command completed normally.\n"<< endl;
  return 0;
}
Exemple #7
0
MibIter::MibIter(Snmp* snmp, Pdu& pdu, UdpTarget *target):
  snmp_(snmp), target_(target), pdu_(pdu), first_(0),
 valid_(0)
{
  // verify we have a valid oid to begin iterating with
  Oid oid;
  Vb vb;
  pdu.get_vb(vb, 0);
  vb.get_oid(oid);
  if (oid.valid())
    valid_ = 1;
}
Exemple #8
0
getapp::getapp(int argc, char *argv[]): valid_(0)
{
   Oid req, def_oid("1.3.6.1.2.1.1.1.0");      // default is sysDescr
   if ( argc < 2) 
     return; 
    
   address_ = argv[argc - 1];
   if ( !address_.valid()) {
      cout << "ERROR: Invalid IPv4 address or DNS hostname: " \
     << argv[argc] << "\n";
      return;
   }

   ACE_Get_Opt get_opt (argc, argv, "o:c:r:t:p:");
   for (int c; (c = get_opt ()) != -1; )
     switch (c)
       {
       case 'o':
         req = get_opt.optarg;
         if (req.valid() == 0) 
         cout << "ERROR: oid value: " <<get_opt.optarg  \
              << "is not valid. using default.\n";
         break;

       case 'c':
         community_ = get_opt.optarg;
         target_.set_read_community(community_);
         break;

       case 'r':
         target_.set_retry(ACE_OS::atoi (get_opt.optarg));
         break;

       case 't':
         target_.set_timeout(ACE_OS::atoi (get_opt.optarg));
         break;

       default:
         break;
       }

  Vb vb;                                  // construct a Vb object
  if (req.valid()) 
     vb.set_oid( req);                    // set the Oid portion of the Vb
  else { 
     vb.set_oid( def_oid);               // set the Oid portion of the Vb
  }
  pdu_ += vb;
  vb.get_oid(oid_); // store for later use
  valid_ = 1;
}
Exemple #9
0
int walkapp::run()
{

   //----------[ create a ASNMP session ]-----------------------------------
   if ( snmp_.valid() != SNMP_CLASS_SUCCESS) {
      cout << "\nASNMP:ERROR:Create session failed: "<<
          snmp_.error_string()<< "\n";
      return 1;
   }

   //--------[ build up ASNMP object needed ]-------------------------------
   if (address_.get_port() == 0)
     address_.set_port(DEF_AGENT_PORT);
   target_.set_address( address_);         // make a target using the address

   //-------[ issue the request, blocked mode ]-----------------------------
   cout << "\nASNMP:INFO:SNMP Version " << (target_.get_version()+ 1) << \
       " WALK SAMPLE PROGRAM \nOID: " << oid_.to_string() << "\n";
   target_.get_address(address_); // target updates port used
   int rc;
   const char *name = address_.resolve_hostname(rc);

   cout << "Device: " << address_ << " ";

   //FUZZ: disable check_for_lack_ACE_OS
   cout << (rc ? "<< did not resolve via gethostbyname() >>" : name) << "\n";
   //FUZZ: enable check_for_lack_ACE_OS

   cout << "[ Retries=" << target_.get_retry() << " \
        Timeout=" << target_.get_timeout() <<" ms " << "Community=" << \
         community_.to_string() << " ]"<< endl;

   MibIter iter(&snmp_, pdu_, &target_);
   char *err_str = 0;
   Vb vb;
   unsigned ctr = 0;
   while (iter.next(vb, err_str))  {
     cout << "\tOid = " << vb.to_string_oid() << "\n";
     cout << "\tValue = " << vb.to_string_value() << "\n";
     ctr++;
   }

   if (!err_str) {
     cout << "ERROR: walk: " << err_str << endl;
     return 0;
   }

  cout << "ASNMP:INFO:command completed normally. ACE Rocks...\n"<< endl;
  return 0;
}
Exemple #10
0
const string & SnmpDG::GetMibObject(const snmp_version  version, const SnmpPara& spr,  const string oid) const
{
	if(!m_inited_success)
	{
		return m_empty_object;
	}
	Snmp::socket_startup();

	UdpAddress address(spr.ip.c_str());
	//string myoid = oid;

	Pdu pdu;
	Vb vb;
	vb.set_oid(oid.c_str());//(myoid.c_str());
	pdu += vb;

	CTarget ctarget(address); 
	ctarget.set_version( version );
	ctarget.set_retry(spr.retry);           
	ctarget.set_timeout(spr.timeout); 
	ctarget.set_readcommunity(spr.community.c_str());
	SnmpTarget *target;
	target = &ctarget;

	int status;
	Snmp snmp(status, 0, false);
	if (status == SNMP_CLASS_SUCCESS)
	{
		if ((status = snmp.get( pdu, *target)) == SNMP_CLASS_SUCCESS)
		{
			pdu.get_vb( vb,0);
			//string oid_tmp = vb.get_printable_oid();
			m_mib_object = vb.get_printable_value();
		}
		else
		{
			m_mib_object = string("");
			SetLastError(status);
		}
	}
	else
	{
		m_mib_object = string("");
		SetLastError(status);
	}
	Snmp::socket_cleanup();  // Shut down socket subsystem
	return m_mib_object;
}
Exemple #11
0
const char *Pdu::agent_error_reason()
{
    int pdu_err = get_error_status();
    if (pdu_err == 0) // any real error?
        return "not in error state";

    int n_vbs = get_vb_count();
    Vb bad;
    get_vb(bad, get_error_index() -1); // not zero based??
    const char *pmsg =   Snmp::error_string(get_error_status());
    const char *id =   bad.to_string_oid();
    const char *val =  bad.to_string_value();
    const int HDR_SZ = 100;

    if (!output_) {
      int size = ACE_OS::strlen(pmsg) + ACE_OS::strlen(id) +
           ACE_OS::strlen(val);
      ACE_NEW_RETURN(output_, char[size + HDR_SZ], "");
    }
Exemple #12
0
// this routine makes up the brains of the agent
// it knows only the MIB II system group set of variables for a get operation
int agent_impl::get_response(Vb& vb)
{
  // these objects represent the MIB II system group per RFC 1213
   static Oid sysDescr("1.3.6.1.2.1.1.1.0"),
   sysObjectID("1.3.6.1.2.1.1.2.0"), sysUpTime("1.3.6.1.2.1.1.3.0"),
   sysContact("1.3.6.1.2.1.1.4.0"), sysName("1.3.6.1.2.1.1.5.0"),
   sysLocation("1.3.6.1.2.1.1.6.0"), sysServices("1.3.6.1.2.1.1.7.0");

  Oid oid;
  vb.get_oid(oid);
  if (oid == sysDescr) {
    OctetStr desc("ASNMP Prototype Agent 1.0");
    vb.set_value(desc);
  }
  else if (oid == sysObjectID) { // the IANA gives assigns Enterprise Numbers
    // see ftp://ftp.isi.edu/in-notes/iana/assignments/enterprise-numbers
    // for the official list of enterprise numbers. Then under this tree
    // assign a unique subtree to identify this agent
    Oid id("1.3.6.1.4.1.2533.9.1");
    vb.set_value(id);
  }
  else if (oid == sysUpTime) {
    ACE_Time_Value tv;
    agent_clock_.elapsed_time (tv);
    TimeTicks tt(tv.msec());
    vb.set_value(tt);
  }
  else if (oid == sysContact) {
    OctetStr contact("*****@*****.**");
    vb.set_value(contact);
  }
  else if (oid == sysName) {
    OctetStr fqdn("foo.org"); // extract this from the gethostbyname() TODO
    vb.set_value(fqdn);
  }
  else if (oid == sysLocation) {
    OctetStr loc("");
    vb.set_value(loc);
  }
  else if (oid == sysServices) {
    SnmpInt32 svcs(72);
    vb.set_value(svcs);
  }
  else
    return 1; // noSuchName

  return 0;
}
Exemple #13
0
// determine the smi type and get a value from the user
int determine_vb( SmiUINT32 val, Vb &vb)
{
  char buffer[255];

  if (val == sNMP_SYNTAX_NOSUCHINSTANCE)
  {
    cout << "Instance does not exists but can be created.\n";
    cout << "Please enter one of the following types:\n\n";
    cout << "Integer:  " << sNMP_SYNTAX_INT << "\n";
    cout << "Bits:     " << sNMP_SYNTAX_BITS << "\n";
    cout << "STRING:   " << sNMP_SYNTAX_OCTETS << "\n";
    cout << "Oid:      " << sNMP_SYNTAX_OID << "\n";
    cout << "IpAddress:" << sNMP_SYNTAX_IPADDR << "\n\n";
    cout << "Please choose value type: ";
    cin >> val;
    vb.set_syntax(val);
  }
Exemple #14
0
// return vb of next oid in agent tree, return 1 else return 0, reason set
int MibIter::next(Vb& vb, char *& reason)
{
  int rc;

  if (valid_ == 0) // not valid object
     return -1;

  // 1. poll for value
  if (first_ == 0) {
    rc = snmp_->get( pdu_, *target_);
    first_++;
  }
  else {
   rc = snmp_->get_next( pdu_, *target_);
  }

  if (rc != SNMP_CLASS_SUCCESS) {
       reason = const_cast <char*> (snmp_->error_string());
       return 0;
  }

  // 2. check for problems
  if (pdu_.get_error_status()) {
     reason = const_cast <char*> (pdu_.agent_error_reason());
     return 0;
  }

  // 3. return vb to caller
  pdu_.get_vb(vb, 0);
  Oid nextoid;
  vb.get_oid(nextoid); // and setup next oid to get
  Vb nextvb(nextoid);
  pdu_.delete_all_vbs();
  pdu_ += nextvb; // can't do set_vb as there are no entries to replace

  return 1; // ok
}
Exemple #15
0
int wpdu::restore_vbs(Pdu& pdu, const snmp_pdu *raw_pdu) const
{
   Vb tempvb;
   Oid tempoid;
   struct variable_list *vp;

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

    // 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:
     case sNMP_SYNTAX_OPAQUE:
    {
       OctetStr octets( (char *) vp->val.string,
                         (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);
    }
     break;

    // timeticks
    case sNMP_SYNTAX_TIMETICKS:
    {
       TimeTicks timeticks( (unsigned long) *(vp->val.integer));
       tempvb.set_value( timeticks);
    }
    break;

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

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

    // ip address
    case sNMP_SYNTAX_IPADDR:
    {
       char buffer[20];
       ACE_OS::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
    case sNMP_SYNTAX_UINT32:
    {
      SnmpUInt32 uint32( (unsigned long) *(vp->val.integer));
      tempvb.set_value( uint32);
    }
     break;

    // v2 counter 64's
    case sNMP_SYNTAX_CNTR64:
     break;

    case sNMP_SYNTAX_NULL:
      tempvb.set_null();
    break;

    // v2 vb exceptions
    case sNMP_SYNTAX_NOSUCHOBJECT:
    case sNMP_SYNTAX_NOSUCHINSTANCE:
    case sNMP_SYNTAX_ENDOFMIBVIEW:
       set_exception_status( &tempvb, vp->type);
     break;

    default:
       tempvb.set_null();

    } // end switch

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

  return 0;
}
Exemple #16
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;
}
Exemple #17
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;
}
Exemple #18
0
// Send a report message.
int v3MP::send_report(unsigned char* scopedPDU, int scopedPDULength,
		      struct snmp_pdu *pdu, int errorCode, int sLevel,
		      int sModel, OctetStr &sName,
		      UdpAddress &destination, Snmp *snmp_session)
{
  debugprintf(2, "v3MP::send_report: Sending report message.");

  unsigned char *data;
  int dataLength;
  int pdu_type = 0;
  unsigned char cEngineID[MAXLENGTH_ENGINEID+1];
  unsigned char cName[MAXLENGTH_CONTEXT_NAME+1];
  int cEngineIDLength = MAXLENGTH_ENGINEID+1;
  int cNameLength = MAXLENGTH_CONTEXT_NAME+1;

  debugprintf(2, "v3MP::send_report: securityLevel %d",sLevel);

  if (scopedPDULength != MAX_SNMP_PACKET)
  {
    // try to get scopedPDU and PDU
    data = asn1_parse_scoped_pdu(scopedPDU, &scopedPDULength,
				 cEngineID, &cEngineIDLength,
				 cName, &cNameLength);
    if (data == NULL) {
      debugprintf(1, "mp: Error while trying to parse  scopedPDU!");
      cEngineID[0] = '\0';
      cEngineIDLength = 0;
      cName[0] = '\0';
      cNameLength = 0;
      // Dont send encrypted report if decryption failed:
      //if (sLevel == SNMP_SECURITY_LEVEL_AUTH_PRIV)
     //   sLevel = SNMP_SECURITY_LEVEL_AUTH_NOPRIV;
    }
    else { // data != NULL
      dataLength = scopedPDULength;

      // parse data of scopedPDU
      snmp_parse_data_pdu(pdu, data, dataLength);
      pdu_type = pdu->command;

      if (!data) {
        debugprintf(0, "mp: Error while trying to parse PDU!");
      }
    } // end of: if (data == NULL)
  } // end if (scopedPDULength != MAX_SNMP_PACKET)
  else { // scopedPDULength == MAX_SNMP_PACKET
    cEngineID[0] = '\0';
    cEngineIDLength = 0;
    cName[0] = '\0';
    cNameLength = 0;
    pdu->reqid = 0;
  }

  clear_pdu(pdu);   // Clear pdu and free all content

  debugprintf(4, "pdu->reqid = %ld",pdu->reqid);
  pdu->errstat = 0;
  pdu->errindex = 0;
  pdu->command = REPORT_MSG;

  Vb counterVb;
  Oid counterOid;
  SmiLPOID smioid;
  SmiVALUE smival;

  switch (errorCode) {
    case SNMPv3_MP_INVALID_MESSAGE:
    case SNMPv3_USM_PARSE_ERROR: {
      counterVb.set_oid(oidSnmpInvalidMsgs);
      counterVb.set_value(Counter32(get_stats_invalid_msgs()));
      break;
    }
    case SNMPv3_USM_NOT_IN_TIME_WINDOW:
    case SNMPv3_MP_NOT_IN_TIME_WINDOW: {
      counterVb.set_oid(oidUsmStatsNotInTimeWindows);
      counterVb.set_value(Counter32(usm->get_stats_not_in_time_windows()));
      break;
    }
    case SNMPv3_USM_DECRYPTION_ERROR: {
      counterVb.set_oid(oidUsmStatsDecryptionErrors);
      counterVb.set_value(Counter32(usm->get_stats_decryption_errors()));
      //sLevel = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV;
      break;
    }
    case SNMPv3_USM_AUTHENTICATION_ERROR:
    case SNMPv3_USM_AUTHENTICATION_FAILURE: {
      counterVb.set_oid(oidUsmStatsWrongDigests);
      counterVb.set_value(Counter32(usm->get_stats_wrong_digests()));
      //sLevel = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV;
      break;
    }
    case SNMPv3_USM_UNKNOWN_ENGINEID:
    case SNMPv3_MP_INVALID_ENGINEID: {
      //sLevel = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV;
      counterVb.set_oid(oidUsmStatsUnknownEngineIDs);
      counterVb.set_value(Counter32(usm->get_stats_unknown_engine_ids()));
      break;
    }
    case SNMPv3_MP_UNSUPPORTED_SECURITY_MODEL: {
      counterVb.set_oid(oidSnmpUnknownSecurityModels);
      counterVb.set_value(Counter32(get_stats_unknown_security_models()));
      sModel = SNMP_SECURITY_MODEL_USM;
      sLevel = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV;
    break;
    }
    case SNMPv3_USM_UNKNOWN_SECURITY_NAME: {
      counterVb.set_oid(oidUsmStatsUnknownUserNames);
      counterVb.set_value(Counter32(usm->get_stats_unknown_user_names()));
      sLevel = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV;
      debugprintf(2, "Report: SecurityName: %s",sName.get_printable());
      break;
    }
    case SNMPv3_USM_UNSUPPORTED_SECURITY_LEVEL: {
      counterVb.set_oid(oidUsmStatsUnsupportedSecLevels);
      counterVb.set_value(Counter32(usm->get_stats_unsupported_sec_levels()));
      sLevel = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV;
      break;
    }
    default: {
      counterVb.set_oid(oidSnmpInvalidMsgs);
      counterVb.set_value(Counter32(get_stats_invalid_msgs()));
      sModel = SNMP_SECURITY_MODEL_USM;
      sLevel = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV;
      sName.set_data(0, 0);

      debugprintf(2, "ErrorCode was %i in snmp_parse", errorCode);
    }
  } // end switch

  counterVb.get_oid(counterOid);
  smioid = counterOid.oidval();

  int status = convertVbToSmival(counterVb, &smival);
  if (status != SNMP_CLASS_SUCCESS) {
    return SNMPv3_MP_ERROR;
  }
  snmp_add_var(pdu, smioid->ptr,
               (int) smioid->len, &smival);
  freeSmivalDescriptor(&smival);

  Buffer<unsigned char> sendbuffer(MAX_SNMP_PACKET);
  int sendbufferlen= MAX_SNMP_PACKET;
  status = snmp_build( pdu, sendbuffer.get_ptr(), &sendbufferlen,
		       own_engine_id_oct, sName, sModel, sLevel,
		       OctetStr(cEngineID, cEngineIDLength),
		       OctetStr(cName, cNameLength));
  if (status != SNMPv3_MP_OK) {
    debugprintf(2, "v3MP::send_report: error serializing message (mpSnmpBuild returns: %i).", status);
    return SNMPv3_MP_ERROR;
  }
  SnmpSocket send_fd = INVALID_SOCKET;
  if (pdu_type == sNMP_PDU_INFORM)
  {
    debugprintf(4, "Received a snmpInform pdu.");
    if (snmp_session->get_eventListHolder()->notifyEventList())
      send_fd = snmp_session->get_eventListHolder()->notifyEventList()->get_notify_fd();
  }

  status = snmp_session->send_raw_data(sendbuffer.get_ptr(),
                                       (size_t)sendbufferlen,// pdu to send
			               destination,          // target address
			               send_fd);             // the fd to use
  if ( status != 0)
  {
    debugprintf(1, "v3MP::send_report: error sending message (%i)", status);
    return SNMPv3_MP_ERROR;
  }
  debugprintf(3, "v3MP::send_report: Report sent.");
  return SNMPv3_MP_OK;
}
Exemple #19
0
set::set(int argc, char *argv[]): valid_(0)
{
   Vb vb;                                  // construct a Vb object
   Oid req;
   if ( argc < 2) 
     return; 
   target_.get_write_community(community_); 
   address_ = argv[argc - 1];
   if ( !address_.valid()) {
      cout << "ERROR: Invalid IPv4 address or DNS hostname: " \
     << argv[argc] << "\n";
      return;
   }

   ACE_Get_Opt get_opt (argc, argv, "o:c:r:t:I:U:C:G:T:O:S:P:");
   for (int c; (c = get_opt ()) != -1; )
     switch (c)
       {
       case 'o':
         req = get_opt.optarg;
         if (req.valid() == 0) 
         cout << "ERROR: oid value: " <<get_opt.optarg  \
              << "is not valid. using default.\n";
         break;

       case 'c':
         community_ = get_opt.optarg;
         target_.set_write_community(community_);
         break;

       case 'r':
         target_.set_retry(ACE_OS::atoi (get_opt.optarg));
         break;

       case 't':
         target_.set_timeout(ACE_OS::atoi (get_opt.optarg));
         break;

       case 'I': // Integer32
         {
         SnmpInt32 o(ACE_OS::atoi(get_opt.optarg)); 
         vb.set_value(o);
         pdu_ += vb;
         }
        break;

       case 'U': // Unsigned32
         {
         SnmpUInt32 o(ACE_OS::atoi(get_opt.optarg)); 
         vb.set_value(o);
         pdu_ += vb;
         }
        break;

       case 'C': // Counter32
         {
         Counter32 o(ACE_OS::atoi(get_opt.optarg)); 
         vb.set_value(o);
         pdu_ += vb;
         }
         break;

       case 'G': // Gauge32
        {
         Gauge32 o(ACE_OS::atoi(get_opt.optarg)); 
         vb.set_value(o);
         pdu_ += vb;
         }
        break;

       case 'T': // TimeTicks
        {
         TimeTicks o(ACE_OS::atoi(get_opt.optarg)); 
         vb.set_value(o);
         pdu_ += vb;
         }
        break;

       case 'O': // Oid as a variable identifier 
        {
         oid_ = get_opt.optarg; 
         vb.set_oid(oid_); // when value is set, pdu updated
         }
         break;

       case 'S': // Octet String
         {
         OctetStr o(get_opt.optarg); 
         vb.set_value(o);                    // set the Oid portion of the Vb
         pdu_ += vb;
         }
         break;

       case 'P': // Oid String as a value
         {
         Oid o(get_opt.optarg); 
         vb.set_value(o);                    // set the Oid portion of the Vb
         pdu_ += vb;
         }
         break;

       default:
         break;
       }

  // if user didn't set anything use defaults 
  if (pdu_.get_vb_count() == 0) {
   Oid def_oid("1.3.6.1.2.1.1.4.0");      // defualt is sysName
   OctetStr def_value("sysName.0 updated by ASNMP set command");
   vb.set_oid(def_oid);
   vb.set_value(def_value);
   pdu_ += vb;
   cout << "INFO: using defaults, setting sysName to : " <<  \
        def_value.to_string() << endl; 
  }

  valid_ = 1;
}
Exemple #20
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
} 
Exemple #21
0
void MainWindow::async_callback(int reason, Snmp * /*snmp*/, Pdu &pdu,
				SnmpTarget &target)
{
  Vb nextVb;
  int pdu_error;
  QString prefix_text;
  QString notify_text;

  push_button_get_next->setEnabled(true);

  // What is the reason for this callback?
  if (reason == SNMP_CLASS_NOTIFICATION)
  {
    prefix_text = "Trap:    ";

    // get the notify id for traps
    Oid id;
    pdu.get_notify_id(id);
    notify_text = QString(" ID: %1 Type %2 -- ").arg(id.get_printable())
                  .arg(pdu.get_type());
  }
  else if (reason == SNMP_CLASS_ASYNC_RESPONSE)
  {
    prefix_text = "Response ";
  }
  else if (reason == SNMP_CLASS_TIMEOUT)
  {
    prefix_text = "Timeout  ";
  }
  else
  {
    QString err = QString("\nDid not receive async response/trap: (%1) %2\n")
                  .arg(reason).arg(Snmp::error_msg(reason));
    text_edit_output->append(err);
  }


  // Look at the error status of the Pdu
  pdu_error = pdu.get_error_status();
  if (pdu_error)
  {
    QString err = "\nResponse contains error:\n";
    err += Snmp::error_msg(pdu_error);
    text_edit_output->append(err);
    return;
  }

  // The Pdu must contain at least one Vb
  if (pdu.get_vb_count() == 0)
  {
    QString err = "\nPdu is empty\n";
    text_edit_output->append(err);
    return;
  }

  for (int i=0; i<pdu.get_vb_count(); i++)
  {
    // Get the Vb of the Pdu
    pdu.get_vb(nextVb, i);

    // Get Oid and value from the Vb and display it
    line_edit_obj_id->setText(nextVb.get_printable_oid());
    line_edit_value->setText(nextVb.get_printable_value());

    text_edit_output->append(prefix_text +
			     target.get_address().get_printable() +
			     " -- " +
			     notify_text +
			     line_edit_obj_id->text() + " = " +
			     line_edit_value->text() + "\n");
  }

  // If we received a inform pdu, we have to send a response
  if (pdu.get_type() == sNMP_PDU_INFORM)
  {
    text_edit_output->append("Sending response to inform.\n");

    // just change the value of the first vb
    pdu.get_vb(nextVb, 0);
    nextVb.set_value("This is the response.");
    pdu.set_vb(nextVb, 0);
    snmp->response(pdu, target);
  }
}
Exemple #22
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;
}
Exemple #23
0
const list<pair<string,string> > & SnmpDG::GetMibTable(const snmp_version  version, const SnmpPara& spr, const string oid) const
{
	m_mib_table.clear();
	if(!m_inited_success)
	{
		return m_mib_table;
	}
	Snmp::socket_startup();  // Initialize socket subsystem

	UdpAddress address( spr.ip.c_str());
	Oid myoid(oid.c_str());      // default is sysDescr
	if( !myoid.valid())
	{// check validity of user oid
		return m_mib_table;
	}
	Pdu pdu;                           // construct a Pdu object
	Vb vb;                             // construct a Vb object(SNMP++ Variable Binding)
	vb.set_oid(myoid);//oid.c_str());
	pdu += vb;

	CTarget ctarget(address); 
	ctarget.set_version( version );
	ctarget.set_retry(spr.retry);           
	ctarget.set_timeout(spr.timeout); 
	ctarget.set_readcommunity(spr.community.c_str());
	SnmpTarget *target;
	target = &ctarget;
	int status;
	Snmp snmp(status, 0, false);
	if (status == SNMP_CLASS_SUCCESS)
	{
		DWORD dwStartTime_ttl = GetTickCount();
	   	DWORD dwStartTime = 0, dwEndTime = 0;
		while ( (status = snmp.get_next(pdu, *target)) == SNMP_CLASS_SUCCESS) //get_next命令是按列遍历oid
		{
			pdu.get_vb(vb, 0);
			Oid oid_tmp = vb.get_oid();//.get_printable_oid();该表项的oid
			string str_oid_tmp = oid_tmp.get_printable();
			if(oid_tmp.nCompare(myoid.len(), myoid) != 0)//判断是否已越界,如果是则结束循环
			{
				break;
			}

			bool bNew = true;
			string value_tmp = vb.get_printable_value();
                        for(std::list<pair<string,string> >::iterator item = m_mib_table.begin();
				item != m_mib_table.end();
				item++)
			{
				if(item->first == str_oid_tmp)//value_tmp)//去掉重复的oid
				{
					bNew = false;
					cout << "ip:" + spr.ip + ",repeat oid:" + str_oid_tmp;
					break;
				}
			}
			if(bNew)
			{
				dwStartTime = GetTickCount();
				m_mib_table.push_back(make_pair(str_oid_tmp,value_tmp));
				vb.set_oid(oid_tmp);
				vb.set_null();
				pdu.set_vb(vb,0);
			}
			else
			{
 			//	if ( GetTickCount() - dwStartTime > 10000 ) //10s
				//{
				//	cout << "Timeout because read repeat data " << endl;
					break;
				//}
			}
			if ( GetTickCount() - dwStartTime_ttl > 300000 )  //5min
			{
				cout << "Timeout because read operation " << endl;
				break;
			}
		}
	}
	else
	{
		cout << "SNMP++ Session Create Fail, " << snmp.error_msg(status) << "\n";
		SetLastError(status);
	}
	Snmp::socket_cleanup();  // Shut down socket subsystem
	return m_mib_table;
}
Exemple #24
0
int main(int argc, char **argv)
{
    int status;
    char *req_str      = (char*) "get";
    //  char *dflt_req_oid = (char*) sysDescr;
    char *dflt_trp_oid = (char*) coldStart;
    char *genAddrStr   = (char*) "127.0.0.1" ;		  // localhost
    char *oid_str      = (char*) NULL;

    if (argc > 1) genAddrStr = argv[1];
    if (argc > 2) req_str    = argv[2];
    if (argc > 3) oid_str    = argv[3];

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

    IpAddress ipAddr(genAddrStr);
    if (!ipAddr.valid()) {
        cout << "Invalid destination: " << genAddrStr << endl;
        return(1);
    }

    // bind to any port and use IPv6 if needed
    Snmp snmp(status, 0, (ipAddr.get_ip_version() == Address::version_ipv6));
    if (status) {
        cout << "Failed to create SNMP Session: " << status << endl;
        return(1);
    }
    cout << "Created session successfully" << endl;


    CTarget target(ipAddr);
    if (! target.valid()) {
        cout << "Invalid target" << endl;
        return(1);
    }

    Pdu pdu;
    Vb vb;
    if ( strcmp(req_str, "get") == 0 ) {

        Vb vbl[NUM_SYS_VBS];
        vbl[0].set_oid(sysDescr);
        vbl[1].set_oid(sysObjectID);
        vbl[2].set_oid(sysUpTime);
        vbl[3].set_oid(sysContact);
        vbl[4].set_oid(sysName);
        vbl[5].set_oid(sysLocation);
//    vbl[6].set_oid(sysServices);

        cout << "Send a GET-REQUEST to: " << ipAddr.get_printable() << endl;
        if ( ! oid_str ) {
            if ( strcmp(genAddrStr,"localhost" ) == 0 ||
                    strcmp(genAddrStr, "127.0.0.1") == 0 ) {
                pdu.set_vblist(vbl, NUM_SYS_VBS);
            } else {
                for (int i=0; i<NUM_SYS_VBS; i++)
                    pdu += vbl[i];
            }
        }
        else {
            Oid req_oid(oid_str);
            if ( ! req_oid.valid() ) {
                cout << "Request oid constructor failed for:" << oid_str << endl;
                return(1);
            }
            vb.set_oid(req_oid);
            pdu += vb;
        }
        status = snmp.get(pdu, target);
        if (status) {
            cout << "Failed to issue SNMP Get: (" << status  << ") "
                 << snmp.error_msg(status) << endl;
            return(1);
        }
        else {
            cout << "Issued get successfully" << endl;
            int vbcount = pdu.get_vb_count();
            if ( vbcount == NUM_SYS_VBS ) {
                pdu.get_vblist(vbl, vbcount);
                for ( int i=0; i<vbcount ; i++ )  {
                    cout << vbl[i].get_printable_oid() << " : " <<
                         vbl[i].get_printable_value() << endl;
                }
            } else {
                for ( int i=0; i<vbcount ; i++ )  {
                    pdu.get_vb(vb, i);
                    cout << vb.get_printable_oid() << " : " <<
                         vb.get_printable_value() << endl;
                }
            }
        }
    }
    else if ( strcmp(req_str, "trap") == 0 ) {
        cout << "Send a TRAP to: " << ipAddr.get_printable() << endl;

        if ( ! oid_str )
            oid_str = dflt_trp_oid;

        Oid notify_oid(oid_str);
        if ( ! notify_oid.valid() ) {
            cout << "Notify oid constructor failed for:" << oid_str << endl;
            return(1);
        }

        pdu.set_notify_id(notify_oid);

        // Use a simple payload
        vb.set_oid(sysLocation);
        vb.set_value("This is a test");
        pdu += vb;

        status = snmp.trap(pdu, target);

        if (status) {
            cout << "Failed to issue SNMP Trap: (" << status  << ") "
                 << snmp.error_msg(status) << endl;
            return(1);
        } else {
            cout << "Success" << endl;
        }

    }
    else {
        cout << "Invalid SNMP operation: " << req_str  << endl ;
        cout << "Usage: " << argv[0] << " hostname [get | trap]" << endl;
        return(1);
    }

    Snmp::socket_cleanup();  // Shut down socket subsystem

    return(0);
}
Exemple #25
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;
}
Exemple #26
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;
}
Exemple #27
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;
}
Exemple #28
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
}
Exemple #29
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;
}
Exemple #30
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;
}