Transport class for IPv4 using UDP
InternetProtocol version 4 User Datagram Protocol (IP/UDP) transport protocol implementation for use with SNMP versions 1, 2 and 3.
Inheritance: UdpTransport, IDisposable
Beispiel #1
1
        public bool sprawdzPolaczenie(string host1, string commun)
        {
            /*! 
	    	 *Sprawdza, czy pod wpisanymi danymi istnieje jakiś serwer do obsługi.
             */
            string OID = "1.3.6.1.2.1.6.11.0";
            OctetString communityOS = new OctetString(commun);
            AgentParameters param = new AgentParameters(communityOS);
            param.Version = SnmpVersion.Ver1;
            IpAddress agent = new IpAddress(host1);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);
            pdu.VbList.Add(OID);
            try
            {
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
            }
            catch
            {
                return false;
            }
            host = host1;
            community = commun;
            return true;
        }
Beispiel #2
1
 public string SNMP_SET(string adres, string value)
 {
     // Prepare target
     UdpTarget target = new UdpTarget((IPAddress)new IpAddress("127.0.0.1"));
     // Create a SET PDU
     Pdu pdu = new Pdu(PduType.Set);
     // Set a value to integer
     pdu.VbList.Add(new Oid(adres), new SnmpSharpNet.Integer32(int.Parse(value)));
     
     // Set Agent security parameters
     AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new SnmpSharpNet.OctetString("public"));
     // Response packet
     SnmpV2Packet response;
     try
     {
         // Send request and wait for response
         response = target.Request(pdu, aparam) as SnmpV2Packet;
     }
     catch (Exception ex)
     {
         // If exception happens, it will be returned here
         target.Close();
         return String.Format("Request failed with exception: {0}", ex.Message);
         
         
     }
     // Make sure we received a response
     if (response == null)
     {
         return ("Error in sending SNMP request.");
     }
     else
     {
         // Check if we received an SNMP error from the agent
         if (response.Pdu.ErrorStatus != 0)
         {
             return (String.Format("SNMP agent returned ErrorStatus {0} on index {1}",
                 response.Pdu.ErrorStatus, response.Pdu.ErrorIndex));
         }
         else
         {
             // Everything is ok. Agent will return the new value for the OID we changed
             return (String.Format("Agent response {0}: {1}",
                 response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString()));
         }
     }
 }
Beispiel #3
0
        public string get(string ip, string oid)
        {
            Pdu pdu = new Pdu(PduType.Get);
            pdu.VbList.Add(oid);
            OctetString community = new OctetString("public");
            AgentParameters param = new AgentParameters(community);
            param.Version = SnmpVersion.Ver1;
            {
                IpAddress agent = new IpAddress(ip);
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {

                        return string.Format("Error in SNMP reply. Error {0} index {1} \r\n",
                            result.Pdu.ErrorStatus,
                            result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        return result.Pdu.VbList[0].Value.ToString();
                    }
                }

                else
                {
                    return string.Format("No response received from SNMP agent. \r\n");
                }
                target.Dispose();
            }
        }
Beispiel #4
0
 public Dictionary<String, String> getCache(UdpTarget target, string oid)
 {
     RemoteQueryCache rqc = new RemoteQueryCache();
     Console.WriteLine("trying from cache");
     Dictionary<string,string> data = rqc.getCache(target.Address.ToString(), oid);
     Console.WriteLine("reading from cache " + data.Count );
     return data;
 }
Beispiel #5
0
        /// <summary>
        /// Performs an SNMP get request
        /// </summary>
        /// <param name="log_options">Log options</param>
        /// <param name="ip">IP of target device</param>
        /// <param name="in_community">Community name</param>
        /// <param name="oid">OID</param>
        /// <returns></returns>
        public static SnmpV1Packet Get(LOG_OPTIONS log_options, IPAddress ip, string in_community, string oid, bool get_next)
        {
            // SNMP community name
            OctetString community = new OctetString(in_community);

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);
            // Set SNMP version to 1 (or 2)
            param.Version = SnmpVersion.Ver1;

            // Construct target
            UdpTarget target = new UdpTarget(ip, 161, 2000, 1);

            // Pdu class used for all requests
            Pdu pdu;
            if (get_next)
            {
                pdu = new Pdu(PduType.GetNext);
            }
            else
            {
                pdu = new Pdu(PduType.Get);
            }
            pdu.VbList.Add(oid); //sysDescr

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

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Logger.Write(log_options, module, "Error in SNMP reply. Error " + result.Pdu.ErrorStatus.ToString() + " index " + result.Pdu.ErrorIndex.ToString());
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    Logger.Write(log_options, module, "OID: " + result.Pdu.VbList[0].Oid.ToString() + " Value: " + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + " : " + result.Pdu.VbList[0].Value.ToString());
                }
            }
            else
            {
                Logger.Write(log_options, module, "No response received from SNMP agent.");
            }
            target.Close();

            return result;
        }
Beispiel #6
0
        public string getHostname(string ip)
        {
            string hostname = null;
            try
            {
                OctetString comm = new OctetString(_community);
                AgentParameters param = new AgentParameters(comm);
                param.Version = SnmpVersion.Ver1;
                IpAddress agent = new IpAddress(ip);
                UdpTarget target = new UdpTarget((IPAddress)agent,161,2000,1);
                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add("1.3.6.1.2.1.1.5.0");
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                if (result!=null)
                {
                    if (result.Pdu.ErrorStatus!= 0)
                    {
                        hostname = null;
                    }
                    else
                    {
                        string[] cutPdu = Regex.Split(result.Pdu.VbList[0].Value.ToString(),@"\.");
                        hostname = cutPdu[0];
                    }
                }
                else
                {
                    hostname = null;
                }
            }
            catch (Exception)
            {
                hostname = null;
            }

            return hostname;
        }
Beispiel #7
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(ESnmpVersion 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 != ESnmpVersion.Ver1 && version != ESnmpVersion.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 (System.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 == ESnmpVersion.Ver2 && (v.Value.Type == SnmpConstants.SmiNoSuchInstance ||
                                                                 v.Value.Type == SnmpConstants.SmiNoSuchObject))
                            {
                                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.EErrorCode.OidValueTypeChanged, string.Format("Value type changed from {0} to {1}", res[v.Oid].Type, v.Value.Type));
                                    }
                                }
                            }
                        }

                        target.Close();
                        target = null;

                        return(res);
                    }

                    if (!suppressExceptions)
                    {
                        throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (!suppressExceptions)
                {
                    target.Close();
                    target = null;
                    throw ex;
                }
            }

            target.Close();
            target = null;

            return(null);
        }
Beispiel #8
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
     {
         var param  = new AgentParameters(version, new OctetString(_community));
         var result = _target.Request(pdu, param);
         if (result != null)
         {
             if (result.Pdu.ErrorStatus == 0)
             {
                 var res = new Dictionary <Oid, AsnType>();
                 foreach (var 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);
 }
Beispiel #9
0
        public Obiekt zwrocWartosciOID(string OID, string male_oid)
        {
            //Dictionary<string, string> struktura_obiektu = new Dictionary<string, string>();
            Obiekt obiekt1 = new Obiekt();
            OctetString communityOS = new OctetString(community);
            AgentParameters param = new AgentParameters(communityOS);
            param.Version = SnmpVersion.Ver1;
            IpAddress agent = new IpAddress(host);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);
            pdu.VbList.Add(OID);
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
            //wyłączony fragment kodu OID :: typ zmiennej: result.Pdu.VbList[0].Oid.ToString() + " :: " + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + " :: " + 
            obiekt1.nazwa = polaTCPslownik.FirstOrDefault(x => x.Value.Contains(OID)).Key;
            obiekt1.OID = result.Pdu.VbList[0].Oid.ToString();
            obiekt1.typ = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);
            obiekt1.wartosc = result.Pdu.VbList[0].Value.ToString();
            obiekt1.localOID = male_oid;
            /*struktura_obiektu.Add("Nazwa",polaTCPslownik.FirstOrDefault(x => x.Value.Contains(OID)).Key);
            string temp = result.Pdu.VbList[0].Oid.ToString();
            struktura_obiektu.Add("OID", temp);
            temp = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);
            struktura_obiektu.Add("Typ", temp);
            temp = result.Pdu.VbList[0].Value.ToString();
            struktura_obiektu.Add("Wartość", temp);
            string zwrot = result.Pdu.VbList[0].Value.ToString();
            

            return struktura_obiektu;*/
            return obiekt1;
        }
