SNMP Agent specific values.
This class stores values to access SNMP version 1 and version 2 agents. Pass this class with your request data (Pdu) to the request method of the target class to make a request.
Inheritance: IAgentParameters
コード例 #1
1
ファイル: dane_geber.cs プロジェクト: Kuczmil/RE-SE
        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;
        }
コード例 #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()));
         }
     }
 }
コード例 #3
0
ファイル: EASYSNMP.cs プロジェクト: hw901013/hw901013
        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();
            }
        }
コード例 #4
0
ファイル: SNMP_Tools.cs プロジェクト: jonathan84clark/JTool
        /// <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;
        }
コード例 #5
0
ファイル: Form1.cs プロジェクト: thakools/SNMPCollector
 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;
 }
コード例 #6
0
ファイル: snmp.cs プロジェクト: g23988/scanNetwork
        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;
        }
コード例 #7
0
ファイル: UdpTarget.cs プロジェクト: mspratap6/SnmpSharpNet
        /// <summary>
        /// Make SNMP request. With this method you can make blocked SNMP version 1, 2 and 3 requests of type GET,
        /// GET-NEXT, GET-BULK, SET and REPORT (request types have to compatible with the SNMP protocol version you
        /// are using).
        ///
        /// This method will pass through any exceptions thrown by parsing classes/methods so see individual packet
        /// classes, ASN.1 type classes, authentication, privacy, etc. classes for exceptions thrown.
        /// </summary>
        /// <param name="pdu">Pdu class (do not pass ScopedPdu)</param>
        /// <param name="agentParameters">Security information for the request. Use <see cref="AgentParameters"/>
        /// for SNMP versions 1 and 2 requests. Use <see cref="SecureAgentParameters"/> for SNMP version 3
        /// requests.</param>
        /// <param name="responseCallback">Callback that receives the result of the async operation.</param>
        /// <returns>True if async request was successfully initiated, otherwise false.</returns>
        public bool RequestAsync(Pdu pdu, IAgentParameters agentParameters, SnmpAsyncResponse responseCallback)
        {
            if (IsBusy)
            {
                return(false); // class is busy
            }
            _response        = null;
            _response       += responseCallback;
            _agentParameters = agentParameters;
            byte[] outPacket;
            if (agentParameters.Version == SnmpVersion.Ver3)
            {
                SecureAgentParameters secparams = (SecureAgentParameters)agentParameters;
                if (secparams.Authentication != AuthenticationDigests.None && secparams.AuthenticationSecret.Length <= 0)
                {
                    // _response(AsyncRequestResult.AuthenticationError, null);
                    return(false);
                }
                if (secparams.Privacy != PrivacyProtocols.None && secparams.PrivacySecret.Length <= 0)
                {
                    // _response(AsyncRequestResult.PrivacyError, null);
                    return(false);
                }
                _noSourceCheck = false; // this option is not valid for SNMP v3 requests
                ScopedPdu outPdu = new ScopedPdu(pdu);
                outPdu.ContextEngineId.Set(secparams.EngineId);
                outPdu.ContextName.Set(secparams.ContextName);
                SnmpV3Packet packet = new SnmpV3Packet(outPdu);
                secparams.InitializePacket(packet);
                try
                {
                    if (secparams.HasCachedKeys)
                    {
                        outPacket = packet.Encode(secparams.AuthenticationKey, secparams.PrivacyKey);
                    }
                    else
                    {
                        outPacket = packet.Encode();
                    }
                }
                catch (Exception ex)
                {
                    ex.GetType();
                    _response(AsyncRequestResult.EncodeError, packet);
                    return(false);
                }
            }
            else if (agentParameters.Version == (int)SnmpVersion.Ver1)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                _noSourceCheck = param.DisableReplySourceCheck;
                SnmpV1Packet packet = new SnmpV1Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                try
                {
                    outPacket = packet.Encode();
                }
                catch (Exception ex)
                {
                    ex.GetType();
                    _response(AsyncRequestResult.EncodeError, packet);
                    return(false);
                }
            }
            else if (agentParameters.Version == SnmpVersion.Ver2)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                _noSourceCheck = param.DisableReplySourceCheck;
                SnmpV2Packet packet = new SnmpV2Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                try
                {
                    outPacket = packet.Encode();
                }
                catch (Exception ex)
                {
                    ex.GetType();
                    _response(AsyncRequestResult.EncodeError, packet);
                    return(false);
                }
            }
            else
            {
                throw new SnmpInvalidVersionException("Unsupported SNMP version.");
            }

            if (!base.RequestAsync(_address, _port, outPacket, outPacket.Length, _timeout, _retry, new SnmpAsyncCallback(AsyncResponse)))
            {
                return(false);
            }
            return(true);
        }
