Пример #1
0
        /// <summary>
        /// SNMP GET-NEXT request
        /// </summary>
        /// <example>SNMP GET-NEXT request:
        /// <code>
        /// String snmpAgent = "10.10.10.1";
        /// String snmpCommunity = "private";
        /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
        /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(SnmpVersion.Ver1, new string[] { "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"
        /// </code>
        /// </example>
        /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
        /// <param name="oidList">List of request OIDs in string dotted decimal format.</param>
        /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
        public Dictionary <Oid, AsnType> GetNext(SnmpVersion version, string[] oidList)
        {
            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);
            }
            Pdu pdu = new Pdu(PduType.GetNext);

            foreach (string s in oidList)
            {
                pdu.VbList.Add(s);
            }
            return(GetNext(version, pdu));
        }
Пример #2
0
        /// <summary>
        /// Funkcja realizująca polecenie GetNext agenta SNMP.
        /// SnmpVersion: SnmpVersion.Ver1 lub SnmpVersion.Ver2 lub SnmpVersion.Ver3. Zalecana Ver2.
        /// oidList: Lista identyfikatorów OID, których obiekty ma znalezc funkcja.
        /// </summary>
        /// <param name="version"></param>
        /// <param name="oid"></param>
        /// <param name="agent"></param>
        /// <returns></returns>
        public SnmpPacket GetNextRequest(SnmpVersion version, string[] oidList, IPAddress agent)
        {
            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetNext);

            foreach (var oid in oidList)
            {
                pdu.VbList.Add(oid);
            }

            // SNMP community name
            OctetString community = new OctetString(snmp.Community);

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);

            // Set SNMP version to 1 (or 2)
            param.Version = version;

            // Make SNMP request
            SnmpPacket result = target.Request(pdu, param);


            return(result);
        }
Пример #3
0
        /// <summary>
        /// SNMP SET request
        /// </summary>
        /// <example>Set operation in SNMP version 1:
        /// <code>
        /// String snmpAgent = "10.10.10.1";
        /// String snmpCommunity = "private";
        /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
        /// // Create a request Pdu
        /// List&lt;Vb&gt; vbList = new List&lt;Vb&gt;();
        /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0
        /// OctetString setValue = new OctetString("My personal toy");
        /// vbList.Add(new Vb(setOid, setValue));
        /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Set(SnmpVersion.Ver1, list.ToArray());
        /// if( result == null ) {
        ///   Console.WriteLine("Request failed.");
        /// } else {
        ///   Console.WriteLine("Success!");
        /// }
        /// </code>
        ///
        /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
        /// </example>
        /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
        /// <param name="vbs">Vb array containing Oid/AsnValue pairs for the SET operation</param>
        /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
        public Dictionary <Oid, AsnType> Set(SnmpVersion version, Vb[] vbs)
        {
            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);
            }
            Pdu pdu = new Pdu(PduType.Set);

            foreach (Vb vb in vbs)
            {
                pdu.VbList.Add(vb);
            }
            return(Set(version, pdu));
        }