Beispiel #10
0
 /// <summary>
 /// Performs an SNMP set request on the target device
 /// </summary>
 /// <param name="log_options">Options on how to display the output</param>
 /// <param name="ip">IP address of target</param>
 /// <param name="in_community">Write-community name</param>
 /// <param name="oid">OID to set</param>
 /// <param name="new_value">Value (int or string)</param>
 /// <returns></returns>
 public static SnmpV2Packet Set(LOG_OPTIONS log_options, IPAddress ip, string in_community, string oid, object new_value)
 {
     // Prepare target
     UdpTarget target = new UdpTarget(ip);
     // Create a SET PDU
     Pdu pdu = new Pdu(PduType.Set);
     // Set sysLocation.0 to a new string
     if (new_value.GetType() == typeof(string))
     {
         pdu.VbList.Add(new Oid(oid), new OctetString(new_value.ToString()));
     }
     else if (new_value.GetType() == typeof(int))
     {
         // Set a value to integer
         pdu.VbList.Add(new Oid(oid), new Integer32(new_value.ToString()));
     }
     else
     {
         Logger.Write(log_options, module, "Invalid data type: " + new_value.GetType());
         return null; //Invalid type
     }
     // Set Agent security parameters
     AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString(in_community));
     // Response packet
     SnmpV2Packet response;
     try
     {
         // Send request and wait for response
         response = target.Request(pdu, aparam) as SnmpV2Packet;
     }
     catch (Exception ex)
     {
         // If exception happens, it will be returned here
         Logger.Write(log_options, module, "Request failed with exception: " + ex.Message);
         target.Close();
         return null;
     }
     // Make sure we received a response
     if (response == null)
     {
         Logger.Write(log_options, module, "Error in sending SNMP request.");
     }
     else
     {
         // Check if we received an SNMP error from the agent
         if (response.Pdu.ErrorStatus != 0)
         {
             string message = String.Format("SNMP agent returned ErrorStatus {0} on index {1}",
                 response.Pdu.ErrorStatus, response.Pdu.ErrorIndex);
             Logger.Write(log_options, module, message);
         }
         else
         {
             // Everything is ok. Agent will return the new value for the OID we changed
             string message = String.Format("Agent response {0}: {1}",
                 response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString());
             Logger.Write(log_options, module, message);
         }
     }
     return response;
 }