コード例 #8
0
 /// <summary>Copy constructor. Initialize the class with the values of the parameter class values.</summary>
 /// <param name="second">Parameter class.</param>
 public AgentParameters(AgentParameters second)
 {
     version.Value = (int)second.Version;
     community.Set(second.Community);
     disableReplySourceCheck = second.DisableReplySourceCheck;
 }
コード例 #9
0
ファイル: SNMP_Tools.cs プロジェクト: jonathan84clark/JTool
 /// <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;
 }
コード例 #10
0
ファイル: SimpleSnmp.cs プロジェクト: griffina/SnmpSharpNet
 /// <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
     {
         AgentParameters param = new AgentParameters(SnmpVersion.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.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;
 }
コード例 #11
0
ファイル: frmOpticalSW.cs プロジェクト: tayeumi/HFC
        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";
                }
        }
コード例 #12
0
ファイル: SimpleSnmp.cs プロジェクト: griffina/SnmpSharpNet
 /// <summary>
 /// SNMP SET request
 /// </summary>
 /// <example>Set operation in SNMP version 1:
 /// <code>
 /// String snmpAgent = "10.10.10.1";
 /// String snmpCommunity = "private";
 /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
 /// // Create a request Pdu
 /// Pdu pdu = new Pdu();
 /// pdu.Type = SnmpConstants.SET; // type SET
 /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0
 /// OctetString setValue = new OctetString("My personal toy");
 /// pdu.VbList.Add(setOid, setValue);
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Set(SnmpVersion.Ver1, pdu);
 /// if( result == null ) {
 ///   Console.WriteLine("Request failed.");
 /// } else {
 ///   Console.WriteLine("Success!");
 /// }
 /// </code>
 /// 
 /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
 /// </example>
 /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
 /// <param name="pdu">Request Protocol Data Unit</param>
 /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
 public Dictionary<Oid, AsnType> Set(SnmpVersion version, Pdu pdu)
 {
     if (!Valid)
     {
         if (!_suppressExceptions)
         {
             throw new SnmpException("SimpleSnmp class is not valid.");
         }
         return null; // class is not fully initialized.
     }
     // function only works on SNMP version 1 and SNMP version 2 requests
     if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
     {
         if (!_suppressExceptions)
         {
             throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
         }
         return null;
     }
     try
     {
         _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
     }
     catch(Exception ex)
     {
         _target = null;
         if( ! _suppressExceptions)
         {
             throw ex;
         }
     }
     if( _target == null )
     {
         return null;
     }
     try {
         AgentParameters param = new AgentParameters(version, new OctetString(_community));
         SnmpPacket result = _target.Request(pdu, param);
         if (result != null)
         {
             if (result.Pdu.ErrorStatus == 0)
             {
                 Dictionary<Oid, AsnType> res = new Dictionary<Oid, AsnType>();
                 foreach (Vb v in result.Pdu.VbList)
                 {
                     if (res.ContainsKey(v.Oid))
                     {
                         if (res[v.Oid].Type != v.Value.Type)
                         {
                             throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString());
                         }
                         else
                         {
                             res[v.Oid] = v.Value;
                         }
                     }
                     else
                     {
                         res.Add(v.Oid, v.Value);
                     }
                 }
                 _target.Close();
                 _target = null;
                 return res;
             }
             else
             {
                 if( ! _suppressExceptions )
                 {
                     throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                 }
             }
         }
     }
     catch(Exception ex)
     {
         if( ! _suppressExceptions )
         {
             _target.Close();
             _target = null;
             throw ex;
         }
     }
     _target.Close();
     _target = null;
     return null;
 }
コード例 #13
0
 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("");
         }
     }
 }