Пример #4
0
        private User User; // Provides SNMPv3 User details
        #endregion Properties

        #region Interface Methods
        public bool OpenSession(IPAddress deviceIp, short port, string community, int version, string username, string authPass, string privPass)
        {
            try
            {
                DeviceEndPoint = new IPEndPoint(deviceIp, port);
                Community      = community;
                Version        = GetVersionByInt(version);

                if (Version == SnmpVersion.Three)
                {
                    // TODO: Remote Operator Panel shall encrypt in Aes256.
                    User = new User(username, authPass, AuthenticationProtocol.Sha, privPass, PrivacyProtocol.Aes128);
                }

                _manager = new Manager();
                using (var mibFile = new FileStream(Settings.Default.MIBPath, FileMode.Open, FileAccess.Read))
                {
                    _manager.Mib.Parse(mibFile);
                    _manager.Mib.GenerateNodes();
                }

                _manager.Security.TrapUsers.Add(User);
                _manager.Start(new NotificationReceived(TrapReceived), new Dart.Snmp.IPEndPoint("", 162), true, null);

                _isOpen = true;
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Пример #5
0
        /// <summary>
        /// Reset the class. Initialize all member values to class defaults.
        /// </summary>
        public void Reset()
        {
            _address = new IpAddress(System.Net.IPAddress.Loopback);
            _port    = 161;
            _version = SnmpVersion.Ver3;
            _timeout = 2000;
            _retry   = 1;

            _engineId    = new OctetString();
            _engineBoots = new Integer32();
            _engineTime  = new Integer32();

            _engineTimeStamp = DateTime.MinValue;

            _privacyProtocol        = PrivacyProtocols.None;
            _authenticationProtocol = AuthenticationDigests.None;

            _privacySecret        = new MutableByte();
            _authenticationSecret = new MutableByte();

            _contextEngineId = new OctetString();
            _contextName     = new OctetString();
            _securityName    = new OctetString();

            // max message size is initialized to 64KB by default. It will be
            // to the smaller of the two values after discovery process
            _maxMessageSize = new Integer32(64 * 1024);

            _reportable = true;
        }
Пример #6
0
        private static int GetMaxRepetitions(PduType type, SnmpVersion version,
                                             int vbCount, int rowCount, int maxRows, int rowsPerQuery)
        {
            if (type != PduType.GetBulk)
            {
                return(0);
            }

            // This is a simple heuristic algorithm that allows to limit
            // the size of a GetBulk response (to fit in a MTU packet).
            if (rowsPerQuery <= 0)
            {
                int header = version == SnmpVersion.SNMPv3
                                        ? MAX_HEADER_V3_SIZE_ : MAX_HEADER_V1_SIZE_;
                rowsPerQuery = ((MAX_DATAGRAM_SIZE_ - header)
                                / vbCount) / AVG_VARBIND_SIZE_;
            }

            int toRead = maxRows - rowCount;

            if (toRead < rowsPerQuery && toRead > 0)
            {
                rowsPerQuery = toRead;
            }
            return(rowsPerQuery);
        }
Пример #7
0
 /// <summary>
 /// Construct from all the parameters.
 /// </summary>
 /// <param name="port">The port number to use for the queries.</param>
 /// <param name="protocolVersion">The SNMP protocol version to use for the queries.</param>
 /// <param name="community">The community string to use for the queries.</param>
 /// <param name="timeout">The query timeout.</param>
 /// <param name="retries">The SNMP peer maximum retires setting. Value of 0 will result in a single request with no retries.</param>
 /// <param name="ver2cMaximumValuesPerRequest">A value telling the SNMP Agent how many GETNEXT like variables to retrieve</param>
 /// <param name="ver2cMaximumRequests">A value telling the SNMP Agent how many VBs to include in a single request.<br/>
 /// Only valid on GETBULK requests.</param>
 /// <param name="enableCaching">Value indicating whether to use caching of non-volatile data.</param>
 /// <param name="loginUser">The user name for logins (if needed).</param>
 /// <param name="loginPassword">The password for logins (if needed).</param>
 /// <param name="allowedApis">The allowed APIs. By default, only SNMP is allowed.</param>
 /// <param name="querierClassHint">If not null or empty, a full qualified class name of the handler class to use (if possible).</param>
 public QuerierOptions(
     int port,
     SnmpVersion protocolVersion,
     OctetString community,
     TimeSpan timeout,
     int retries,
     int ver2cMaximumValuesPerRequest,
     int ver2cMaximumRequests,
     bool enableCaching,
     string loginUser,
     string loginPassword,
     QueryApis allowedApis,
     string querierClassHint = null)
 {
     this.Port                         = port;
     this.ProtocolVersion              = protocolVersion;
     this.Community                    = community;
     this.Timeout                      = timeout;
     this.Retries                      = retries;
     this.Ver2cMaximumRequests         = ver2cMaximumRequests;
     this.Ver2cMaximumValuesPerRequest = ver2cMaximumValuesPerRequest;
     this.EnableCaching                = enableCaching;
     this.LoginUser                    = loginUser;
     this.LoginPassword                = loginPassword;
     this.AllowedApis                  = allowedApis;
     this.QuerierClassHint             = querierClassHint;
 }
Пример #8
0
 /// <summary>
 /// Constructor
 /// </summary>
 public CTarget()
 {
     _address   = new IpAddress(System.Net.IPAddress.Loopback);
     _port      = 161;
     _version   = SnmpVersion.Ver2;
     _timeout   = 2000;
     _retry     = 1;
     _community = "public";
 }
Пример #9
0
 /// <summary>
 /// Constructor
 /// </summary>
 public CTarget()
 {
     _address = new IpAddress(System.Net.IPAddress.Loopback);
     _port = 161;
     _version = SnmpVersion.Ver2;
     _timeout = 2000;
     _retry = 1;
     _community = "public";
 }
Пример #10
0
 public Entity(string ip, SnmpVersion version, string communityName, int port, PduType pduType, string oid)
 {
     this.IP            = ip;
     this.Version       = version;
     this.CommunityName = communityName;
     this.Port          = port;
     this.PduType       = pduType;
     this.OID           = new Oid(oid);
 }
Пример #11
0
        /// <summary>
        /// Converts the Asn.1 encoded byte array to SNMP Datagram.
        /// </summary>
        /// <param name="bytes">The asn.1 encoded bytes.</param>
        /// <returns>
        /// SnmpPacket
        /// </returns>
        /// <exception cref="System.ArgumentNullException">bytes</exception>
        /// <exception cref="System.IO.InvalidDataException">Snmp Version V3 not supported</exception>
        /// <exception cref="System.NotImplementedException">SNMP v1 traps are not yet implemented</exception>
        public static SnmpDatagram ToSnmpDatagram(this byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                throw new ArgumentNullException("bytes");
            }

            int offset = 0;
            int length;

            offset = bytes.NextValueLength(offset, -1, -1, -1, out length);
            offset = bytes.NextValueLength(offset, -1, -1, (int)Asn1Tag.Integer, out length);
            SnmpVersion snmpVersion = (SnmpVersion)bytes.ReadInteger(offset, length);

            offset += length;

            if (snmpVersion == SnmpVersion.V3)
            {
                throw new InvalidDataException("Snmp Version V3 not supported");
            }

            offset = bytes.NextValueLength(offset, -1, -1, (int)Asn1Tag.OctetString, out length);
            string community = bytes.ReadOctetString(offset, length);

            offset += length;

            PduType pduType = (PduType)(bytes[offset++] & 0x1F);

            if (pduType == PduType.Trap)
            {
                throw new NotImplementedException("SNMP v1 traps are not yet implemented");
            }

            offset = bytes.ReadLength(offset, out length);

            offset = bytes.NextValueLength(offset, -1, -1, (int)Asn1Tag.Integer, out length);
            int requestId = bytes.ReadInteger(offset, length);

            offset += length;

            offset = bytes.NextValueLength(offset, -1, -1, (int)Asn1Tag.Integer, out length);
            SnmpErrorStatus errorStatus = (SnmpErrorStatus)bytes.ReadInteger(offset, length);

            offset += length;

            offset = bytes.NextValueLength(offset, -1, -1, (int)Asn1Tag.Integer, out length);
            int errorIndex = bytes.ReadInteger(offset, length);

            offset += length;

            offset = bytes.NextValueLength(offset, (int)Asn1Class.Universal, (int)ConstructType.Constructed, (int)Asn1Tag.Sequence, out length);
            VarBind[] varBinds = bytes.ReadVarBinds(offset, length);

            return(new SnmpDatagram(new SnmpHeader(snmpVersion, community), new SnmpPDU(pduType, varBinds, requestId, errorStatus, errorIndex)));
        }
Пример #12
0
 private void Init(string adresseIP, int retry, int timeout, SnmpVersion version, string communaute,
                   int portLocal, int portDistant)
 {
     m_adresseIP   = adresseIP;
     m_retry       = retry;
     m_timeout     = timeout;
     m_version     = version;
     m_communaute  = communaute;
     m_portLocal   = portLocal;
     m_portDistant = portDistant;
 }
Пример #13
0
        public SnmpHelper(string commnuity, string destIpAddr, long destPort, long trapPort
                          , SnmpVersion version, long timeOut)
        {
            this.m_Community  = commnuity;
            this.m_DestIPAddr = destIpAddr;
            this.m_DestPort   = destPort;
            this.m_TrapPort   = trapPort;
            this.m_Version    = version;
            this.m_TimeOut    = timeOut;

            ConnectToAgent(m_Community, m_DestIPAddr);
        }
Пример #14
0
        public IEnumerable<SnmpResult> GetBulk(SnmpVersion version, int maxBulkRepetiotions, string octetString, Oid oid, IPAddress ipAddress = null, string hostname = null, string userLoginV3 = null, string passwordV3 = null)
        {
            if (ipAddress != null)
            {
                return GetBulkOperation(version, ipAddress, maxBulkRepetiotions, octetString, oid);
            }
            else if (!string.IsNullOrEmpty(hostname))
            {
                return GetBulkOperation(version, GetIpAddressFromHostName(hostname), maxBulkRepetiotions, octetString, oid);
            }

            return null;
        }
Пример #15
0
        public IEnumerable<SnmpResult> Walk(SnmpVersion version, string octetString, Oid oid, WalkingMode walkMode, IPAddress ipAddress = null, string hostname = null, string userLoginV3 = null, string passwordV3 = null)
        {
            if (ipAddress != null)
            {
                return WalkOperation(version, ipAddress, octetString, oid, walkMode);
            }
            else if (!string.IsNullOrEmpty(hostname))
            {
                return WalkOperation(version, GetIpAddressFromHostName(hostname), octetString, oid, walkMode);
            }

            return null;
        }
        /// <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 (rootOid.Length < 2)
            {
                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)
                {
                    // error of some sort happened. abort...
                    return(null);
                }
                foreach (KeyValuePair <Oid, AsnType> entry in val)
                {
                    if (root.IsRootOf(entry.Key))
                    {
                        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);
        }
Пример #17
0
        private void btnExecute_Click(object sender, EventArgs e)
        {
            if (txtOIDValue.Text.Trim().Length <= 0)
            {
                toast.ShowAlert("Xin hãy nhập OID:");
            }
            else
            {
                Pdu pdu = new Pdu();
                Dictionary <Oid, AsnType> dicOID = null;
                SimpleSnmp snmp = null;

                loadSNMPParameters(out snmp);
                SnmpVersion version = SnmpVersion.Ver2;
                if (cbbSNMPVersion.SelectedItem.Equals("1"))
                {
                    version = SnmpVersion.Ver1;
                }

                VbCollection vbList = new VbCollection();
                vbList.Add(txtOIDValue.Text);

                pdu.SetVbList(vbList);

                switch (cbbCommand.SelectedItem)
                {
                case "Get":
                    pdu.Type = PduType.Get;
                    dicOID   = snmp.Get(version, pdu);
                    break;

                case "Get Next":
                    pdu.Type = PduType.GetNext;
                    dicOID   = snmp.Get(version, pdu);
                    break;

                case "Get Bulk":
                    pdu.Type            = PduType.GetBulk;
                    snmp.MaxRepetitions = 20;
                    dicOID = snmp.Get(version, pdu);
                    break;
                }


                if (dicOID != null && dicOID.Count > 0)
                {
                    this.mgResponseQueue.Enqueue(dicOID);
                }
            }
        }
Пример #18
0
 public VersionCode ToVersionCodeConverter(SnmpVersion version)
 {
     switch (version)
     {
         case SnmpVersion.V1:
             return VersionCode.V1;
         case SnmpVersion.V2:
             return VersionCode.V2;
         case SnmpVersion.V3:
              return VersionCode.V3;
         default:
             throw new ArgumentOutOfRangeException(nameof(version), version, null);
     }
 }
Пример #19
0
        /// <summary>
        /// Performs procedure for *QuerySystemData tests.
        /// </summary>
        /// <param name="address">The address to test with.</param>
        /// <param name="snmpVersion">The SNMP protocol version to use.</param>
        /// <param name="useCache">Value indicating whether to use caching of non-volatile data.</param>
        /// <param name="allowedApis">The list of allowed APIs</param>
        private static void QueryAndPrintSystemData(IpAddress address, SnmpVersion snmpVersion, bool useCache = false, QueryApis allowedApis = QueryApis.Snmp)
        {
            var querier = SnmpQuerierFactory.Instance.Create(address.ToString(), QuerierOptions.Default.WithProtocolVersion(snmpVersion).WithCaching(useCache).WithAllowedApis(allowedApis));

            Assert.NotNull(querier, "Create(...) returned null");

            var systemData = querier.SystemData;

            Assert.NotNull(systemData, "querier.SystemData returned null");

            systemData.ForceEvaluateAll();

            Console.WriteLine("Obtained system data:");
            Console.WriteLine(new BlockTextFormatter().Format(systemData));
        }
Пример #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SnmpSimpleDatagram" /> class.
 /// </summary>
 /// <param name="snmpDatagramInput">The SNMP datagram input.</param>
 public SnmpSimpleDatagram(SnmpDatagram snmpDatagramInput)
 {
     snmpDatagram = snmpDatagramInput;
     Version      = snmpDatagram.Header.Version;
     Community    = snmpDatagram.Header.Community;
     PDUType      = snmpDatagram.PduV2c.PduType;
     RequestId    = snmpDatagram.PduV2c.RequestId;
     ErrorStatus  = snmpDatagram.PduV2c.ErrorStatus;
     ErrorIndex   = snmpDatagram.PduV2c.ErrorIndex;
     VarBinds     = new List <KeyValuePair <string, object> >();
     for (int i = 0; i < snmpDatagram.PduV2c.VarBinds.Count; i++)
     {
         var varBind = snmpDatagram.PduV2c.VarBinds[i];
         VarBinds.Add(new KeyValuePair <string, object>(varBind.Oid.ToString(), varBind.Value));
     }
 }
Пример #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SnmpSimpleDatagram" /> class.
 /// </summary>
 /// <param name="snmpDatagramInput">The SNMP datagram input.</param>
 public SnmpSimpleDatagram(SnmpDatagram snmpDatagramInput)
 {
     snmpDatagram = snmpDatagramInput;
     Version = snmpDatagram.Header.Version;
     Community = snmpDatagram.Header.Community;
     PDUType = snmpDatagram.PduV2c.PduType;
     RequestId = snmpDatagram.PduV2c.RequestId;
     ErrorStatus = snmpDatagram.PduV2c.ErrorStatus;
     ErrorIndex = snmpDatagram.PduV2c.ErrorIndex;
     VarBinds = new List<KeyValuePair<string, object>>();
     for(int i=0 ; i< snmpDatagram.PduV2c.VarBinds.Count; i++)
     {
         var varBind = snmpDatagram.PduV2c.VarBinds[i];
         VarBinds.Add(new KeyValuePair<string, object>(varBind.Oid.ToString(), varBind.Value));
     }
 }
 /// <summary>
 /// SNMP GET-NEXT request
 /// </summary>
 /// <example>SNMP GET-NEXT request:
 /// <code>
 /// String snmpAgent = "10.10.10.1";
 /// String snmpCommunity = "private";
 /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
 /// // Create a request Pdu
 /// Pdu pdu = new Pdu();
 /// pdu.Type = SnmpConstants.GETNEXT; // type GETNEXT
 /// pdu.VbList.Add("1.3.6.1.2.1.1");
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(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> GetNext(SnmpVersion version, Pdu pdu)
 {
     if (!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)
     {
         return(null);
     }
     try
     {
         _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
         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_ENDOFMIBVIEW) ||
                         (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE) ||
                         (v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT))
                     {
                         break;
                     }
                     res.Add(v.Oid, v.Value);
                 }
                 _target.Close();
                 _target = null;
                 return(res);
             }
         }
     }
     catch (Exception ex)
     {
         ex.GetType();                 // just to stop a warning
     }
     _target.Close();
     _target = null;
     return(null);
 }