Beispiel #11
0
        /// <summary>SNMP GET-BULK request</summary>
        /// <remarks>
        /// GetBulk request type is only available with SNMP v2c agents. SNMP v3 also supports the request itself
        /// but that version of the protocol is not supported by SimpleSnmp.
        ///
        /// GetBulk method will return a dictionary of Oid to value mapped values as returned form a
        /// single GetBulk request to the agent. You can change how the request itself is made by changing the
        /// SimpleSnmp.NonRepeaters and SimpleSnmp.MaxRepetitions values. SimpleSnmp properties are only used
        /// when values in the parameter Pdu are set to 0.
        /// </remarks>
        /// <example>SNMP GET-BULK 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.GETBULK; // type GETBULK
        /// pdu.VbList.Add("1.3.6.1.2.1.1");
        /// pdu.NonRepeaters = 0;
        /// pdu.MaxRepetitions = 10;
        /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetBulk(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"
        /// 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>
        /// </example>
        /// <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> GetBulk(Pdu pdu)
        {
            if (!Valid)
            {
                if (!suppressExceptions)
                {
                    throw new SnmpException("SimpleSnmp class is not valid.");
                }

                return(null); // class is not fully initialized.
            }

            try
            {
                pdu.NonRepeaters   = nonRepeaters;
                pdu.MaxRepetitions = maxRepetitions;

                target = new UdpTarget(peerIP, peerPort, timeout, retry);
            }
            catch (System.Exception ex)
            {
                target = null;
                if (!suppressExceptions)
                {
                    throw ex;
                }
            }

            if (target == null)
            {
                return(null);
            }

            try
            {
                AgentParameters param  = new AgentParameters(ESnmpVersion.Ver2, 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 (
                                (v.Value.Type == SnmpConstants.SmiEndOfMIBView) ||
                                (v.Value.Type == SnmpConstants.SmiNoSuchInstance) ||
                                (v.Value.Type == SnmpConstants.SmiNoSuchObject))
                            {
                                break;
                            }

                            if (res.ContainsKey(v.Oid))
                            {
                                if (res[v.Oid].Type != v.Value.Type)
                                {
                                    throw new SnmpException(SnmpException.EErrorCode.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);
                    }

                    if (!suppressExceptions)
                    {
                        throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (!suppressExceptions)
                {
                    target.Close();
                    target = null;

                    throw ex;
                }
            }

            target.Close();
            target = null;

            return(null);
        }
Beispiel #12
0
        protected void btnReset_Click(object sender, EventArgs e)
        {
            string IP = _Ip;
            try
            {
                    if (IP.Trim() != "")
                    {
                        if (IP.Trim() != "0.0.0.0")
                        {
                            UdpTarget target = new UdpTarget((IPAddress)new IpAddress(IP));
                            // Create a SET PDU
                            Pdu pdu = new Pdu(PduType.Set);
                            // Set sysLocation.0 to a new string
                            // pdu.VbList.Add(new Oid("1.3.6.1.2.1.1.6.0"), new OctetString("Some other value"));
                            // Set a value to integer
                            pdu.VbList.Add(new Oid(".1.3.6.1.2.1.69.1.1.3.0"), new Integer32(1));
                            // Set a value to unsigned integer
                            //   pdu.VbList.Add(new Oid("1.3.6.1.2.1.67.1.1.1.1.6.0"), new UInteger32(101));
                            // Set Agent security parameters
                            AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString("LBC"));
                            // Response packet
                            SnmpV2Packet response;
                            try
                            {
                                // Send request and wait for response
                                response = target.Request(pdu, aparam) as SnmpV2Packet;
                            }
                            catch (Exception ex)
                            {
                                // If exception happens, it will be returned here
                                Console.WriteLine(String.Format("Request failed with exception: {0}", ex.Message));
                                target.Close();
                                return;
                            }
                            // Make sure we received a response
                            if (response == null)
                            {
                                Console.WriteLine("Error in sending SNMP request.");
                            }
                            else
                            {
                                // Check if we received an SNMP error from the agent
                                if (response.Pdu.ErrorStatus != 0)
                                {
                                    Console.WriteLine(String.Format("SNMP agent returned ErrorStatus {0} on index {1}",
                                      response.Pdu.ErrorStatus, response.Pdu.ErrorIndex));
                                }
                                else
                                {
                                    // Everything is ok. Agent will return the new value for the OID we changed
                                    Console.WriteLine(String.Format("Agent response {0}: {1}",
                                      response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString()));
                                }
                            }

                        }
                    }

                    Response.Write("<script>alert('Reset Modem OK !')</script>");

            }
            catch { Response.Write("<script>alert('Chưa reset được Modem. Có thể modem đang offline !')</script>"); }
        }
Beispiel #13
0
        private static async Task <bool> WalkGetBulkAsync(IPAddress agent, string community, string oid, Func <Vb, bool> handleValue)
        {
            OctetString communityString = new OctetString(community);

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

            // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
            param.Version = SnmpVersion.Ver2;

            // Construct target
            UdpTarget target = new UdpTarget(agent, 161, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(oid); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetBulk)
            {
                // In this example, set NonRepeaters value to 0
                NonRepeaters = 0,
                // MaxRepetitions tells the agent how many Oid/Value pairs to return
                // in the response.
                MaxRepetitions = 5
            };

            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to 0
                // and during encoding id will be set to the random value
                // for subsequent requests, id will be set to a value that
                // needs to be incremented to have unique request ids for each
                // packet
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                //var result = (SnmpV1Packet)target.Request(pdu, param);
                SnmpV2Packet result = (SnmpV2Packet)(await target.RequestAsync(pdu, param));

                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        //System.Diagnostics.Debug.WriteLine("Error in SNMP reply. Error {0} index {1}",
                        //    result.Pdu.ErrorStatus,
                        //    result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                //System.Diagnostics.Debug.WriteLine("{0} ({1}): {2}",
                                //    v.Oid.ToString(),
                                //    SnmpConstants.GetTypeName(v.Value.Type),
                                //    v.Value.ToString());

                                handleValue(v);

                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid = null;
                                }
                                else
                                {
                                    lastOid = v.Oid;
                                }
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    //System.Diagnostics.Debug.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();
            return(true);
        }
Beispiel #14
0
    /// <summary>
    /// Gets the model of the printer requested
    /// </summary>
    private void getModel()
    {
        // SNMP community name
        OctetString community = new OctetString( "public" );

        // Define agent parameters class
        AgentParameters param = new AgentParameters( community );
        // Set SNMP version to 1 (or 2)
        param.Version = SnmpVersion.Ver1;
        // Construct the agent address object
        // IpAddress class is easy to use here because
        //  it will try to resolve constructor parameter if it doesn't
        //  parse to an IP address
        IpAddress agent = new IpAddress( printerName );

        // Construct target
        UdpTarget target = new UdpTarget( (System.Net.IPAddress)agent, 161, 2000, 3 );

        // Pdu class used for all requests
        Pdu pdu = new Pdu( PduType.Get );
        pdu.VbList.Add( "1.3.6.1.2.1.1.1.0" ); //sysDescr

        // Make SNMP request
        SnmpV1Packet result = null;
        try
        {
            result = (SnmpV1Packet)target.Request( pdu, param );
        }
        catch
        {
        }
        // If result is null then agent didn't reply or we couldn't parse the reply.
        if ( result != null )
        {
            // ErrorStatus other then 0 is an error returned by
            // the Agent - see SnmpConstants for error definitions
            if ( result.Pdu.ErrorStatus != 0 )
            {
                // agent reported an error with the request
                Console.WriteLine( "Error in SNMP reply. Error {0} index {1}",
                    result.Pdu.ErrorStatus,
                    result.Pdu.ErrorIndex );
            }
            else
            {
                // Reply variables are returned in the same order as they were added
                //  to the VbList
                printerModel = result.Pdu.VbList[0].Value.ToString();
            }
        }
        else
        {
            Console.WriteLine( "No response received from SNMP agent." );
        }
        target.Close();
    }
Beispiel #15
0
    /// <summary>
    /// Will get the rest of the variables, parts and percentages
    /// </summary>
    private Dictionary<String, String> getData()
    {
        Dictionary<String, String> dictionary = new Dictionary<String, String>();
        OctetString community = new OctetString( "public" );
        AgentParameters param = new AgentParameters( community );
        param.Version = SnmpVersion.Ver1;
        IpAddress agent = new IpAddress( printerName );

        UdpTarget target = new UdpTarget( (System.Net.IPAddress)agent, 161, 2000, 1 );
        Oid rootOid = new Oid( printerOID ); // ifDescr
        Oid lastOid = (Oid)rootOid.Clone();
        Pdu pdu = new Pdu( PduType.GetNext );

        while ( lastOid != null )
        {
            // When Pdu class is first constructed, RequestId is set to a random value
            // that needs to be incremented on subsequent requests made using the
            // same instance of the Pdu class.
            if ( pdu.RequestId != 0 )
            {
                pdu.RequestId += 1;
            }
            // Clear Oids from the Pdu class.
            pdu.VbList.Clear();
            // Initialize request PDU with the last retrieved Oid
            pdu.VbList.Add( lastOid );
            // Make SNMP request
            SnmpV1Packet result = null;
            try
            {
                result = (SnmpV1Packet)target.Request( pdu, param );
            }
            catch
            {
                return null;
            }

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if ( result != null )
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if ( result.Pdu.ErrorStatus != 0 )
                {
                    // agent reported an error with the request
                    Console.WriteLine( "Error in SNMP reply. Error {0} index {1}",
                        result.Pdu.ErrorStatus,
                        result.Pdu.ErrorIndex );
                    lastOid = null;
                    break;
                }
                else
                {
                    // Walk through returned variable bindings
                    foreach ( Vb v in result.Pdu.VbList )
                    {
                        // Check that retrieved Oid is "child" of the root OID
                        if ( rootOid.IsRootOf( v.Oid ) )
                        {
                            dictionary.Add( v.Oid.ToString(), v.Value.ToString() );
                            lastOid = v.Oid;
                        }
                        else
                        {
                            lastOid = null;
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine( "No response received from SNMP agent." );
            }
        }
        target.Close();

        return dictionary;
    }
Beispiel #16
0
        public bool sprawdzCzyPoleIstnieje(string OID)
        {
            /*! 
		     *Metoda publiczna do sprawdzenia, czy dane OID jest dostępne na danej maszynie
             */
            bool czyIstnieje = false;

            OctetString communityOS = new OctetString(community);
            AgentParameters param = new AgentParameters(communityOS);
            param.Version = SnmpVersion.Ver1;
            IpAddress agent = new IpAddress(host);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);
            pdu.VbList.Add(OID);
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
            if (result.Pdu.ErrorIndex == 0)
            {
                czyIstnieje = true;
            }
            if (OID == "1.3.6.1.2.1.6.13.0")
                czyIstnieje = true;
            return czyIstnieje;
        }
Beispiel #17
0
        public Tabela pobierzTabele()
        {
            /*! 
		     *Pobiera tabele SNMP.
             */
            Tabela tabela1 = new Tabela();
            AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(community));
            IpAddress peer = new IpAddress(host);
            if (!peer.Valid)
            {
                Console.WriteLine("Zły adres.");
                //return false;
            }
            UdpTarget target = new UdpTarget((IPAddress)peer);
            Oid startOid = new Oid("1.3.6.1.2.1.6.13");
            startOid.Add(1);
            Pdu bulkPdu = Pdu.GetBulkPdu();
            bulkPdu.VbList.Add(startOid);
            bulkPdu.NonRepeaters = 0;
            bulkPdu.MaxRepetitions = 100;
            Oid curOid = (Oid)startOid.Clone();
            while (startOid.IsRootOf(curOid))
            {
                SnmpPacket res = null;
                try
                {
                    res = target.Request(bulkPdu, param);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Zapytanie nieudane {0}", ex.Message);
                    target.Close();
                    //return false;
                }
                if (res.Version != SnmpVersion.Ver2)
                {
                    Console.WriteLine("Otrzymano inną wersję SNMP w odpowiedzi.");
                    target.Close();
                    //return false;
                }
                if (res.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine("SNMP agent zwrócił błąd {0} dla zapytania {1}", res.Pdu.ErrorStatus, res.Pdu.ErrorIndex);
                    target.Close();
                    //return false;
                }
                foreach (Vb v in res.Pdu.VbList)
                {
                    curOid = (Oid)v.Oid.Clone();
                    if (startOid.IsRootOf(v.Oid))
                    {
                        uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid);
                        uint[] instance = new uint[childOids.Length - 1];
                        Array.Copy(childOids, 1, instance, 0, childOids.Length - 1);
                        String strInst = InstanceToString(instance);
                        uint column = childOids[0];
                        if (!tabelaKolumn.Contains(column))
                            tabelaKolumn.Add(column);
                        if (slownikRezultatu.ContainsKey(strInst))
                        {
                            slownikRezultatu[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else {
                            slownikRezultatu[strInst] = new Dictionary<uint, AsnType>();
                            slownikRezultatu[strInst][column] = (AsnType)v.Value.Clone();
                        }
                    }
                    else {
                        break;
                    }
                }
                if (startOid.IsRootOf(curOid))
                {
                    bulkPdu.VbList.Clear();
                    bulkPdu.VbList.Add(curOid);
                    bulkPdu.NonRepeaters = 0;
                    bulkPdu.MaxRepetitions = 100;
                }
            }
            target.Close();

            if (slownikRezultatu.Count <= 0)
            {
                //Console.WriteLine("Żadnych rezlutatów nie zwrócono");
                //return false;
            }
            else {
                //return true;
            }

            /*UFAM W TABELE, ŻE SŁOWNIK NIE ODWRÓCI KOLEJNOŚCI I WALĘ NA OŚLEP KOLEJNE WARTOŚCI*/
            foreach (KeyValuePair<string, Dictionary<uint, AsnType>> kvp in slownikRezultatu)
            {
                int i = 0;
                tabela1.tcpAddress.Add(kvp.Key);
                foreach (uint kolumna in tabelaKolumn)
                {
                    if (kvp.Value.ContainsKey(kolumna))
                    {
                        if (i == 0)
                            tabela1.tcpConnLocalAddress.Add(kvp.Value[kolumna].ToString());
                        else if (i == 1)
                            tabela1.tcpConnLocalPort.Add(kvp.Value[kolumna].ToString());
                        else if (i == 2)
                            tabela1.tcpConnRemAddress.Add(kvp.Value[kolumna].ToString());
                        else if (i == 3)
                            tabela1.tcpConnRemPort.Add(kvp.Value[kolumna].ToString());
                        else if (i == 4)
                            tabela1.tcpConnState.Add(kvp.Value[kolumna].ToString());

                        i++;
                    }
                }
            }

            /*/BUDOWA DRZEWA
            foreach (KeyValuePair<string,Dictionary<uint,AsnType>> kvp in slownikRezultatu)
            {
                tabela1.tcpAddress.Add(kvp.Key);
                tabela1.tcpConnLocalAddress.Add(kvp.Value[0].ToString());
                tabela1.tcpConnLocalPort.Add(kvp.Value[1].ToString());
                tabela1.tcpConnRemAddress.Add(kvp.Value[2].ToString());
                tabela1.tcpConnRemPort.Add(kvp.Value[3].ToString());
                tabela1.tcpConnState.Add(kvp.Value[4].ToString());
            }*/
            return tabela1;
        }
Beispiel #18
0
        public void pobierzTabeleDoUsuniecia()
        {
            /*! 
		     *Pobiera tabele SNMP.
             */
            Dictionary<String, Dictionary<uint, AsnType>> tabela_rezultat = new Dictionary<string, Dictionary<uint, AsnType>>();
            List<uint> tabeleKolumy = new List<uint>();
            AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(community));
            IpAddress peer = new IpAddress(host);
            if (!peer.Valid)
            {
                Console.WriteLine("Zły adres.");
                return;
            }

            UdpTarget target = new UdpTarget((IPAddress)peer);
            Oid startOid = new Oid("1.3.6.1.2.1.6.13");
            startOid.Add(1);

            //przygotowanie zapytania
            Pdu bulkPdu = Pdu.GetBulkPdu();
            bulkPdu.VbList.Add(startOid);
            bulkPdu.NonRepeaters = 0;
            bulkPdu.MaxRepetitions = 100;
            Oid curOid = (Oid)startOid.Clone();
            while (startOid.IsRootOf(curOid))
            {
                SnmpPacket res = null;
                try
                {
                    res = target.Request(bulkPdu, param);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Zapytanie nieudane {0}", ex.Message);
                    target.Close();
                    return;
                }
                if (res.Version != SnmpVersion.Ver2)
                {
                    Console.WriteLine("Received wrong SNMP version response packet.");
                    target.Close();
                    return;
                }
                if (res.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine("SNMP agent zwrócił błąd {0} dla zapytania {1}", res.Pdu.ErrorStatus, res.Pdu.ErrorIndex);
                    target.Close();
                    return;
                }
                foreach (Vb v in res.Pdu.VbList)
                {
                    curOid = (Oid)v.Oid.Clone();
                    if (startOid.IsRootOf(v.Oid))
                    {
                        uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid);
                        uint[] instance = new uint[childOids.Length - 1];
                        Array.Copy(childOids, 1, instance, 0, childOids.Length - 1);
                        String strInst = InstanceToString(instance);
                        uint column = childOids[0];
                        if (!tabeleKolumy.Contains(column))
                            tabeleKolumy.Add(column);
                        if (tabela_rezultat.ContainsKey(strInst))
                        {
                            tabela_rezultat[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else
                        {
                            tabela_rezultat[strInst] = new Dictionary<uint, AsnType>();
                            tabela_rezultat[strInst][column] = (AsnType)v.Value.Clone();
                        }
                    }
                    else
                    {
                        break; //bo koniec tabeli ;)
                    }
                }
                if (startOid.IsRootOf(curOid))
                {
                    bulkPdu.VbList.Clear();
                    bulkPdu.VbList.Add(curOid);
                    bulkPdu.NonRepeaters = 0;
                    bulkPdu.MaxRepetitions = 100;
                }
                target.Close();
                if (tabela_rezultat.Count <= 0)
                {
                    Console.WriteLine("Żadnych rezlutatów nie zwrócono");
                }
                else
                {
                    Console.WriteLine("Instance");
                    foreach (uint column in tabeleKolumy)
                    {
                        Console.Write("\tColumn id {0}", column);
                    }
                    Console.WriteLine("");
                    foreach (KeyValuePair<string, Dictionary<uint, AsnType>> kvp in tabela_rezultat)
                    {
                        Console.Write("{0}", kvp.Key);
                        foreach (uint column in tabeleKolumy)
                        {
                            if (kvp.Value.ContainsKey(column))
                            {
                                Console.Write("\t{0} ({1})", kvp.Value[column].ToString(), SnmpConstants.GetTypeName(kvp.Value[column].Type));
                            }
                            else
                            {
                                Console.Write("\t-");
                            }
                        }
                        Console.WriteLine("");
                    }
                }
            }
        }
Beispiel #19
0
        public bool zmienWartoscOID(string OID, string wartosc)
        {
            /*! 
		     *Zmienia wartość zadanego OID na żądaną wartość
             */
            UdpTarget target = new UdpTarget((IPAddress)new IpAddress(host));
            Pdu pdu = new Pdu(PduType.Set);
            pdu.VbList.Add(new Oid(OID), new Integer32(wartosc));
            AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString("private"));
            SnmpV2Packet response;
            try
            {
                response = target.Request(pdu, aparam) as SnmpV2Packet;
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Request failed with exception: {0}", ex.Message));
                target.Close();
                return false;
            }
            if (response == null)
            {
                Console.WriteLine("Błąd w wysyłaniu pakietu");
            }
            else
            {
                if (response.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine(String.Format("SNMP agent returned ErrorStatus {0} on index {1}", response.Pdu.ErrorStatus, response.Pdu.ErrorIndex));
                }
                else
                {
                    Console.WriteLine(String.Format("Agent response {0}: {1}", response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString()));
                    return true;
                }
            }
            return false;
        }
Beispiel #20
0
        private void button11_Click(object sender, EventArgs e)
        {
            //SnmpTest snt = new SnmpTest(tbAddress.Text, "public", ".1.3.6.1.4.1.38446");
            //string[] t=  {".1.3.6.1.4.1.38446"};
            //snt.Test();

            


            OctetString community = new OctetString("public");
            AgentParameters param = new AgentParameters(community);
            param.Version = SnmpVersion.Ver2;
            IpAddress agent = new IpAddress("192.168.1.120");
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            Pdu pdu2 = new Pdu(PduType.GetBulk);
            pdu2.VbList.Add(".1.3.6.1.4.1.38446.1.1.2.1.13");

            SnmpV2Packet result2 = (SnmpV2Packet)target.Request(pdu2, param);

            int i=result2.Pdu.VbCount;
            
            string str= SnmpConstants.GetTypeName(result2.Pdu.VbList[0].Value.Type);
            string str2 = result2.Pdu.VbList[0].Value.ToString();
            return;











            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(".1.3.6.1.4.1.38446.1.5.9.1.9"); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetBulk);

            // In this example, set NonRepeaters value to 0
            pdu.NonRepeaters = 0;
            // MaxRepetitions tells the agent how many Oid/Value pairs to return
            // in the response.
            pdu.MaxRepetitions = 5;

            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to 0
                // and during encoding id will be set to the random value
                // for subsequent requests, id will be set to a value that
                // needs to be incremented to have unique request ids for each
                // packet
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by 
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                            result.Pdu.ErrorStatus,
                            result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                Console.WriteLine("{0} ({1}): {2}",
                                    v.Oid.ToString(),
                                    SnmpConstants.GetTypeName(v.Value.Type),
                                    v.Value.ToString());
                                lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Dispose();
        }
Beispiel #21
0
        private static bool WalkGetNext(IPAddress agent, string community, string oid, Func <Vb, bool> handleValue)
        {
            // SNMP community name
            OctetString communityString = new OctetString(community);

            // Define agent parameters class
            AgentParameters param = new AgentParameters(communityString)
            {
                // Set SNMP version to 1
                Version = SnmpVersion.Ver1
            };

            // Construct target
            UdpTarget target = new UdpTarget(agent, 161, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(oid); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetNext);

            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to a random value
                // that needs to be incremented on subsequent requests made using the
                // same instance of the Pdu class.
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        //System.Diagnostics.Debug.WriteLine("Error in SNMP reply. Error {0} index {1}",
                        //    result.Pdu.ErrorStatus,
                        //    result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                //System.Diagnostics.Debug.WriteLine("{0} ({1}): {2}",
                                //    v.Oid.ToString(),
                                //    SnmpConstants.GetTypeName(v.Value.Type),
                                //    v.Value.ToString());

                                handleValue(v);

                                lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    //System.Diagnostics.Debug.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();
            return(true);
        }
Beispiel #22
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(ESnmpVersion 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 != ESnmpVersion.Ver1 && version != ESnmpVersion.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 (System.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.EErrorCode.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);
                    }

                    if (!suppressExceptions)
                    {
                        throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (!suppressExceptions)
                {
                    target.Close();
                    target = null;

                    throw ex;
                }
            }

            target.Close();
            target = null;

            return(null);
        }