コード例 #14
0
ファイル: SimpleSnmp.cs プロジェクト: tuga1975/SnmpSharpNet
 /// <summary>
 /// SNMP GET request
 /// </summary>
 /// <example>SNMP GET request:
 /// <code>
 /// String snmpAgent = "10.10.10.1";
 /// String snmpCommunity = "public";
 /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
 /// // Create a request Pdu
 /// Pdu pdu = new Pdu();
 /// pdu.Type = SnmpConstants.GET; // type GET
 /// pdu.VbList.Add("1.3.6.1.2.1.1.1.0");
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.GetNext(SnmpVersion.Ver1, pdu);
 /// if( result == null ) {
 ///   Console.WriteLine("Request failed.");
 /// } else {
 ///   foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result)
 ///   {
 ///     Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
 ///       entry.Value.ToString());
 ///   }
 /// }
 /// </code>
 /// Will return:
 /// <code>
 /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
 /// </code>
 /// </example>
 /// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
 /// <param name="pdu">Request Protocol Data Unit</param>
 /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
 public Dictionary <Oid, AsnType> Get(SnmpVersion version, Pdu pdu)
 {
     if (!Valid)
     {
         if (!_suppressExceptions)
         {
             throw new SnmpException("SimpleSnmp class is not valid.");
         }
         return(null);                // class is not fully initialized.
     }
     // function only works on SNMP version 1 and SNMP version 2 requests
     if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
     {
         if (!_suppressExceptions)
         {
             throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
         }
         return(null);
     }
     try
     {
         _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
     }
     catch (Exception ex)
     {
         _target = null;
         if (!_suppressExceptions)
         {
             throw ex;
         }
     }
     if (_target == null)
     {
         return(null);
     }
     try
     {
         AgentParameters param  = new AgentParameters(version, new OctetString(_community));
         SnmpPacket      result = _target.Request(pdu, param);
         if (result != null)
         {
             if (result.Pdu.ErrorStatus == 0)
             {
                 Dictionary <Oid, AsnType> res = new Dictionary <Oid, AsnType>();
                 foreach (Vb v in result.Pdu.VbList)
                 {
                     if (version == SnmpVersion.Ver2 && (v.Value.Type == SnmpConstants.SMI_NOSUCHINSTANCE ||
                                                         v.Value.Type == SnmpConstants.SMI_NOSUCHOBJECT))
                     {
                         if (!res.ContainsKey(v.Oid))
                         {
                             res.Add(v.Oid, new Null());
                         }
                         else
                         {
                             res.Add(Oid.NullOid(), v.Value);
                         }
                     }
                     else
                     {
                         if (!res.ContainsKey(v.Oid))
                         {
                             res.Add(v.Oid, v.Value);
                         }
                         else
                         {
                             if (res[v.Oid].Type == v.Value.Type)
                             {
                                 res[v.Oid] = v.Value;                                         // update value of the existing Oid entry
                             }
                             else
                             {
                                 throw new SnmpException(SnmpException.OidValueTypeChanged, String.Format("Value type changed from {0} to {1}", res[v.Oid].Type, v.Value.Type));
                             }
                         }
                     }
                 }
                 _target.Close();
                 _target = null;
                 return(res);
             }
             else
             {
                 if (!_suppressExceptions)
                 {
                     throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         if (!_suppressExceptions)
         {
             _target.Close();
             _target = null;
             throw ex;
         }
     }
     _target.Close();
     _target = null;
     return(null);
 }
コード例 #15
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);
        }
コード例 #16
0
ファイル: UdpTarget.cs プロジェクト: mspratap6/SnmpSharpNet
        /// <summary>Make SNMP Request</summary>
        /// <remarks>
        /// Make SNMP request. With this method you can make blocked SNMP version 1, 2 and 3 requests of type GET,
        /// GET-NEXT, GET-BULK, SET and REPORT (request types have to compatible with the SNMP protocol version you
        /// are using).
        ///
        /// This method will pass through any exceptions thrown by parsing classes/methods so see individual packet
        /// classes, ASN.1 type classes, authentication, privacy, etc. classes for exceptions thrown.
        /// </remarks>
        /// <param name="pdu">Pdu class (do not pass ScopedPdu)</param>
        /// <param name="agentParameters">Security information for the request. Use <see cref="AgentParameters"/>
        /// for SNMP versions 1 and 2 requests. Use <see cref="SecureAgentParameters"/> for SNMP version 3
        /// requests.</param>
        /// <returns>Appropriate SNMP packet class for the reply received (<see cref="SnmpV1Packet"/>,
        /// <see cref="SnmpV2Packet"/>, or <see cref="SnmpV3Packet"/>. Null value if there was an error
        /// with the request.</returns>
        /// <exception cref="SnmpAuthenticationException">Thrown on SNMPv3 requests when authentication password
        /// is not specified on authNoPriv or authPriv requests in SecureAgentParameters or if incoming packet
        /// authentication check failed.
        ///
        /// With SNMP ver1 and ver2c, authentication check fails when invalid community name is parsed in the reply.</exception>
        /// <exception cref="SnmpPrivacyException">Thrown on SNMPv3 requests when privacy password is not
        /// specified in SecureAgentParameters on authPriv requests.</exception>
        /// <exception cref="SnmpException">Thrown in following cases:
        ///
        /// * IAgentParameters.Valid() returned false. SnmpException.ErrorCode is set to SnmpException.InvalidIAgentParameters
        /// * No data received on request. SnmpException.ErrorCode is set to SnmpException.NoDataReceived
        /// * Invalid RequestId in reply. SnmpException.ErrorCode is set to SnmpException.InvalidRequestId
        /// </exception>
        public SnmpPacket Request(Pdu pdu, IAgentParameters agentParameters)
        {
            byte[] outPacket;
            if (agentParameters.Version == SnmpVersion.Ver3)
            {
                SecureAgentParameters secparams = (SecureAgentParameters)agentParameters;
                if (secparams.Authentication != AuthenticationDigests.None && secparams.AuthenticationSecret.Length <= 0)
                {
                    throw new SnmpAuthenticationException("Authentication password not specified.");
                }

                if (secparams.Privacy != PrivacyProtocols.None && secparams.PrivacySecret.Length <= 0)
                {
                    throw new SnmpPrivacyException("Privacy password not specified.");
                }

                _noSourceCheck = false; // this option is not valid for SNMP v3 requests
                ScopedPdu    outPdu = new ScopedPdu(pdu);
                SnmpV3Packet packet = new SnmpV3Packet(outPdu);
                secparams.InitializePacket(packet);
                if (secparams.HasCachedKeys)
                {
                    outPacket = packet.Encode(secparams.AuthenticationKey, secparams.PrivacyKey);
                }
                else
                {
                    outPacket = packet.Encode();
                }
            }
            else if (agentParameters.Version == SnmpVersion.Ver1)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                if (!param.Valid())
                {
                    throw new SnmpException(SnmpException.InvalidIAgentParameters, "Invalid AgentParameters. Unable to process request.");
                }

                SnmpV1Packet packet = new SnmpV1Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                outPacket      = packet.Encode();
                _noSourceCheck = param.DisableReplySourceCheck;
            }
            else if (agentParameters.Version == SnmpVersion.Ver2)
            {
                AgentParameters param = (AgentParameters)agentParameters;
                if (!param.Valid())
                {
                    throw new SnmpException(SnmpException.InvalidIAgentParameters, "Invalid AgentParameters. Unable to process request.");
                }

                SnmpV2Packet packet = new SnmpV2Packet();
                packet.Pdu.Set(pdu);
                packet.Community.Set(param.Community);
                _noSourceCheck = param.DisableReplySourceCheck;
                outPacket      = packet.Encode();
            }
            else
            {
                throw new SnmpInvalidVersionException("Unsupported SNMP version.");
            }

            byte[] inBuffer = base.Request(_address, _port, outPacket, outPacket.Length, _timeout, _retry);

            if (inBuffer == null || inBuffer.Length <= 0)
            {
                throw new SnmpException(SnmpException.NoDataReceived, "No data received on request.");
            }
            // verify packet
            if (agentParameters.Version == SnmpVersion.Ver1)
            {
                SnmpV1Packet    packet = new SnmpV1Packet();
                AgentParameters param  = (AgentParameters)agentParameters;
                packet.Decode(inBuffer, inBuffer.Length);
                if (packet.Community != param.Community)
                {
                    // invalid community name received. Ignore the rest of the packet
                    throw new SnmpAuthenticationException("Invalid community name in reply.");
                }
                if (packet.Pdu.RequestId != pdu.RequestId)
                {
                    // invalid request id. unmatched response ignored
                    throw new SnmpException(SnmpException.InvalidRequestId, "Invalid request id in reply.");
                }
                return(packet);
            }
            else if (agentParameters.Version == SnmpVersion.Ver2)
            {
                SnmpV2Packet    packet = new SnmpV2Packet();
                AgentParameters param  = (AgentParameters)agentParameters;
                packet.Decode(inBuffer, inBuffer.Length);
                if (packet.Community != param.Community)
                {
                    // invalid community name received. Ignore the rest of the packet
                    throw new SnmpAuthenticationException("Invalid community name in reply.");
                }
                if (packet.Pdu.RequestId != pdu.RequestId)
                {
                    // invalid request id. unmatched response ignored
                    throw new SnmpException(SnmpException.InvalidRequestId, "Invalid request id in reply.");
                }
                return(packet);
            }
            else if (agentParameters.Version == SnmpVersion.Ver3)
            {
                SnmpV3Packet          packet    = new SnmpV3Packet();
                SecureAgentParameters secparams = (SecureAgentParameters)agentParameters;
                secparams.InitializePacket(packet);
                if (secparams.HasCachedKeys)
                {
                    packet.Decode(inBuffer, inBuffer.Length, secparams.AuthenticationKey, secparams.PrivacyKey);
                }
                else
                {
                    packet.Decode(inBuffer, inBuffer.Length);
                }
                // first check if packet is a discovery response and process it
                if (packet.Pdu.Type == PduType.Report && packet.Pdu.VbCount > 0 && packet.Pdu.VbList[0].Oid.Equals(SnmpConstants.usmStatsUnknownEngineIDs))
                {
                    secparams.UpdateDiscoveryValues(packet);
                    return(packet);
                }
                else
                {
                    if (!secparams.ValidateIncomingPacket(packet))
                    {
                        return(null);
                    }
                    else
                    {
                        secparams.UpdateDiscoveryValues(packet); // update time, etc. values
                        return(packet);
                    }
                }
            }
            return(null);
        }