Пример #23
0
        /// <summary>
        /// Performs procedure for *QueryInterfaceData tests.
        /// </summary>
        /// <param name="address">The address to test with.</param>
        /// <param name="snmpVersion">The SNMP protocol version to use.</param>
        /// <param name="useCache">Value indicating whether to use caching of non-volatile data.</param>
        /// <param name="allowedApis">The list of allowed APIs</param>
        private static void QueryAndPrintInterfaces(IpAddress address, SnmpVersion snmpVersion, bool useCache = false, QueryApis allowedApis = QueryApis.Snmp)
        {
            var querier = SnmpQuerierFactory.Instance.Create(address.ToString(), QuerierOptions.Default.WithProtocolVersion(snmpVersion).WithCaching(useCache).WithAllowedApis(allowedApis));

            Assert.NotNull(querier, "Create(...) returned null");

            var networkInterfaceDetails = querier.NetworkInterfaceDetails;

            Assert.NotNull(networkInterfaceDetails, "querier.NetworkInterfaceDetails returned null");

            networkInterfaceDetails.ForceEvaluateAll();

            Assert.NotNull(networkInterfaceDetails.Details, "querier.NetworkInterfaceDetails.Details returned null");
            Assert.Greater(networkInterfaceDetails.Details.Count, 0, "querier.NetworkInterfaceDetails.Details.Count == 0");

            Console.WriteLine("Obtained interface details:");
            Console.WriteLine(new BlockTextFormatter().Format(networkInterfaceDetails));
        }