Beispiel #23
0
 private SnmpV2Packet GetSNMP()
 {
     IpAddress agent = new IpAddress(textBox3.Text);
     String myOID = textBox1.Text;
     // Define agent parameters class
     AgentParameters param = new AgentParameters(community);
     // Set SNMP version to 2
     param.Version = SnmpVersion.Ver2;
     // Construct target
     UdpTarget target = new UdpTarget((System.Net.IPAddress)agent, 161, 2000, 1);
     // Pdu class used for all requests
     Pdu pdu = new Pdu(PduType.Get);
     pdu.VbList.Add(myOID); //sysDescr
     // Make SNMP request
     SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
     return result;
 }
Beispiel #24
0
 /// <summary>
 /// WALk方法
 /// </summary>
 /// <param name="Ip_OID">ip-oid</param>
 /// <param name="outinfo">输出到那个字典</param>
 public void SnmpWalk(Dictionary<string, List<string>> Ip_OID, Dictionary<string, Dictionary<string, string>> outinfo)
 {
     foreach (string address in Ip_OID.Keys)
     {
         Dictionary<string, string> Info = new Dictionary<string, string>();
         try
         {
             {
                 Pdu pdu = new Pdu(PduType.Get);
                 foreach (string a in Ip_OID[address])
                 {
                     pdu.VbList.Add(a);
                 }
                 OctetString community = new OctetString("public");
                 AgentParameters param = new AgentParameters(community);
                 param.Version = SnmpVersion.Ver2;
                 IpAddress agent = new IpAddress(address);
                 UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                 SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                 if (result != null)
                 {
                     if (result.Pdu.ErrorStatus != 0)
                     {
                         Console.WriteLine("Error in SNMP reply. Error {0} index {1} \r\n",
                         result.Pdu.ErrorStatus,
                         result.Pdu.ErrorIndex);
                     }
                     else
                     {
                         for (int i = 0; i < pdu.VbCount; i++)
                         {
                             Info.Add(result.Pdu.VbList[i].Oid.ToString(), result.Pdu.VbList[i].Value.ToString());
                         }
                         if (outinfo.ContainsKey(address) == false)
                         {
                             outinfo.Add(address, Info);
                         }
                         else
                         {
                             outinfo[address] = Info;
                         }
                     }
                 }
                 else
                 {
                     Console.WriteLine("No response received from SNMP agent. \r\n");
                     msg.SaveTempMessage("", DateTime.Now.ToString(), "No response received from SNMP agent. \r\n");
                 }
                 target.Dispose();
             }
         }
         catch (Exception ex)
         {
             msg.SaveTempMessage(ex.Source.ToString(), ex.Message.ToString(), DateTime.Now.ToString());
         }
     }
 }