コード例 #17
0
ファイル: SimpleSnmp.cs プロジェクト: tuga1975/SnmpSharpNet
 /// <summary>
 /// SNMP SET request
 /// </summary>
 /// <example>Set operation in SNMP version 1:
 /// <code>
 /// String snmpAgent = "10.10.10.1";
 /// String snmpCommunity = "private";
 /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
 /// // Create a request Pdu
 /// Pdu pdu = new Pdu();
 /// pdu.Type = SnmpConstants.SET; // type SET
 /// Oid setOid = new Oid("1.3.6.1.2.1.1.1.0"); // sysDescr.0
 /// OctetString setValue = new OctetString("My personal toy");
 /// pdu.VbList.Add(setOid, setValue);
 /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Set(SnmpVersion.Ver1, pdu);
 /// if( result == null ) {
 ///   Console.WriteLine("Request failed.");
 /// } else {
 ///   Console.WriteLine("Success!");
 /// }
 /// </code>
 ///
 /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
 /// </example>
 /// <param name="version">SNMP protocol version number. Acceptable values are SnmpVersion.Ver1 and SnmpVersion.Ver2</param>
 /// <param name="pdu">Request Protocol Data Unit</param>
 /// <returns>Result of the SNMP request in a dictionary format with Oid => AsnType values</returns>
 public Dictionary <Oid, AsnType> Set(SnmpVersion version, Pdu pdu)
 {
     if (!Valid)
     {
         if (!_suppressExceptions)
         {
             throw new SnmpException("SimpleSnmp class is not valid.");
         }
         return(null);                // class is not fully initialized.
     }
     // function only works on SNMP version 1 and SNMP version 2 requests
     if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
     {
         if (!_suppressExceptions)
         {
             throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
         }
         return(null);
     }
     try
     {
         _target = new UdpTarget(_peerIP, _peerPort, _timeout, _retry);
     }
     catch (Exception ex)
     {
         _target = null;
         if (!_suppressExceptions)
         {
             throw ex;
         }
     }
     if (_target == null)
     {
         return(null);
     }
     try {
         AgentParameters param  = new AgentParameters(version, new OctetString(_community));
         SnmpPacket      result = _target.Request(pdu, param);
         if (result != null)
         {
             if (result.Pdu.ErrorStatus == 0)
             {
                 Dictionary <Oid, AsnType> res = new Dictionary <Oid, AsnType>();
                 foreach (Vb v in result.Pdu.VbList)
                 {
                     if (res.ContainsKey(v.Oid))
                     {
                         if (res[v.Oid].Type != v.Value.Type)
                         {
                             throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + v.Oid.ToString());
                         }
                         else
                         {
                             res[v.Oid] = v.Value;
                         }
                     }
                     else
                     {
                         res.Add(v.Oid, v.Value);
                     }
                 }
                 _target.Close();
                 _target = null;
                 return(res);
             }
             else
             {
                 if (!_suppressExceptions)
                 {
                     throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         if (!_suppressExceptions)
         {
             _target.Close();
             _target = null;
             throw ex;
         }
     }
     _target.Close();
     _target = null;
     return(null);
 }
コード例 #18
0
ファイル: SimpleSnmp.cs プロジェクト: tuga1975/SnmpSharpNet
 /// <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
     {
         AgentParameters param  = new AgentParameters(SnmpVersion.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.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);
 }
コード例 #19
0
ファイル: PrinterObj.cs プロジェクト: jlam916/ServiceDesk
    /// <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();
    }
コード例 #20
0
ファイル: SharpWalk.cs プロジェクト: odnanref/snrviewer
        static void remoteCall(string[] args)
        {
            // SNMP community name
            OctetString community = new OctetString("public");

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);
            // Set SNMP version to 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("127.0.0.1");

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

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid("1.3.6.1.2.1.2.2.1.2"); // 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
                        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.Close();
        }