Пример #24
0
        /// <summary>
        /// Performs procedure for BGP tests.
        /// </summary>
        /// <param name="address">The address to test with.</param>
        /// <param name="snmpVersion">The SNMP protocol version to use.</param>
        /// <param name="useCache">Value indicating whether to use caching of non-volatile data.</param>
        /// <param name="allowedApis">The list of allowed APIs</param>
        private static void QueryAndPrintBgpPeers(IpAddress address, SnmpVersion snmpVersion, bool useCache = false, QueryApis allowedApis = QueryApis.VendorSpecific)
        {
            var querier = SnmpQuerierFactory.Instance.Create(address.ToString(), QuerierOptions.Default.WithProtocolVersion(snmpVersion).WithCaching(useCache).WithAllowedApis(allowedApis));

            var systemData = querier.SystemData;

            systemData.ForceEvaluateAll();

            Assert.NotNull(querier, "Create(...) returned null");

            var bgpPeers = querier.FetchBgpPeers(null);

            Assert.NotNull(bgpPeers, "querier.BgpPeers returned null");

            bgpPeers.ForceEvaluateAll();

            Console.WriteLine("Obtained BGP peers:");
            Console.WriteLine(new BlockTextFormatter().Format(bgpPeers));
        }
Пример #25
0
        /// <summary>
        /// Sets the given protocol version and community.
        /// </summary>
        /// <param name="protocolVersion">The new protocol version to use.</param>
        /// <param name="community">The new communitiy to use.</param>
        private void SetVersionAndCommunity(SnmpVersion protocolVersion, OctetString community)
        {
            if ((this.QueryParameters?.Version == protocolVersion) && (this.QueryParameters?.Community == community))
            {
#if DEBUG
                log.Debug($"Device '{this.Address}': SNMP community '{community}' and protocol version '{protocolVersion}' already set. No change.");
#endif
                return;
            }

#if DEBUG
            log.Debug($"Device '{this.Address}': From now on using SNMP community '{community}' and protocol version '{protocolVersion}'");
#endif
            this.QueryParameters = new AgentParameters(community)
            {
                Version = protocolVersion,
                DisableReplySourceCheck = true
            };
        }