Beispiel #25
0
        void getSNMP(string ip,out float ValueA,out float ValueB,out string Status)
        {
            ValueA = 0;
                ValueB = 0;
                Status = "";
                // SNMP community name
                OctetString community = new OctetString("PUBLIC");

                // Define agent parameters class
                AgentParameters param = new AgentParameters(community);
                // Set SNMP version to 1 (or 2)
                param.Version = SnmpVersion.Ver1;

                IpAddress agent = new IpAddress(ip);

                // Construct target
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add("1.3.6.1.4.1.33826.1.1.5.1.2.1"); //a
                pdu.VbList.Add("1.3.6.1.4.1.33826.1.1.5.1.2.2"); //b
                Application.DoEvents();
                // Make SNMP request
            try{
                    SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                    Application.DoEvents();
                    // If result is null then agent didn't reply or we couldn't parse the reply.
                    if (result != null)
                    {
                        // ErrorStatus other then 0 is an error returned by
                        // the Agent - see SnmpConstants for error definitions
                        if (result.Pdu.ErrorStatus != 0)
                        {
                            // agent reported an error with the request
                            Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                result.Pdu.ErrorStatus,
                                result.Pdu.ErrorIndex);
                            Status = "false";
                        }
                        else
                        {
                            // Reply variables are returned in the same order as they were added
                            //  to the VbList
                            //  MessageBox.Show(result.Pdu.VbList[0].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + ") " + result.Pdu.VbList[0].Value.ToString());
                            //   MessageBox.Show(result.Pdu.VbList[1].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type) + ") " + result.Pdu.VbList[1].Value.ToString());
                            //  MessageBox.Show(result.Pdu.VbList[2].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type) + ") " + result.Pdu.VbList[2].Value.ToString());
                            ValueA = float.Parse(result.Pdu.VbList[0].Value.ToString()) / 10;
                            ValueB = float.Parse(result.Pdu.VbList[1].Value.ToString()) / 10;
                            Status = "done";
                        }
                    }
                    else
                    {
                        Console.WriteLine("No response received from SNMP agent.");
                    }
                    target.Close();

                }
                catch
                {
                    Status = "false";
                }
        }