コード例 #21
0
ファイル: EASYSNMP.cs プロジェクト: hw901013/hw901013
 /// <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());
         }
     }
 }
コード例 #22
0
ファイル: dane_geber.cs プロジェクト: Kuczmil/RE-SE
        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;
        }
コード例 #23
0
ファイル: NW_InterfaceGauge.cs プロジェクト: tayeumi/HFC
        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();
            }
        }
コード例 #24
0
ファイル: dane_geber.cs プロジェクト: Kuczmil/RE-SE
        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;
        }
コード例 #25
0
ファイル: Form1.cs プロジェクト: shakasi/shakasi.github.com
        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();
        }
コード例 #26
0
ファイル: dane_geber.cs プロジェクト: Kuczmil/RE-SE
        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;
        }
コード例 #27
0
ファイル: getSignal.aspx.cs プロジェクト: tayeumi/HFC
        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>"); }
        }
コード例 #28
0
ファイル: dane_geber.cs プロジェクト: Kuczmil/RE-SE
        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;
        }
コード例 #29
0
 /// <summary>
 /// Copy constructor. Initialize the class with the values of the parameter class values.
 /// </summary>
 /// <param name="second">Parameter class.</param>
 public AgentParameters(AgentParameters second)
 {
     _version.Value = (int)second.Version;
     _community.Set(second.Community);
     _disableReplySourceCheck = second.DisableReplySourceCheck;
 }
コード例 #30
0
ファイル: dane_geber.cs プロジェクト: Kuczmil/RE-SE
        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("");
                    }
                }
            }
        }
コード例 #31
0
ファイル: SNMP_Tools.cs プロジェクト: jonathan84clark/JTool
        /// <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;
        }
コード例 #32
0
ファイル: dane_geber.cs プロジェクト: Kuczmil/RE-SE
        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;
        }
コード例 #33
0
ファイル: sv2.aspx.cs プロジェクト: tayeumi/HFC
        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;
                }
        }
コード例 #34
0
ファイル: PrinterObj.cs プロジェクト: jlam916/ServiceDesk
    /// <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;
    }
コード例 #35
0
ファイル: RemoteQuery.cs プロジェクト: odnanref/snrviewer
        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;
        }
コード例 #36
0
ファイル: Check_AC.cs プロジェクト: ravihuang/check_ac
        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);
        }
コード例 #37
-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");
                }
            }
        }