Пример #26
0
        private void comboBoxVersion_SelectedIndexChanged(object sender, EventArgs e)
        {
            SnmpVersion version = (SnmpVersion)((DictionaryEntry)comboBoxVersion.SelectedItem).Value;

            if (version == SnmpVersion.Ver1 && comboBoxGetStyle.SelectedIndex == 2)
            {
                MessageBox.Show("Ver1不支持Bulk...", "提示");
                comboBoxVersion.SelectedIndex = 1;
            }
            else if (version == SnmpVersion.Ver3 && comboBoxGetStyle.SelectedIndex == 3)
            {
                MessageBox.Show("后续版本增加Ver3版本SET支持...", "提示");
                comboBoxVersion.SelectedIndex = 0;
            }
            else
            {
                snmpObj.Version = version;
            }
        }
        /// <summary>
        /// SNMP SET request
        /// </summary>
        /// <example>Set operation in SNMP version 1:
        /// <code>
        /// String snmpAgent = "10.10.10.1";
        /// String snmpCommunity = "private";
        /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
        /// // Create a request Pdu
        /// List&lt;Vb&gt; vbList = new List&lt;Vb&gt;();
        /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0
        /// OctetString setValue = new OctetString("My personal toy");
        /// vbList.Add(new Vb(setOid, setValue));
        /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Set(SnmpVersion.Ver1, list.ToArray());
        /// if( result == null ) {
        ///   Console.WriteLine("Request failed.");
        /// } else {
        ///   Console.WriteLine("Success!");
        /// }
        /// </code>
        ///
        /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
        /// </example>
        /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
        /// <param name="vbs">Vb array containing Oid/AsnValue pairs for the SET operation</param>
        /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
        public Dictionary <Oid, AsnType> Set(SnmpVersion version, Vb[] vbs)
        {
            if (!Valid)
            {
                return(null);
            }
            // function only works on SNMP version 1 and SNMP version 2 requests
            if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
            {
                return(null);
            }
            Pdu pdu = new Pdu(PduType.Set);

            foreach (Vb vb in vbs)
            {
                pdu.VbList.Add(vb);
            }
            return(Set(version, pdu));
        }
        /// <summary>
        /// SNMP GET-NEXT request
        /// </summary>
        /// <example>SNMP GET-NEXT request:
        /// <code>
        /// String snmpAgent = "10.10.10.1";
        /// String snmpCommunity = "private";
        /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
        /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(SnmpVersion.Ver1, new string[] { "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"
        /// </code>
        /// </example>
        /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
        /// <param name="oidList">List of request OIDs in string dotted decimal format.</param>
        /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
        public Dictionary <Oid, AsnType> GetNext(SnmpVersion version, string[] oidList)
        {
            if (!Valid)
            {
                return(null);
            }
            // function only works on SNMP version 1 and SNMP version 2 requests
            if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
            {
                return(null);
            }
            Pdu pdu = new Pdu(PduType.GetNext);

            foreach (string s in oidList)
            {
                pdu.VbList.Add(s);
            }
            return(GetNext(version, pdu));
        }
Пример #29
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="peerName">节点主机名</param>
        /// <param name="peerPort">端口</param>
        /// <param name="community">社区名</param>
        /// <param name="SnmpVersion">SNMP协议版本</param>
        public SnmpHelper(String peerName, Int32 peerPort, String community, Int32 SnmpVersion)
        {
            this.PeerName  = peerName;
            this.PeerPort  = peerPort;
            this.Community = community;
            switch (SnmpVersion)
            {
            case 1:
                this.SnmpVersion = SnmpSharpNet.SnmpVersion.Ver1;
                break;

            case 2:
                this.SnmpVersion = SnmpSharpNet.SnmpVersion.Ver2;
                break;

            case 3:
                this.SnmpVersion = SnmpSharpNet.SnmpVersion.Ver3;
                break;
            }

            SimpleSnmp = new SimpleSnmp(peerName, peerPort, community);
        }
 /// <summary>
 /// SNMP SET request
 /// </summary>
 /// <example>Set operation in SNMP version 1:
 /// <code>
 /// String snmpAgent = "10.10.10.1";
 /// String snmpCommunity = "private";
 /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
 /// // Create a request Pdu
 /// Pdu pdu = new Pdu();
 /// pdu.Type = SnmpConstants.SET; // type SET
 /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0
 /// OctetString setValue = new OctetString("My personal toy");
 /// pdu.VbList.Add(setOid, setValue);
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Set(SnmpVersion.Ver1, pdu);
 /// if( result == null ) {
 ///   Console.WriteLine("Request failed.");
 /// } else {
 ///   Console.WriteLine("Success!");
 /// }
 /// </code>
 ///
 /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
 /// </example>
 /// <param name="version">SNMP protocol version number. 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> Set(SnmpVersion version, Pdu pdu)
 {
     if (!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)
     {
         return(null);
     }
     try
     {
         _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
         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)
                 {
                     res.Add(v.Oid, v.Value);
                 }
                 _target.Close();
                 _target = null;
                 return(res);
             }
         }
     }
     catch
     {
     }
     _target.Close();
     _target = null;
     return(null);
 }
Пример #31
0
        private static Oid[] ProcessSnmpv1EndOfMIB(SnmpVersion version,
                                                   Oid[] columnOids, Pdu request, SnmpException e)
        {
            int index = 0;

            if (version == SnmpVersion.SNMPv1 &&
                e.ErrorStatus == SnmpError.NoSuchName &&
                (index = e.ErrorIndex) > 0 &&
                index <= request.Count)
            {
                index--;
                for (int i = 0, j = 0; i < columnOids.Length; i++)
                {
                    if (columnOids[i] != null && j++ == index)
                    {
                        columnOids[i] = null;
                        break;
                    }
                }

                Vb[]  vbs  = request.Vbs;
                Oid[] oids = new Oid[vbs.Length - 1];
                for (int i = 0; i < index; i++)
                {
                    oids[i] = vbs[i].Oid;
                }
                for (int i = index; i < oids.Length; i++)
                {
                    oids[i] = vbs[i + 1].Oid;
                }
                return(oids);
            }
            else
            {
                return(null);
            }
        }
Пример #32
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>
        /// <param name="tryGetBulk">this param is used to use get bulk on V2 requests</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(bool tryGetBulk, 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
                {
                    if (tryGetBulk == true)
                    {
                        val = GetBulk(new string[] { lastOid.ToString() });
                    }
                    else
                    {
                        val = GetNext(version, new string[] { lastOid.ToString() });
                    }
                }
                // check that we have a result
                if (val == null)
                {
                    // error of some sort happened. abort...
                    return null;
                }
                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;
        }
Пример #33
0
 /// <summary>
 /// SNMP GET-NEXT request
 /// </summary>
 /// <example>SNMP GET-NEXT request:
 /// <code>
 /// String snmpAgent = "10.10.10.1";
 /// String snmpCommunity = "private";
 /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(SnmpVersion.Ver1, new string[] { "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"
 /// </code>
 /// </example>
 /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
 /// <param name="oidList">List of request OIDs in string dotted decimal format.</param>
 /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
 public Dictionary<Oid, AsnType> GetNext(SnmpVersion version, string[] oidList)
 {
     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;
     }
     Pdu pdu = new Pdu(PduType.GetNext);
     foreach (string s in oidList)
     {
         pdu.VbList.Add(s);
     }
     return GetNext(version, pdu);
 }
Пример #34
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;
 }