Beispiel #26
0
        public Dictionary<string, string> Query(String oid, string Type)
        {
            Dictionary<string, string> Res = new Dictionary<string, string>();
            // SNMP community name
            OctetString community = new OctetString(Community);

            // Define agent parameters class
            param = new AgentParameters(community);
            // Set SNMP version to 1 (or 2)
            if (Version == 1 ) {
                param.Version = SnmpVersion.Ver1;
            }
            // Construct the agent address object
            // IpAddress class is easy to use here because
            //  it will try to resolve constructor parameter if it doesn't
            //  parse to an IP address
            IpAddress agent = new IpAddress(Ip.ToString());

            // Construct target
            UdpTarget target = new UdpTarget((IPAddress)agent, Port, 2000, 1);

            switch (Type) {
                case "get":
                    Res = getResult(target, basicInfo());
                break;

                case "walk":
                    Res = walk(target, oid);
                break;
            }

            target.Close();
            return Res;
        }
Beispiel #27
0
        /// <summary>
        /// Walks an SNMP mib table displaying the results on the fly (unless otherwise desired)
        /// </summary>
        /// <param name="log_options">Logging options</param>
        /// <param name="ip">IPAddress of device to walk</param>
        /// <param name="in_community">Read-community of device to walk</param>
        /// <param name="start_oid">Start OID (1.3, etc)</param>
        /// <returns></returns>
        public static List<SnmpV1Packet> MibWalk(LOG_OPTIONS log_options, IPAddress ip, string in_community, string start_oid)
        {
            stop = false;
            List<SnmpV1Packet> packets = new List<SnmpV1Packet>();
            // SNMP community name
            OctetString community = new OctetString(in_community);

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);
            // Set SNMP version to 1
            param.Version = SnmpVersion.Ver1;

            // Construct target
            UdpTarget target = new UdpTarget(ip, 161, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(start_oid); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetNext);

            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to a random value
                // that needs to be incremented on subsequent requests made using the
                // same instance of the Pdu class.
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                if (stop)
                {
                    return packets;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    packets.Add(result);
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Logger.Write(log_options, module, "Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                Logger.Write(log_options, module, v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) + ": " + v.Value.ToString());
                                lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();

            return packets;
        }
Beispiel #28
0
        public Dictionary<string, string> walk(UdpTarget target, string oid)
        {
            Dictionary<string, string> Output = new Dictionary<string, string>();
            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(oid); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetNext);

            if (useCache == true ) {
                Dictionary<string, string> data = getCache(target, oid);
                if (data.Count > 0 ) {
                    return data;
                }
            }

            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to a random value
                // that needs to be incremented on subsequent requests made using the
                // same instance of the Pdu class.
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                            result.Pdu.ErrorStatus,
                            result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                /*
                                  Console.WriteLine("{0} ({1}): {2}",
                                    v.Oid.ToString(),
                                    SnmpConstants.GetTypeName(v.Value.Type),
                                    v.Value.ToString());
                                 */
                                // keep the result
                                Output.Add(v.Oid.ToString(), v.Value.ToString());

                                lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }

            if (useCache == true || overrideCache == true ) {
                setCache(target, oid, Output);
            }
            return Output;
        }
 public static void GetTable()
 {
     Dictionary<String, Dictionary<uint, AsnType>> result = new Dictionary<String, Dictionary<uint, AsnType>>();
     // Not every row has a value for every column so keep track of all columns available in the table
     List<uint> tableColumns = new List<uint>();
     // Prepare agent information
     AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString("public"));
     IpAddress peer = new IpAddress("192.168.15.42");
     if (!peer.Valid)
     {
         Console.WriteLine("Unable to resolve name or error in address for peer: {0}", "");
         return;
     }
     UdpTarget target = new UdpTarget((IPAddress)peer);
     // This is the table OID supplied on the command line
     Oid startOid = new Oid("1.3.6.1.2.1.47.1.1.1");
     // Each table OID is followed by .1 for the entry OID. Add it to the table OID
     startOid.Add(1); // Add Entry OID to the end of the table OID
                      // Prepare the request PDU
     Pdu bulkPdu = Pdu.GetBulkPdu();
     bulkPdu.VbList.Add(startOid);
     // We don't need any NonRepeaters
     bulkPdu.NonRepeaters = 0;
     // Tune MaxRepetitions to the number best suited to retrive the data
     bulkPdu.MaxRepetitions = 100;
     // Current OID will keep track of the last retrieved OID and be used as
     //  indication that we have reached end of table
     Oid curOid = (Oid)startOid.Clone();
     // Keep looping through results until end of table
     while (startOid.IsRootOf(curOid))
     {
         SnmpPacket res = null;
         try
         {
             res = target.Request(bulkPdu, param);
         }
         catch (Exception ex)
         {
             Console.WriteLine("Request failed: {0}", ex.Message);
             target.Close();
             return;
         }
         // For GetBulk request response has to be version 2
         if (res.Version != SnmpVersion.Ver2)
         {
             Console.WriteLine("Received wrong SNMP version response packet.");
             target.Close();
             return;
         }
         // Check if there is an agent error returned in the reply
         if (res.Pdu.ErrorStatus != 0)
         {
             Console.WriteLine("SNMP agent returned error {0} for request Vb index {1}",
                               res.Pdu.ErrorStatus, res.Pdu.ErrorIndex);
             target.Close();
             return;
         }
         // Go through the VbList and check all replies
         foreach (Vb v in res.Pdu.VbList)
         {
             curOid = (Oid)v.Oid.Clone();
             // VbList could contain items that are past the end of the requested table.
             // Make sure we are dealing with an OID that is part of the table
             if (startOid.IsRootOf(v.Oid))
             {
                 // Get child Id's from the OID (past the table.entry sequence)
                 uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid);
                 // Get the value instance and converted it to a dotted decimal
                 //  string to use as key in result dictionary
                 uint[] instance = new uint[childOids.Length - 1];
                 Array.Copy(childOids, 1, instance, 0, childOids.Length - 1);
                 String strInst = InstanceToString(instance);
                 // Column id is the first value past <table oid>.entry in the response OID
                 uint column = childOids[0];
                 if (!tableColumns.Contains(column))
                     tableColumns.Add(column);
                 if (result.ContainsKey(strInst))
                 {
                     result[strInst][column] = (AsnType)v.Value.Clone();
                 }
                 else
                 {
                     result[strInst] = new Dictionary<uint, AsnType>();
                     result[strInst][column] = (AsnType)v.Value.Clone();
                 }
             }
             else
             {
                 // We've reached the end of the table. No point continuing the loop
                 break;
             }
         }
         // If last received OID is within the table, build next request
         if (startOid.IsRootOf(curOid))
         {
             bulkPdu.VbList.Clear();
             bulkPdu.VbList.Add(curOid);
             bulkPdu.NonRepeaters = 0;
             bulkPdu.MaxRepetitions = 100;
         }
     }
     target.Close();
     if (result.Count <= 0)
     {
         Console.WriteLine("No results returned.\n");
     }
     else
     {
         Console.Write("Instance");
         foreach (uint column in tableColumns)
         {
             Console.Write("\tColumn id {0}", column);
         }
         Console.WriteLine("");
         foreach (KeyValuePair<string, Dictionary<uint, AsnType>> kvp in result)
         {
             Console.Write("{0}", kvp.Key);
             foreach (uint column in tableColumns)
             {
                 if (kvp.Value.ContainsKey(column))
                 {
                     Console.Write("\t{0} ({1})", kvp.Value[column].ToString(),
                                       SnmpConstants.GetTypeName(kvp.Value[column].Type));
                 }
                 else
                 {
                     Console.Write("\t-");
                 }
             }
             Console.WriteLine("");
         }
     }
 }
Beispiel #30
0
        public string zwrocWartoscOID(string OID)
        {
            /*! 
		     *Zwraca wartość zadanego OID
             */
            OctetString communityOS = new OctetString(community);
            AgentParameters param = new AgentParameters(communityOS);
            param.Version = SnmpVersion.Ver1;
            IpAddress agent = new IpAddress(host);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);
            pdu.VbList.Add(OID);
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
            //wyłączony fragment kodu OID :: typ zmiennej: result.Pdu.VbList[0].Oid.ToString() + " :: " + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + " :: " + 
            string zwrot = result.Pdu.VbList[0].Value.ToString();
            return zwrot;
        }
