예제 #1
0
 /// <summary> Appends the passed Oid object to
 /// self.
 /// </summary>
 /// <param name="second">The object to Append to self
 /// </param>
 public virtual void Add(Oid second)
 {
     Add(second.GetData());
 }
예제 #2
0
 /// <summary>
 /// Exact comparison of two Oid values
 /// </summary>
 /// <param name="oid">Oid to compare against</param>
 /// <returns>1 if class is greater then argument, -1 if class value is less then argument, 0 if the same</returns>
 public int CompareExact(Oid oid)
 {
     return(CompareExact(oid.GetData()));
 }
예제 #3
0
 /// <summary>
 /// SNMP GET request
 /// </summary>
 /// <example>SNMP GET request:
 /// <code>
 /// String snmpAgent = "10.10.10.1";
 /// String snmpCommunity = "public";
 /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
 /// // Create a request Pdu
 /// Pdu pdu = new Pdu();
 /// pdu.Type = SnmpConstants.GET; // type GET
 /// pdu.VbList.Add("1.3.6.1.2.1.1.1.0");
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(SnmpVersion.Ver1, pdu);
 /// if( result == null ) {
 ///   Console.WriteLine("Request failed.");
 /// } else {
 ///   foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result)
 ///   {
 ///     Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
 ///       entry.Value.ToString());
 ///   }
 /// }
 /// </code>
 /// Will return:
 /// <code>
 /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
 /// </code>
 /// </example>
 /// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
 /// <param name="pdu">Request Protocol Data Unit</param>
 /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
 public Dictionary <Oid, AsnType> Get(SnmpVersion version, Pdu pdu)
 {
     if (!Valid)
     {
         if (!_suppressExceptions)
         {
             throw new SnmpException("SimpleSnmp class is not valid.");
         }
         return(null);                // class is not fully initialized.
     }
     // function only works on SNMP version 1 and SNMP version 2 requests
     if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
     {
         if (!_suppressExceptions)
         {
             throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
         }
         return(null);
     }
     try
     {
         _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
     }
     catch (Exception ex)
     {
         _target = null;
         if (!_suppressExceptions)
         {
             throw ex;
         }
     }
     if (_target == null)
     {
         return(null);
     }
     try
     {
         AgentParameters param  = new AgentParameters(version, new OctetString(_community));
         SnmpPacket      result = _target.Request(pdu, param);
         if (result != null)
         {
             if (result.Pdu.ErrorStatus == 0)
             {
                 Dictionary <Oid, AsnType> res = new Dictionary <Oid, AsnType>();
                 foreach (Vb v in result.Pdu.VbList)
                 {
                     if (version == SnmpVersion.Ver2 && (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE ||
                                                         v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT))
                     {
                         if (!res.ContainsKey(v.Oid))
                         {
                             res.Add(v.Oid, new Null());
                         }
                         else
                         {
                             res.Add(Oid.NullOid(), v.Value);
                         }
                     }
                     else
                     {
                         if (!res.ContainsKey(v.Oid))
                         {
                             res.Add(v.Oid, v.Value);
                         }
                         else
                         {
                             if (res[v.Oid].Type == v.Value.Type)
                             {
                                 res[v.Oid] = v.Value;                                         // update value of the existing Oid entry
                             }
                             else
                             {
                                 throw new SnmpException(SnmpException.OidValueTypeChanged, String.Format("Value type changed from {0} to {1}", res[v.Oid].Type, v.Value.Type));
                             }
                         }
                     }
                 }
                 _target.Close();
                 _target = null;
                 return(res);
             }
             else
             {
                 if (!_suppressExceptions)
                 {
                     throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         if (!_suppressExceptions)
         {
             _target.Close();
             _target = null;
             throw ex;
         }
     }
     _target.Close();
     _target = null;
     return(null);
 }
예제 #4
0
        /// <summary>SNMP WALK operation</summary>
        /// <remarks>
        /// When using SNMP version 1, walk is performed using GET-NEXT calls. When using SNMP version 2,
        /// walk is performed using GET-BULK calls.
        /// </remarks>
        /// <example>Example SNMP walk operation using SNMP version 1:
        /// <code>
        /// String snmpAgent = "10.10.10.1";
        /// String snmpCommunity = "private";
        /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
        /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Walk(SnmpVersion.Ver1, "1.3.6.1.2.1.1");
        /// if( result == null ) {
        ///   Console.WriteLine("Request failed.");
        /// } else {
        /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result)
        /// {
        ///   Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
        ///     entry.Value.ToString());
        /// }
        /// </code>
        /// Will return:
        /// <code>
        /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
        /// 1.3.6.1.2.1.1.2.0 = ObjectId: 1.3.6.1.9.233233.1.1
        /// 1.3.6.1.2.1.1.3.0 = TimeTicks: 0d 0h 0m 1s 420ms
        /// 1.3.6.1.2.1.1.4.0 = OctetString: "*****@*****.**"
        /// 1.3.6.1.2.1.1.5.0 = OctetString: "milans-nbook"
        /// 1.3.6.1.2.1.1.6.0 = OctetString: "Developer home"
        /// 1.3.6.1.2.1.1.8.0 = TimeTicks: 0d 0h 0m 0s 10ms
        /// </code>
        ///
        /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
        /// </example>
        /// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and
        /// SnmpVersion.Ver2</param>
        /// <param name="rootOid">OID to start WALK operation from. Only child OIDs of the rootOid will be
        /// retrieved and returned</param>
        /// <returns>Oid => AsnType value mappings on success, empty dictionary if no data was found or
        /// null on error</returns>
        public Dictionary <Oid, AsnType> Walk(SnmpVersion version, string rootOid)
        {
            if (!Valid)
            {
                if (!_suppressExceptions)
                {
                    throw new SnmpException("SimpleSnmp class is not valid.");
                }
                return(null);
            }
            // function only works on SNMP version 1 and SNMP version 2 requests
            if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
            {
                if (!_suppressExceptions)
                {
                    throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
                }
                return(null);
            }
            if (rootOid.Length < 2)
            {
                if (!_suppressExceptions)
                {
                    throw new SnmpException(SnmpException.InvalidOid, "RootOid is not a valid Oid");
                }
                return(null);
            }
            Oid root = new Oid(rootOid);

            if (root.Length <= 0)
            {
                return(null);                // unable to parse root oid
            }
            Oid lastOid = (Oid)root.Clone();

            Dictionary <Oid, AsnType> result = new Dictionary <Oid, AsnType>();

            while (lastOid != null && root.IsRootOf(lastOid))
            {
                Dictionary <Oid, AsnType> val = null;
                if (version == SnmpVersion.Ver1)
                {
                    val = GetNext(version, new string[] { lastOid.ToString() });
                }
                else
                {
                    val = GetBulk(new string[] { lastOid.ToString() });
                }
                // check that we have a result
                if (val == null || val.Count == 0)
                {
                    // error of some sort happened. abort...
                    break;
                }
                foreach (KeyValuePair <Oid, AsnType> entry in val)
                {
                    if (root.IsRootOf(entry.Key))
                    {
                        if (result.ContainsKey(entry.Key))
                        {
                            if (result[entry.Key].Type != entry.Value.Type)
                            {
                                throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + entry.Key.ToString());
                            }
                            else
                            {
                                result[entry.Key] = entry.Value;
                            }
                        }
                        else
                        {
                            result.Add(entry.Key, entry.Value);
                        }
                        lastOid = (Oid)entry.Key.Clone();
                    }
                    else
                    {
                        // it's faster to check if variable is null then checking IsRootOf
                        lastOid = null;
                        break;
                    }
                }
            }
            return(result);
        }
예제 #5
0
        /// <summary>Used to create correct variable type object for the specified encoded type</summary>
        /// <param name="asnType">ASN.1 type code</param>
        /// <returns>A new object matching type supplied or null if type was not recognized.</returns>
        public static AsnType GetSyntaxObject(SMIDataTypeCode asnType)
        {
            AsnType obj = null;

            if (asnType == SMIDataTypeCode.Integer)
            {
                obj = new Integer32();
            }
            else if (asnType == SMIDataTypeCode.Counter32)
            {
                obj = new Counter32();
            }
            else if (asnType == SMIDataTypeCode.Gauge32)
            {
                obj = new Gauge32();
            }
            else if (asnType == SMIDataTypeCode.Counter64)
            {
                obj = new Counter64();
            }
            else if (asnType == SMIDataTypeCode.TimeTicks)
            {
                obj = new TimeTicks();
            }
            else if (asnType == SMIDataTypeCode.OctetString)
            {
                obj = new OctetString();
            }
            else if (asnType == SMIDataTypeCode.Opaque)
            {
                obj = new Opaque();
            }
            else if (asnType == SMIDataTypeCode.IPAddress)
            {
                obj = new IpAddress();
            }
            else if (asnType == SMIDataTypeCode.ObjectId)
            {
                obj = new Oid();
            }
            else if (asnType == SMIDataTypeCode.PartyClock)
            {
                obj = new V2PartyClock();
            }
            else if (asnType == SMIDataTypeCode.NoSuchInstance)
            {
                obj = new NoSuchInstance();
            }
            else if (asnType == SMIDataTypeCode.NoSuchObject)
            {
                obj = new NoSuchObject();
            }
            else if (asnType == SMIDataTypeCode.EndOfMibView)
            {
                obj = new EndOfMibView();
            }
            else if (asnType == SMIDataTypeCode.Null)
            {
                obj = new Null();
            }

            return(obj);
        }
예제 #6
0
        /// <summary>Used to create correct variable type object for the specified encoded type</summary>
        /// <param name="asnType">ASN.1 type code</param>
        /// <returns>A new object matching type supplied or null if type was not recognized.</returns>
        public static AsnType GetSyntaxObject(byte asnType)
        {
            AsnType obj = null;

            if (asnType == SMI_INTEGER)
            {
                obj = new Integer32();
            }
            else if (asnType == SMI_COUNTER32)
            {
                obj = new Counter32();
            }
            else if (asnType == SMI_GAUGE32)
            {
                obj = new Gauge32();
            }
            else if (asnType == SMI_COUNTER64)
            {
                obj = new Counter64();
            }
            else if (asnType == SMI_TIMETICKS)
            {
                obj = new TimeTicks();
            }
            else if (asnType == SMI_STRING)
            {
                obj = new OctetString();
            }
            else if (asnType == SMI_OPAQUE)
            {
                obj = new Opaque();
            }
            else if (asnType == SMI_IPADDRESS)
            {
                obj = new IpAddress();
            }
            else if (asnType == SMI_OBJECTID)
            {
                obj = new Oid();
            }
            else if (asnType == SMI_PARTY_CLOCK)
            {
                obj = new V2PartyClock();
            }
            else if (asnType == SMI_NOSUCHINSTANCE)
            {
                obj = new NoSuchInstance();
            }
            else if (asnType == SMI_NOSUCHOBJECT)
            {
                obj = new NoSuchObject();
            }
            else if (asnType == SMI_ENDOFMIBVIEW)
            {
                obj = new EndOfMibView();
            }
            else if (asnType == SMI_NULL)
            {
                obj = new Null();
            }

            return(obj);
        }
예제 #7
0
        /// <summary>
        ///     Construct and send SNMP v3 authPriv Trap
        /// </summary>
        /// <param name="receiver">Trap receiver IP address</param>
        /// <param name="receiverPort">Trap receiver UDP port number</param>
        /// <param name="engineId">Sender SNMP engineId</param>
        /// <param name="senderEngineBoots">Sender SNMP engine boots</param>
        /// <param name="senderEngineTime">Sender SNMP engine time</param>
        /// <param name="senderUserName">Security (user) name</param>
        /// <param name="senderUpTime">Sender upTime</param>
        /// <param name="trapObjectID">Trap object ID</param>
        /// <param name="varList">Variable binding list</param>
        /// <param name="authDigest">
        ///     Authentication digest. See <see cref="AuthenticationDigests" /> enumeration for
        ///     available digests
        /// </param>
        /// <param name="authSecret">Authentication secret</param>
        /// <param name="privProtocol">
        ///     Privacy protocol. See <see cref="PrivacyProtocols" /> enumeration for
        ///     available privacy protocols.
        /// </param>
        /// <param name="privSecret">Privacy secret</param>
        public void SendV3Trap(IpAddress receiver, int receiverPort, byte[] engineId, int senderEngineBoots,
                               int senderEngineTime, string senderUserName, uint senderUpTime, Oid trapObjectID, VbCollection varList,
                               AuthenticationDigests authDigest, byte[] authSecret, PrivacyProtocols privProtocol, byte[] privSecret)
        {
            var packet = new SnmpV3Packet();

            packet.Pdu.Type = PduType.V2Trap;
            packet.authPriv(Encoding.UTF8.GetBytes(senderUserName), authSecret, authDigest, privSecret, privProtocol);
            packet.SetEngineId(engineId);
            packet.SetEngineTime(senderEngineBoots, senderEngineTime);
            packet.ScopedPdu.TrapObjectID.Set(trapObjectID);
            packet.ScopedPdu.TrapSysUpTime.Value = senderUpTime;
            packet.ScopedPdu.VbList.Add(varList);
            packet.MsgFlags.Reportable = false;
            SendV3Trap(packet, receiver, receiverPort);
        }
예제 #8
0
 /// <summary>
 /// Construct Vb with the OID and value
 /// </summary>
 /// <param name="oid">OID</param>
 /// <param name="value">Value</param>
 public Vb(Oid oid, AsnType value)
     : this(oid) {
     _value = (AsnType)value.Clone();
 }
 private int getSNMPParam(string ipAddr, SnmpSharpNet.Oid oid_needed)
 {
     try
     {
         OctetString     community = new OctetString("public");
         AgentParameters param     = new AgentParameters(community);
         param.Version = SnmpVersion.Ver2;
         IpAddress agent   = new IpAddress(ipAddr);
         UdpTarget target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
         Oid       rootOid = new Oid(oid_needed);
         Oid       lastOid = (Oid)rootOid.Clone();
         Pdu       pdu     = new Pdu(PduType.GetBulk);
         pdu.NonRepeaters   = 0;
         pdu.MaxRepetitions = 5;
         while (lastOid != null)
         {
             if (pdu.RequestId != 0)
             {
                 pdu.RequestId += 1;
             }
             pdu.VbList.Clear();
             pdu.VbList.Add(lastOid);
             try
             {
                 SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                 if (result != null)
                 {
                     if (result.Pdu.ErrorStatus != 0)
                     {
                         throw new NullReferenceException();
                     }
                     else
                     {
                         foreach (Vb v in result.Pdu.VbList)
                         {
                             if (rootOid.IsRootOf(v.Oid))
                             {
                                 if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                 {
                                     lastOid = null;
                                 }
                                 else
                                 {
                                     lastOid = v.Oid;
                                 }
                                 target.Close();
                                 return(Convert.ToInt32(v.Value));
                             }
                             else
                             {
                                 lastOid = null;
                             }
                         }
                     }
                 }
                 else
                 {
                     throw new NullReferenceException();
                 }
             }
             catch (NullReferenceException)
             {
             }
         }
         target.Close();
         return(0);
     }
     catch (Exception)
     {
         return(0);
     }
 }
예제 #10
0
        /// <summary>
        ///     Construct and send SNMP v3 noAuthNoPriv Trap
        /// </summary>
        /// <param name="receiver">Trap receiver IP address</param>
        /// <param name="receiverPort">Trap receiver UDP port number</param>
        /// <param name="engineId">Sender SNMP engineId</param>
        /// <param name="senderEngineBoots">Sender SNMP engine boots</param>
        /// <param name="senderEngineTime">Sender SNMP engine time</param>
        /// <param name="senderUserName">Security (user) name</param>
        /// <param name="senderUpTime">Sender upTime</param>
        /// <param name="trapObjectID">Trap object ID</param>
        /// <param name="varList">Variable binding list</param>
        public void SendV3Trap(IpAddress receiver, int receiverPort, byte[] engineId, int senderEngineBoots,
                               int senderEngineTime, string senderUserName, uint senderUpTime, Oid trapObjectID, VbCollection varList)
        {
            var packet = new SnmpV3Packet();

            packet.Pdu.Type = PduType.V2Trap;
            packet.NoAuthNoPriv(Encoding.UTF8.GetBytes(senderUserName));
            packet.SetEngineId(engineId);
            packet.SetEngineTime(senderEngineBoots, senderEngineTime);
            packet.ScopedPdu.TrapObjectID.Set(trapObjectID);
            packet.ScopedPdu.TrapSysUpTime.Value = senderUpTime;
            packet.ScopedPdu.VbList.Add(varList);
            packet.MsgFlags.Reportable = false;
            SendV3Trap(packet, receiver, receiverPort);
        }
예제 #11
0
        /// <summary>
        /// Create a new Variable Binding with the supplied OID and value and add to the end of the Vb collection
        /// </summary>
        /// <param name="oid">OID to assign to the new Vb</param>
        /// <param name="value">SNMP value to assign to the new Vb</param>
        public void Add(Oid oid, AsnType value)
        {
            Vb v = new Vb(oid, value);

            Add(v);
        }
예제 #12
0
 /// <summary>
 /// SET class value from supplied Vb class
 /// </summary>
 /// <param name="value">Vb class to clone data from</param>
 public void Set(Vb value)
 {
     this._oid   = (Oid)value.Oid.Clone();
     this._value = (Oid)value.Value.Clone();
 }
예제 #13
0
 /// <summary>
 /// Construct Vb with the oid value and <seealso cref="Null"/> value.
 /// </summary>
 /// <param name="oid">String representing OID value to set</param>
 public Vb(string oid)
     : this()
 {
     _oid   = new Oid(oid);
     _value = new Null();
 }
예제 #14
0
 /// <summary>Compares the passed object identifier against self
 /// to determine if self is the root of the passed object.
 /// If the passed object is in the same root tree as self
 /// then a true value is returned. Otherwise a false value
 /// is returned from the object.
 /// </summary>
 /// <param name="leaf">The object to be tested
 /// </param>
 /// <returns> True if leaf is in the tree.
 /// </returns>
 public virtual bool IsRootOf(Oid leaf)
 {
     return(Compare(leaf._data, _data == null ? 0 : _data.Length) == 0);
 }
예제 #15
0
        /// <summary>
        ///     Construct and send SNMP v1 Trap
        /// </summary>
        /// <param name="receiver">Receiver IP address</param>
        /// <param name="receiverPort">Receiver UDP port number</param>
        /// <param name="community">SNMP community name</param>
        /// <param name="senderSysObjectID">Senders sysObjectID</param>
        /// <param name="senderIpAdress">Sender IP address</param>
        /// <param name="genericTrap">Generic trap code</param>
        /// <param name="specificTrap">Specific trap code</param>
        /// <param name="senderUpTime">Senders sysUpTime</param>
        /// <param name="varList">Variable binding list</param>
        public void SendV1Trap(IpAddress receiver, int receiverPort, string community, Oid senderSysObjectID,
                               IpAddress senderIpAdress, int genericTrap, int specificTrap, uint senderUpTime,
                               VbCollection varList)
        {
            var packet = new SnmpV1TrapPacket(community);

            packet.Pdu.Generic  = genericTrap;
            packet.Pdu.Specific = specificTrap;
            packet.Pdu.AgentAddress.Set(senderIpAdress);
            packet.Pdu.TimeStamp = senderUpTime;
            packet.Pdu.VbList.Add(varList);
            packet.Pdu.Enterprise.Set(senderSysObjectID);
            SendV1Trap(packet, receiver, receiverPort);
        }
예제 #16
0
 /// <summary>Constructor. Duplicate objectId value from argument.</summary>
 /// <param name="second">objectId whose value is used to initilize this class value</param>
 public Oid(Oid second)
     : this()
 {
     Set(second);
 }
예제 #17
0
 /// <summary>
 /// Construct Vb with the supplied OID and Null value
 /// </summary>
 /// <param name="oid">OID</param>
 public Vb(Oid oid)
     : this()
 {
     _oid   = (Oid)oid.Clone();
     _value = new Null();
 }