Пример #35
0
 /// <summary>
 /// Creates a new object that is a copy of this object with modified SNMP protocol version.
 /// </summary>
 /// <param name="protocolVersion">The new SNMP protocol version to use for the queries.</param>
 /// <returns>A new object that is a copy of this object with modified SNMP protocol version.</returns>
 public QuerierOptions WithProtocolVersion(SnmpVersion protocolVersion)
 {
     return(new QuerierOptions(this.Port, protocolVersion, this.Community, this.Timeout, this.Retries, this.Ver2cMaximumValuesPerRequest, this.Ver2cMaximumRequests, this.EnableCaching, this.LoginUser, this.LoginPassword, this.AllowedApis));
 }
Пример #36
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="version">SNMP Protocol version</param>
 /// <param name="community">SNMP community name</param>
 /// <param name="disableReplySourceCheck">Should reply source IP address/port number be checked on reply reception</param>
 public AgentParameters(SnmpVersion version, OctetString community, bool disableReplySourceCheck)
     : this(version, community)
 {
     _disableReplySourceCheck = disableReplySourceCheck;
 }
Пример #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SnmpHeader" /> struct.
 /// </summary>
 /// <param name="version">The Snmp version.</param>
 /// <param name="community">The Snmp Community.</param>
 public SnmpHeader(SnmpVersion version, string community)
 {
     this.Version = version;
     this.Community = community;
 }
Пример #38
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="version">SNMP Protocol version</param>
 /// <param name="community">SNMP community name</param>
 public AgentParameters(SnmpVersion version, OctetString community)
     : this(version)
 {
     _community.Set(community);
 }
Пример #39
0
        private IEnumerable<SnmpResult> WalkOperation(SnmpVersion version, IPAddress ipAddress, string octetString, Oid oid, WalkingMode walkMode)
        {
            _log.Info("SnmpEngine.WalkOperation(): Started");

            List<SnmpResult> result;

            try
            {
                if (_timeOut == 0)
                {
                    _timeOut = SnmpHelper.DefaultTimeOut;
                }

                if (string.IsNullOrEmpty(octetString))
                {
                    octetString = SnmpHelper.DefaultOctetString;
                }

                result = oid.HasChildOids ? Walk(version, ipAddress, octetString, oid, walkMode).ToList() : WalkSingle(version, ipAddress, octetString, oid, walkMode).ToList();

            }
            catch (Exception e)
            {
                if (e is TimeoutException)
                {
                    _log.Error("SnmpEngine.WalkOperation():Timeout Exception caught:", e);
                    throw new SnmpTimeOutException(e.Message, _timeOut);
                }
                else if (e is ArgumentOutOfRangeException)
                {
                    _log.Error("SnmpEngine.WalkOperation():Argument Out Of Range Exception caught:", e);
                    throw new SnmpEngineConvertorException((ArgumentOutOfRangeException)e);
                }
                else
                {
                    _log.Error("SnmpEngine.WalkOperation():Exception caught:", e);
                    throw new SnmpEngineException(e.Message);
                }
            }
            finally
            {
                _log.Info("SnmpEngine.WalkOperation(): Finished");
            }

            return result;
        }
Пример #40
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="version">SNMP Protocol version</param>
 /// <param name="community">SNMP community name</param>
 public AgentParameters(SnmpVersion version, OctetString community)
     : this(version)
 {
     _community.Set(community);
 }
Пример #41
0
        private IEnumerable<SnmpResult> GetNextOperation(SnmpVersion version, IPAddress ipAddress, string octetString, Oid oid)
        {
            _log.Info("SnmpEngine.GetNextOperation() : Started oid: " + oid.Value);
            List<SnmpResult> results;
            var variable = new List<Variable>
            {
                new Variable(new ObjectIdentifier(oid.Value))
            };

            try
            {
                var getNextRequest = new GetNextRequestMessage(0, _converter.ToVersionCodeConverter(version), new OctetString(octetString), variable);
                var responce = getNextRequest.GetResponse(SnmpHelper.DefaultTimeOut, new IPEndPoint(ipAddress, SnmpHelper.SnmpServerPort));

                if (responce.Pdu().ErrorStatus.ToInt32() != 0)
                {
                    throw new SnmpEngineException("SnmpEngine.GetNextOperation() error status = 0; oid = " + oid.Value);
                }

                results = responce.Pdu().Variables.Select(var => new SnmpResult(new Oid(var.Id.ToString()), var.Data, _converter.ToSnmpDataType(var.Data.TypeCode))).ToList();
            }
            catch (Exception e)
            {
                if (e is TimeoutException)
                {
                    _log.Error("SnmpEngine.GetOperation():Timeout Exception caught:", e);
                    throw new SnmpTimeOutException(e.Message, _timeOut);
                }
                else if (e is ArgumentOutOfRangeException)
                {
                    _log.Error("SnmpEngine.GetOperation():Argument Out Of Range Exception caught:", e);
                    throw new SnmpEngineConvertorException((ArgumentOutOfRangeException)e);
                }
                else
                {
                    _log.Error("SnmpEngine.GetOperation():Exception caught:", e);
                    throw new SnmpEngineException(e.Message);
                }
            }
            finally
            {
                _log.Info("SnmpEngine.GetNextOperation(): Finished");
            }

            return results;
        }
Пример #42
0
        private IEnumerable<SnmpResult> GetOperation(SnmpVersion version, IPAddress ipAddress, string octetString, Oid oid)
        {
            _log.Info("SnmpEngine.GetOperation(): Started");
            var variables = new List<Variable>
            {
                new Variable(new ObjectIdentifier(oid.Value))
            };

            try
            {
                if (_timeOut == 0)
                {
                    _timeOut = SnmpHelper.DefaultTimeOut;
                }

                if (string.IsNullOrEmpty(octetString))
                {
                    octetString = SnmpHelper.DefaultOctetString;
                }

                Messenger.Get(_converter.ToVersionCodeConverter(version), new IPEndPoint(ipAddress, SnmpHelper.SnmpServerPort), new OctetString(octetString), variables, _timeOut);
            }
            catch (Exception e)
            {
                if (e is TimeoutException)
                {
                    _log.Error("SnmpEngine.GetOperation():Timeout Exception caught:", e);
                    throw new SnmpTimeOutException(e.Message, _timeOut);
                }
                else if (e is ArgumentOutOfRangeException)
                {
                    _log.Error("SnmpEngine.GetOperation():Argument Out Of Range Exception caught:", e);
                    throw new SnmpEngineConvertorException((ArgumentOutOfRangeException)e);
                }
                else
                {
                    _log.Error("SnmpEngine.GetOperation():Exception caught:", e);
                    throw new SnmpEngineException(e.Message);
                }
            }
            finally
            {
                _log.Info("SnmpEngine.GetOperation(): Finished");
            }

            return variables.Select(var => new SnmpResult(new Oid(var.Id.ToString()), var.Data, _converter.ToSnmpDataType(var.Data.TypeCode)));
        }