Beispiel #31
0
 public void setCache(UdpTarget target, string oid, Dictionary<string, string> data)
 {
     RemoteQueryCache rqc = new RemoteQueryCache();
     Console.WriteLine("writting to cache");
     rqc.setCache(target.Address.ToString(), oid, data);
 }
Beispiel #32
0
        public void GetInfoOID(DataTable dtInterfaceGauge,out DataTable dt)
        {
            dt = dtInterfaceGauge.Copy();
            if (dtInterfaceGauge.Rows.Count > 0)
            {
                // SNMP community name
                OctetString community = new OctetString(_community);

                // Define agent parameters class
                AgentParameters param = new AgentParameters(community);
                // Set SNMP version to 1 (or 2)
                param.Version = SnmpVersion.Ver1;
                // Construct the agent address object
                // IpAddress class is easy to use here because
                //  it will try to resolve constructor parameter if it doesn't
                //  parse to an IP address
                IpAddress agent = new IpAddress(_ipHost);

                // Construct target
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.Get);

                for (int i = 0; i < dtInterfaceGauge.Rows.Count; i++)
                {
                    pdu.VbList.Add(dtInterfaceGauge.Rows[i]["OIDIn"].ToString());
                    pdu.VbList.Add(dtInterfaceGauge.Rows[i]["OIDOut"].ToString());
                }
                // Make SNMP request
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                            result.Pdu.ErrorStatus,
                            result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        // MessageBox.Show(result.Pdu.VbList[0].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + ") " + result.Pdu.VbList[0].Value.ToString());

                        for (int i = 0; i < dtInterfaceGauge.Rows.Count; i++)
                        {
                            dtInterfaceGauge.Rows[i]["InBandwidth"] = result.Pdu.VbList[i+i].Value.ToString();
                            dtInterfaceGauge.Rows[i]["OutBandwidth"] = result.Pdu.VbList[i+i+1].Value.ToString();
                        }
                        dt = dtInterfaceGauge;
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
                target.Close();
            }
        }
Beispiel #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);
 /// // 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)
     {
         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
     {
         _target = null;
     }
     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_ENDOFMIBVIEW) ||
                         (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE) ||
                         (v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT))
                     {
                         break;
                     }
                     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);
 }
Beispiel #34
0
 /// <summary>
 ///     SNMP GET-BULK request
 /// </summary>
 /// <remarks>
 ///     GetBulk request type is only available with SNMP v2c agents. SNMP v3 also supports the request itself
 ///     but that version of the protocol is not supported by SimpleSnmp.
 ///     GetBulk method will return a dictionary of Oid to value mapped values as returned form a
 ///     single GetBulk request to the agent. You can change how the request itself is made by changing the
 ///     SimpleSnmp.NonRepeaters and SimpleSnmp.MaxRepetitions values. SimpleSnmp properties are only used
 ///     when values in the parameter Pdu are set to 0.
 /// </remarks>
 /// <example>
 ///     SNMP GET-BULK 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.GETBULK; // type GETBULK
 /// pdu.VbList.Add("1.3.6.1.2.1.1");
 /// pdu.NonRepeaters = 0;
 /// pdu.MaxRepetitions = 10;
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetBulk(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"
 /// 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>
 /// </example>
 /// <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> GetBulk(Pdu pdu)
 {
     if (!Valid)
     {
         if (!_suppressExceptions)
         {
             throw new SnmpException("SimpleSnmp class is not valid.");
         }
         return(null); // class is not fully initialized.
     }
     try
     {
         pdu.NonRepeaters   = _nonRepeaters;
         pdu.MaxRepetitions = _maxRepetitions;
         _target            = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
     }
     catch (Exception ex)
     {
         _target = null;
         if (!_suppressExceptions)
         {
             throw ex;
         }
     }
     if (_target == null)
     {
         return(null);
     }
     try
     {
         var param  = new AgentParameters(SnmpVersion.Ver2, new OctetString(_community));
         var result = _target.Request(pdu, param);
         if (result != null)
         {
             if (result.Pdu.ErrorStatus == 0)
             {
                 var res = new Dictionary <Oid, AsnType>();
                 foreach (var v in result.Pdu.VbList)
                 {
                     if (
                         v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW ||
                         v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE ||
                         v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT
                         )
                     {
                         break;
                     }
                     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);
                         }
                         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);
 }
Beispiel #35
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["key"] != null)
                {
                    txtCommand.Visible = false;
                    btnSubmit.Visible = false;
                    string _key = Request.Form["key"].ToString().Trim();
                    if (_key.IndexOf("168.") > 0)
                    {

                        // kiem tra neu key la IP thi log thang vao modem

                        _key = _key.Trim();
                        try
                        {
                            string IP = _key;
                            if (IP.Trim() != "")
                            {
                                if (IP.Trim() != "0.0.0.0")
                                {
                                    // SNMP community name
                                    OctetString community = new OctetString("LBC");

                                    // Define agent parameters class
                                    AgentParameters param = new AgentParameters(community);
                                    // Set SNMP version to 1 (or 2)
                                    param.Version = SnmpVersion.Ver1;

                                    IpAddress agent = new IpAddress(IP);

                                    // Construct target
                                    UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                                    // Pdu class used for all requests
                                    Pdu pdu = new Pdu(PduType.Get);
                                    pdu.VbList.Add("1.3.6.1.2.1.10.127.1.1.4.1.5.3"); //Noise  -- value1
                                    pdu.VbList.Add("1.3.6.1.2.1.10.127.1.2.2.1.3.2"); //US Power Level --- value2
                                    pdu.VbList.Add("1.3.6.1.2.1.10.127.1.1.1.1.6.3"); //DS Power level     -- value3

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

                                    // If result is null then agent didn't reply or we couldn't parse the reply.
                                    if (result != null)
                                    {
                                        // ErrorStatus other then 0 is an error returned by
                                        // the Agent - see SnmpConstants for error definitions
                                        if (result.Pdu.ErrorStatus != 0)
                                        {
                                            // agent reported an error with the request
                                            Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                                result.Pdu.ErrorStatus,
                                                result.Pdu.ErrorIndex);
                                            lblKQ.Text = "Device Offline";
                                        }
                                        else
                                        {
                                            // Reply variables are returned in the same order as they were added
                                            //  to the VbList
                                            lblKQ.Text += "DS SNR: " + (float.Parse(result.Pdu.VbList[0].Value.ToString()) / 10).ToString() + "   \r\n";
                                            lblKQ.Text += "US Tx: " + (float.Parse(result.Pdu.VbList[1].Value.ToString()) / 10).ToString() + "   \r\n";
                                            lblKQ.Text += "DS Rx: " + (float.Parse(result.Pdu.VbList[2].Value.ToString()) / 10).ToString() + "   \n\r";
                                            // gridItemDetail.SetRowCellValue(gridItemDetail.FocusedRowHandle, colValue1, (float.Parse(result.Pdu.VbList[0].Value.ToString()) / 10).ToString());
                                            //  gridItemDetail.SetRowCellValue(gridItemDetail.FocusedRowHandle, colValue2, (float.Parse(result.Pdu.VbList[1].Value.ToString()) / 10).ToString());
                                            // gridItemDetail.SetRowCellValue(gridItemDetail.FocusedRowHandle, colValue3, (float.Parse(result.Pdu.VbList[2].Value.ToString()) / 10).ToString());
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("No response received from SNMP agent.");
                                        lblKQ.Text = "Device Offline";
                                    }
                                    target.Close();

                                }
                            }

                        }
                        catch { lblKQ.Text = "Device Offline"; }

                        // lblKQ.Text = _key;
                    }
                    else
                    {
                        if (Request.Form["mode"] != null)
                        {
                            if (Request.Form["mode"].ToString().Trim() == "phy")
                            {
                                string result = ShowCable(_key, "phy");
                                string[] sp = result.Split('|');
                                result = "";
                                for (int i = 0; i < sp.Length; i++)
                                {
                                    string _mac = "";
                                    if (sp[i].Length > 13)
                                    {
                                        string txt = sp[i].Trim();
                                        _mac = txt.Substring(0, 14);
                                        _mac = _mac.Trim();
                                    }
                                    if (_mac != "")
                                    {
                                        if (!_mac.Contains("Server"))
                                        {
                                            _mac = "<a href=http://101.99.28.156:88/sv2.aspx?macip=" + _mac + ">" + _mac + "</a>" + sp[i].Trim().Substring(14) + "<br>";
                                            result += _mac.Trim();
                                        }
                                        else
                                        {
                                            _mac = _mac + sp[i].Trim().Substring(14) + "<br>";
                                            result += _mac.Trim();
                                        }
                                    }
                                }
                                lblKQ.Text = result.Trim();
                            }
                            else
                            {
                                lblKQ.Text = ShowCable(_key, "remote");
                            }
                        }
                        else
                        {
                            string result = ShowCable(_key, "phy");
                            string[] sp = result.Split('|');
                            result = "";
                            for (int i = 0; i < sp.Length; i++)
                            {
                                string _mac = "";
                                if (sp[i].Length > 13)
                                {
                                    string txt = sp[i].Trim();
                                    _mac = txt.Substring(0, 14);
                                    _mac = _mac.Trim();
                                }
                                if (_mac != "")
                                {
                                    if (!_mac.Contains("Server"))
                                    {
                                        _mac = "<a href=http://101.99.28.156:88/sv2.aspx?macip=" + _mac + ">" + _mac + "</a>" + sp[i].Trim().Substring(14) + "<br>";
                                        result += _mac.Trim();
                                    }
                                    else
                                    {
                                        _mac = _mac + sp[i].Trim().Substring(14) + "<br>";
                                        result += _mac.Trim();
                                    }
                                }
                            }
                            lblKQ.Text = result.Trim();
                            // lblKQ.Text = ShowCable(_key, "phy");
                        }
                        DateTime datetime = DateTime.Now;
                        // giai phong telnet
                        if (datetime.Minute.ToString() == "5" || datetime.Minute.ToString() == "10" || datetime.Minute.ToString() == "15" || datetime.Minute.ToString() == "20" || datetime.Minute.ToString() == "25" || datetime.Minute.ToString() == "30" || datetime.Minute.ToString() == "35" || datetime.Minute.ToString() == "40" || datetime.Minute.ToString() == "45" || datetime.Minute.ToString() == "50" || datetime.Minute.ToString() == "55")
                        {
                            SendCMD("exit");
                            tcpClient = null;
                        }

                    }
                }       // het key
                else
                {
                    if (Request.QueryString["macip"] != null)
                    {
                        string _mac = Request.QueryString["macip"].ToString().Trim();
                        try
                        {
                            string result = SendCMD("sh host authorization | include " + _mac);
                            result = result.Replace("sh host authorization | include " + _mac, "");
                            result = result.Replace("Host", "<br>Host");
                            result = result.Replace("Modem", "<br>Modem");
                            result = result.Replace("MOT:7A#", "");
                            lblKQ.Text = result.Trim();

                        }
                        catch (Exception ex)
                        {
                            lblKQ.Text = ex.Message;
                        }
                    }

                    txtCommand.Visible = false;
                    btnSubmit.Visible = false;
                }
        }