Пример #43
0
        private List<SnmpResult> WalkWithAdditionalCodes(SnmpVersion version, IPAddress ipAddress, string octetString, Oid oid, WalkingMode walkMode)
        {
            _log.Info("SnmpEngine.WalkWithAdditionalCodes(): Started oid: " + oid.Value);
            var list = new List<Variable>();
            var results = new List<SnmpResult>();
            
            var codesTable = XmlLoader.InitAdditionalCodes(oid);
            var codes = (Codes)codesTable[oid.Name];

            if (codes != null)
            {


                foreach (var code in codes.Code)
                {
                    try
                    {

                        Messenger.Walk(_converter.ToVersionCodeConverter(version),
                        new IPEndPoint(ipAddress, SnmpHelper.SnmpServerPort), new OctetString(octetString),
                        new ObjectIdentifier(string.Concat(oid.Value, ".", code.Decimal)), list, _timeOut,
                        _converter.ToWalkModeConverter(walkMode));
                    }
                    catch (Exception e)
                    {
                        _log.Error("SnmpEngine.WalkWithAdditionalCodes(): Exception caught:", e);
                        _log.Error("SnmpEngine.WalkWithAdditionalCodes(): Exception oid: " + string.Concat(oid.Value, ".", code.Decimal));
                    }

                    if (list.Any())
                    {
                        _log.Info("SnmpEngine.WalkWithAdditionalCodes(): sucess oid: " + string.Concat(oid.Value, ".", code.Decimal));
                        _log.Info("SnmpEngine.WalkWithAdditionalCodes(): request result oids: " + list.Count);
                        results.AddRange(list.Select(var => new SnmpResult(new Oid(string.Concat(oid.Value, ".", code.Decimal),
                            code.Name, string.Concat(oid.FullName, ".", code.Name)),
                            var.Data, _converter.ToSnmpDataType(var.Data.TypeCode))));
                        list.Clear();
                    }
                }
            }

            codesTable.Clear();

            _log.Info("SnmpEngine.WalkWithAdditionalCodes(): Finished");
            return results;
        }
Пример #44
0
        private IEnumerable<SnmpResult> WalkSingle(SnmpVersion version, IPAddress ipAddress, string octetString, Oid oid, WalkingMode walkMode)
        {
            _log.Info("SnmpEngine.WalkSingle(): Started oid: " + oid.Value);
            var list = new List<Variable>();

            if (oid.HasAdditionalCodes)
            {
                return WalkWithAdditionalCodes(version, ipAddress, octetString, oid, walkMode);
            }

            try
            {
                Messenger.Walk(
                _converter.ToVersionCodeConverter(version),
                new IPEndPoint(ipAddress, SnmpHelper.SnmpServerPort),
                new OctetString(octetString),
                new ObjectIdentifier(oid.Value),
                list,
                _timeOut,
                _converter.ToWalkModeConverter(walkMode));
            }
            catch (Exception e)
            {
                _log.Error("SnmpEngine.WalkSingle(): Exception caught: ", e);
                _log.Error("SnmpEngine.WalkSingle(): Exception oid: " + oid.Value);
            }

            _log.Info("SnmpEngine.WalkSingle(): Finished");

            return list.Select(var => new SnmpResult(new Oid(var.Id.ToString()), var.Data, _converter.ToSnmpDataType(var.Data.TypeCode)));
        }
Пример #45
0
        private IEnumerable<SnmpResult> WalkBulk(SnmpVersion version, IPAddress ipAddress, int maxBulkRepetitions, string octetString, Oid oid, WalkingMode walkMode)
        {
            _log.Info("SnmpEngine.WalkBulk(): Started oid: " + oid.Value);
            var result = new List<SnmpResult>();

            foreach (var childOid in oid.ChildOids)
            {
                result.AddRange(!childOid.HasChildOids ? WalkBulkSingle(version, ipAddress, maxBulkRepetitions, octetString, childOid, walkMode)
                    : WalkBulk(version, ipAddress, maxBulkRepetitions, octetString, childOid, walkMode));
            }

            _log.Info("SnmpEngine.WalkBulk(): Finished");
            return result;
        }
Пример #46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SnmpHeader" /> struct.
 /// </summary>
 /// <param name="version">The Snmp version.</param>
 /// <param name="community">The Snmp Community.</param>
 public SnmpHeader(SnmpVersion version, string community)
 {
     Version = version;
     Community = community;
 }
Пример #47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SnmpDatagram"/> class.
 /// </summary>
 /// <param name="pduType">Type of the pdu.</param>
 /// <param name="snmpVersion">The SNMP version.</param>
 /// <param name="community">The community.</param>
 /// <param name="enterprise">The enterprise.</param>
 /// <param name="agentAddress">The agent address.</param>
 /// <param name="genericV1Trap">The generic v1 trap.</param>
 /// <param name="specificTrap">The specific trap.</param>
 /// <param name="timeStamp">The time stamp.</param>
 /// <param name="varBinds">The variable binds.</param>
 public SnmpDatagram(PduType pduType, SnmpVersion snmpVersion, string community, ObjectIdentifier enterprise, IPAddress agentAddress, GenericTrap genericV1Trap, int specificTrap, uint timeStamp, VarBind[] varBinds)
 {
     Header = new SnmpHeader(snmpVersion, community);
     PduV1 = new SnmpV1PDU(pduType, enterprise, agentAddress, genericV1Trap, specificTrap, timeStamp, varBinds);
     PduV2c = default(SnmpV2cPDU);
 }
Пример #48
0
 /// <summary>
 /// Constructor. Initialize SNMP version as supplied.
 /// </summary>
 /// <param name="protocolVersion">Protocol version. Acceptable values are SnmpConstants.SNMPV1, 
 /// SnmpConstants.SNMPV2 and SnmpConstants.SNMPV3</param>
 public SnmpPacket(SnmpVersion protocolVersion)
 {
     _protocolVersion = new Integer32((int)protocolVersion);
 }
Пример #49
0
        /// <summary>
        /// Reset the class. Initialize all member values to class defaults.
        /// </summary>
        public void Reset()
        {
            _address = new IpAddress(System.Net.IPAddress.Loopback);
            _port = 161;
            _version = SnmpVersion.Ver3;
            _timeout = 2000;
            _retry = 1;

            _engineId = new OctetString();
            _engineBoots = new Integer32();
            _engineTime = new Integer32();

            _engineTimeStamp = DateTime.MinValue;

            _privacyProtocol = PrivacyProtocols.None;
            _authenticationProtocol = AuthenticationDigests.None;

            _privacySecret = new MutableByte();
            _authenticationSecret = new MutableByte();

            _contextEngineId = new OctetString();
            _contextName = new OctetString();
            _securityName = new OctetString();

            // max message size is initialized to 64KB by default. It will be
            // to the smaller of the two values after discovery process
            _maxMessageSize = new Integer32(64 * 1024);

            _reportable = true;
        }
Пример #50
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="version">SNMP protocol version. Acceptable values are SnmpConstants.SNMPV1 and
 /// SnmpConstants.SNMPV2</param>
 public AgentParameters(SnmpVersion version)
     : this()
 {
     _version.Value = (int)version;
 }
Пример #51
0
 /// <summary>
 /// SNMP SET request
 /// </summary>
 /// <example>Set operation in SNMP version 1:
 /// <code>
 /// String snmpAgent = "10.10.10.1";
 /// String snmpCommunity = "private";
 /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
 /// // Create a request Pdu
 /// List&lt;Vb&gt; vbList = new List&lt;Vb&gt;();
 /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0
 /// OctetString setValue = new OctetString("My personal toy");
 /// vbList.Add(new Vb(setOid, setValue));
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Set(SnmpVersion.Ver1, list.ToArray());
 /// if( result == null ) {
 ///   Console.WriteLine("Request failed.");
 /// } else {
 ///   Console.WriteLine("Success!");
 /// }
 /// </code>
 /// 
 /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
 /// </example>
 /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
 /// <param name="vbs">Vb array containing Oid/AsnValue pairs for the SET operation</param>
 /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
 public Dictionary<Oid, AsnType> Set(SnmpVersion version, Vb[] vbs)
 {
     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;
     }
     Pdu pdu = new Pdu(PduType.Set);
     foreach (Vb vb in vbs)
     {
         pdu.VbList.Add(vb);
     }
     return Set(version, pdu);
 }
Пример #52
0
        /// <summary>
        /// Tries to obtain the oid lookup table given lookup ID.
        /// </summary>
        /// <param name="context">The device database context to extend.</param>
        /// <param name="oidLookupId">The OID mapping lookup ID to get.</param>
        /// <param name="maximumSupportedSnmpVersion">The maximum supported SNMP version (to put into returned lookup)</param>
        /// <param name="oidLookup">Returns the OID lookup, if found.</param>
        /// <returns><c>true</c> if a lookup of the given lookup ID has been found and the ID returned. Otherwise <c>false</c>.</returns>
        public static bool TryFindDeviceSpecificOidLookup(this DeviceDatabaseContext context, int oidLookupId, SnmpVersion maximumSupportedSnmpVersion, out IDeviceSpecificOidLookup oidLookup)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context), "The context to search OID lookup is null");
            }

            oidLookup = null;

            var result = context.DeviceSpecificOids.Where(d => d.OidMappingId == oidLookupId);

            if (!result.Any())
            {
                return(false);
            }

            oidLookup = new DeviceSpecificOidLookup(result, maximumSupportedSnmpVersion);

            return(true);
        }
Пример #53
0
 /// <summary>
 /// SNMP SET request
 /// </summary>
 /// <example>Set operation in SNMP version 1:
 /// <code>
 /// String snmpAgent = "10.10.10.1";
 /// String snmpCommunity = "private";
 /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
 /// // Create a request Pdu
 /// Pdu pdu = new Pdu();
 /// pdu.Type = SnmpConstants.SET; // type SET
 /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0
 /// OctetString setValue = new OctetString("My personal toy");
 /// pdu.VbList.Add(setOid, setValue);
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Set(SnmpVersion.Ver1, pdu);
 /// if( result == null ) {
 ///   Console.WriteLine("Request failed.");
 /// } else {
 ///   Console.WriteLine("Success!");
 /// }
 /// </code>
 /// 
 /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
 /// </example>
 /// <param name="version">SNMP protocol version number. 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> Set(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 (res.ContainsKey(v.Oid))
                     {
                         if (res[v.Oid].Type != v.Value.Type)
                         {
                             throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString());
                         }
                         else
                         {
                             res[v.Oid] = v.Value;
                         }
                     }
                     else
                     {
                         res.Add(v.Oid, v.Value);
                     }
                 }
                 _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;
 }
Пример #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SnmpDatagram"/> class.
 /// </summary>
 /// <param name="pduType">Type of the pdu.</param>
 /// <param name="snmpVersion">The SNMP version.</param>
 /// <param name="community">The community.</param>
 /// <param name="requestId">The request identifier.</param>
 /// <param name="errorStatus">The error status.</param>
 /// <param name="errorIndex">Index of the error.</param>
 /// <param name="varBinds">The variable binds.</param>
 public SnmpDatagram(PduType pduType, SnmpVersion snmpVersion, string community, int requestId, SnmpErrorStatus errorStatus, int errorIndex, VarBind[] varBinds)
 {
     Header = new SnmpHeader(snmpVersion, community);
     PduV2c = new SnmpV2cPDU(pduType, requestId, errorStatus, errorIndex, varBinds);
     PduV1 = default(SnmpV1PDU);
 }
Пример #55
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="version">SNMP protocol version. Acceptable values are SnmpConstants.SNMPV1 and
 /// SnmpConstants.SNMPV2</param>
 public AgentParameters(SnmpVersion version)
     : this()
 {
     _version.Value = (int)version;
 }