Beispiel #36
0
        public Dictionary<string, string> getResult( UdpTarget target, Pdu pdu )
        {
            Dictionary<string, string> Res = new Dictionary<string, string> ();
            // Make SNMP request
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                        result.Pdu.ErrorStatus,
                        result.Pdu.ErrorIndex);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    Console.WriteLine("sysDescr({0}) ({1}): {2}",
                        result.Pdu.VbList[0].Oid.ToString(),
                        SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                        result.Pdu.VbList[0].Value.ToString());
                    Console.WriteLine("sysObjectID({0}) ({1}): {2}",
                        result.Pdu.VbList[1].Oid.ToString(),
                        SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type),
                        result.Pdu.VbList[1].Value.ToString());
                    Console.WriteLine("sysUpTime({0}) ({1}): {2}",
                        result.Pdu.VbList[2].Oid.ToString(),
                        SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type),
                        result.Pdu.VbList[2].Value.ToString());
                    Console.WriteLine("sysContact({0}) ({1}): {2}",
                        result.Pdu.VbList[3].Oid.ToString(),
                        SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type),
                        result.Pdu.VbList[3].Value.ToString());
                    Console.WriteLine("sysName({0}) ({1}): {2}",
                        result.Pdu.VbList[4].Oid.ToString(),
                        SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type),
                        result.Pdu.VbList[4].Value.ToString());
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }

            return Res; // FIXME not sure if going to need this method
        }
Beispiel #37
0
        public void init()
        {
            Console.Write("please input agent ip[" + ip + "]:");
            String tmp = Console.ReadLine();
            if (tmp.StartsWith("debug"))
            {
                for (int i = 0; i < oids.Length; i++)
                {
                    Console.WriteLine(oids[i][0]);
                }
                Console.Write("please input agent ip[" + ip + "]:");
                tmp = Console.ReadLine();
            }
            ip = tmp.Length > 0 ? tmp.Trim() : ip;

            Console.Write("please input agent port[" + port + "]:");
            tmp = Console.ReadLine();
            port = tmp.Length > 0 ? tmp.Trim() : port;

            Console.Write("please input agent read community[" + rc + "]:");
            tmp = Console.ReadLine();
            rc = tmp.Length > 0 ? tmp.Trim() : rc;

            Console.WriteLine(ip + ":" + port + ":" + rc);

            OctetString community = new OctetString(rc);
            param = new AgentParameters(community);
            param.Version = SnmpVersion.Ver2;
            IpAddress agent = new IpAddress(ip);
            target = new UdpTarget((IPAddress)agent, int.Parse(port), 10000, 2);
        }
Beispiel #38
-1
        /// <summary>
        /// Executa uma requisição do tipo Set
        /// </summary>
        /// <param name="setValue">Valor a set definido</param>
        public void Send(AsnType setValue)
        {
            using (var target = new UdpTarget(Host.IP, Host.Port, TimeOut, Retries))
            {
                var agentp = new AgentParameters(SnmpVersion.Ver2, new OctetString(Host.Community));

                // Caso necessario, appenda o .0 na requisição
                var oid = new Oid(Object.OID);
                if (oid[oid.Length - 1] != 0)
                    oid.Add(0);

                // Cria pacote de dados
                RequestData = new Pdu(setValue == null ? PduType.Get : PduType.Set);

                // Adiciona dados da requisição
                switch (RequestData.Type)
                {
                    case PduType.Get:
                        RequestData.VbList.Add(oid);
                        break;
                    case PduType.Set:
                        RequestData.VbList.Add(oid, setValue);
                        break;
                    default:
                        throw new InvalidOperationException("unsupported");
                }
                try
                {
                    if (LogRequests) Logger.Self.Log(this);
                    Timestamp = DateTime.Now;

                    // Envia requisição
                    ResponsePacket = target.Request(RequestData, agentp) as SnmpV2Packet;

                    // Trata resposta
                    if (ResponsePacket != null && ResponsePacket.Pdu.ErrorStatus == (int)PduErrorStatus.noError)
                    {
                        // TODO: suportar mais de um retorno
                        var item = ResponsePacket.Pdu.VbList[0];

                        ResponseValue = item.Value;
                        if (LogRequests) Logger.Self.Log(item);
                    }
                }
                catch (Exception ex)
                {
                    if (LogRequests) Logger.Self.Log(ex);
                    throw new SnmpException("Não foi possível realizar a operação");
                }
            }
        }