예제 #1
0
        public void Metoda()
        {
            string     host      = "localhost";
            string     community = "public";
            SimpleSnmp snmp      = new SimpleSnmp(host, community);

            if (!snmp.Valid)
            {
                Console.WriteLine("SNMP agent host name/ip address is invalid.");
                return;
            }
            Dictionary <Oid, AsnType> result = snmp.Get(SnmpVersion.Ver1,
                                                        new string[] { ".1.3.6.1.2.1.1.1" });

            if (result == null)
            {
                Console.WriteLine("No results received.");
                return;
            }

            foreach (KeyValuePair <Oid, AsnType> kvp in result)
            {
                Console.WriteLine("{0}: {1} {2}", kvp.Key.ToString(),
                                  SnmpConstants.GetTypeName(kvp.Value.Type),
                                  kvp.Value.ToString());
            }
        }
예제 #2
0
        public void QuerySuccessTest()
        {
            Oid testOid = new Oid("1.3.6.1.2.1.1.1.0");

            // test a (hopefully) successful query to a MikroTik
            // THIS CAN FAIL IF THE DEVICE HOLDING THE address specified by "testAddress"
            // is not available or has no SNMP service running.
            using (var snmpll = new SnmpLowerLayer(TestConstants.TestAddressMikrotik1, QuerierOptions.Default.WithProtocolVersion(SnmpVersion.Ver2)))
            {
                VbCollection result = snmpll.Query(new Oid("1.3.6.1.2.1.1.1.0"));
                Assert.NotNull(result, "The query result is null");
                Assert.GreaterOrEqual(result.Count, 1, "Empty result list when querying 1 OID");

                Assert.NotNull(result[0], "result[0] is null");
                Assert.AreEqual(testOid, result[0].Oid, "result[0] is of wrong OID");

                Console.WriteLine($"Result for OID {result[0].Oid} is of type '{SnmpConstants.GetTypeName(result[0].Value.Type)}' with value '{result[0].Value}'");
            }

            // test a (hopefully) successful query to a Ubiquiti device.
            // THIS CAN FAIL IF THE DEVICE HOLDING THE address specified by "testAddress"
            // is not available or has no SNMP service running.
            using (var snmpll = new SnmpLowerLayer(TestConstants.TestAddressUbntAirOs4side1, QuerierOptions.Default.WithProtocolVersion(SnmpVersion.Ver1)))
            {
                VbCollection result = snmpll.Query(new Oid("1.3.6.1.2.1.1.1.0"));
                Assert.NotNull(result, "The query result is null");
                Assert.GreaterOrEqual(result.Count, 1, "Empty result list when querying 1 OID");

                Assert.NotNull(result[0], "result[0] is null");
                Assert.AreEqual(testOid, result[0].Oid, "result[0] is of wrong OID");

                Console.WriteLine($"Result for OID {result[0].Oid} is of type '{SnmpConstants.GetTypeName(result[0].Value.Type)}' with value '{result[0].Value}'");
            }
        }
예제 #3
0
 protected override void ProcessRecord()
 {
     base.ProcessRecord();
     foreach (string node in _IpAddress)
     {
         _SimpleSnmp.PeerIP = System.Net.IPAddress.Parse(node);
         Dictionary <Oid, AsnType> response = _SimpleSnmp.Get(_Version, _Oid);
         if (response != null)
         {
             foreach (KeyValuePair <Oid, AsnType> item in response)
             {
                 if (!item.Key.ToString().Equals("0.0"))
                 {
                     PSObject obj = new PSObject();
                     //PSNoteProperties are not strongly typed but do contain an explicit type.
                     obj.Properties.Add(new PSNoteProperty("Node", node));
                     obj.Properties.Add(new PSNoteProperty("OID", item.Key.ToString()));
                     obj.Properties.Add(new PSNoteProperty("Type", SnmpConstants.GetTypeName(item.Value.Type)));
                     obj.Properties.Add(new PSNoteProperty("Value", item.Value.ToString()));
                     WriteObject(obj);
                 }
             }
         }
         else
         {
             WriteError(new ErrorRecord(new Exception("OID " + string.Join(", ", _Oid) + " returned Null "), "", ErrorCategory.ProtocolError, null));
         }
     }
 }
예제 #4
0
파일: Form1.cs 프로젝트: zdatou/DotNet_Snmp
        private void Snmp_Get(string ip, string oid, string comm)
        {
            OctetString     community = new OctetString(comm);
            AgentParameters param     = new AgentParameters(community);

            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(oid);
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

            if (result != null)
            {
                if (result.Pdu.ErrorStatus != 0)
                {
                    this.txtTest.Text += string.Format("Error in SNMP reply. Error {0} index {1} \r\n", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                }
                else
                {
                    int index = this.dataGridView1.Rows.Add();
                    this.dataGridView1.Rows[index].Cells[0].Value = "hello";
                    this.dataGridView1.Rows[index].Cells[1].Value = result.Pdu.VbList[0].Oid.ToString();
                    this.dataGridView1.Rows[index].Cells[2].Value = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);
                    this.dataGridView1.Rows[index].Cells[3].Value = result.Pdu.VbList[0].Value.ToString();
                }
            }
        }
예제 #5
0
 protected override void ProcessRecord()
 {
     base.ProcessRecord();
     foreach (string node in _IpAddress)
     {
         IPAddress ip = null;
         if (!System.Net.IPAddress.TryParse(node, out ip))
         {
             ThrowTerminatingError(new ErrorRecord(new Exception("Not a valid ipaddress"), "", ErrorCategory.InvalidData, ""));
         }
         else
         {
             _SimpleSnmp.PeerIP = ip;
         }
         _SimpleSnmp.PeerIP = System.Net.IPAddress.Parse(ip.ToString());
         string LastOid = _Oid;
         while (LastOid != null)
         {
             Dictionary <Oid, AsnType> response = _SimpleSnmp.GetNext(_Version, new string[] { LastOid });
             if (response != null)
             {
                 foreach (KeyValuePair <Oid, AsnType> item in response)
                 {
                     if (!item.Key.ToString().Equals("0.0"))
                     {
                         PSObject obj = new PSObject();
                         obj.Properties.Add(new PSNoteProperty("Node", node));
                         obj.Properties.Add(new PSNoteProperty("OID", item.Key.ToString()));
                         obj.Properties.Add(new PSNoteProperty("Type", SnmpConstants.GetTypeName(item.Value.Type)));
                         obj.Properties.Add(new PSNoteProperty("Value", item.Value.ToString()));
                         if (_Force)
                         {
                             LastOid = item.Key.ToString();
                         }
                         else
                         {
                             if (_RootOID.IsRootOf(item.Key))
                             {
                                 LastOid = item.Key.ToString();
                             }
                             else
                             {
                                 LastOid = null;
                                 break;
                             }
                         }
                         WriteObject(obj);
                     }
                 }
             }
             else
             {
                 Console.WriteLine("OID " + LastOid + " returned Null ");
                 LastOid = null;
             }
         }
     }
 }
예제 #6
0
 private void ReceiveTrap(object sender, SnmpPacket snmpPacket)
 {
     foreach (var vb in snmpPacket.GetValues())
     {
         trapListenerDataGridView.Rows.Add(vb.Oid.ToString(), vb.Value.ToString(),
                                           SnmpConstants.GetTypeName(vb.Value.Type),
                                           DateTime.Now.ToString("G"), snmpPacket.Version);
     }
 }
예제 #7
0
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            OctetString community = new OctetString("public");

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

            // Set SNMP version to 1 (or 2)
            param.Version = SnmpVersion.Ver2;
            // 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");
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            // Pdu class used for all requests
            Pdu    pdu = new Pdu(PduType.Get);
            string oid = whatShouldIAdd("Adding new property to PDU list");

            pdu.VbList.Add(oid);
            SnmpV2Packet result = (SnmpV2Packet)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
                {
                    for (int i = 0; i < pdu.VbList.Count; i++)
                    {
                        resultString = String.Format("(0}) ({1}): {2}",
                                                     result.Pdu.VbList[0].Oid.ToString(),
                                                     SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type).ToString(),
                                                     result.Pdu.VbList[0].Value.ToString());
                        MessageBox.Show(resultString);
                        watchIterations = watchIterations + 1;
                        if (watchIterations > 5)
                        {
                            GeneratorsTimer.Enabled = false;
                        }
                    }
                }
            }

            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }
        }
예제 #8
0
        public override SnmpV2Packet GetRequest(Pdu pdu)
        {
            if (m_target == null)
            {
                Log.Error("SNMP m_target = null.");
                return(null);
            }

            if (pdu == null)
            {
                Log.Error("SNMP请求参数pdu为空");
                return(null);
            }

            // Log msg
            string       logMsg;
            SnmpV2Packet result = null;

            pdu.Type = PduType.Get;
            try
            {
                result = (SnmpV2Packet)m_target.Request(pdu, m_Param);
                if (null != result)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        logMsg = string.Format("Error in SNMP reply. Error {0} index {1}"
                                               , result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                        Log.Error(logMsg);
                    }
                    else
                    {
                        foreach (Vb vb in result.Pdu.VbList)
                        {
                            logMsg = string.Format("ObjectName={0}, Type={1}, Value={2}"
                                                   , vb.Oid.ToString(), SnmpConstants.GetTypeName(vb.Value.Type), vb.Value.ToString());
                            Log.Debug(logMsg);
                        }
                    }
                }
                else
                {
                    Log.Error("No response received from SNMP agent.");
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message.ToString());
                throw e;
            }


            return(result);
        }
예제 #9
0
        public SnmpV1Packet GetNextRequest(string OID)
        {
            this.param.Version = SnmpVersion.Ver1;
            this.pdu           = new Pdu(PduType.GetNext);
            this.pdu.VbList.Add(OID);
            result = (SnmpV1Packet)target.Request(pdu, param);

            OidNumber = result.Pdu.VbList[0].Oid.ToString();
            type      = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);
            value     = result.Pdu.VbList[0].Value.ToString();
            ipPort    = address + ":161";

            return(result);
        }
예제 #10
0
        public SnmpV2Packet GetNextRequest(Oid oid)
        {
            IpAddress agent  = new IpAddress(_agentsIP);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

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

            //Adding new property to PDU list
            pdu.VbList.Add(oid);

            // Make SNMP request
            SnmpV2Packet result = (SnmpV2Packet)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
                    string errorMessage = String.Format("Error in SNMP reply. Error {0} index {1}",
                                                        result.Pdu.ErrorStatus.ToString(),
                                                        result.Pdu.ErrorIndex.ToString());
                    MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK);
                    return(null);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList

                    //DATABASE adding
                    string newOid   = result.Pdu.VbList[0].Oid.ToString();
                    string newValue = result.Pdu.VbList[0].Value.ToString();
                    string newType  = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type).ToString();
                    string newIp    = _agentsIP;
                    _oid = result.Pdu.VbList[0].Oid;
                    AddItemToDatabase(newOid, newValue, newType, newIp);

                    return(result);
                }
            }
            else
            {
                MessageBox.Show("No response received from SNMP agent.", "Error", MessageBoxButtons.OK);
                return(null);
            }
        }
예제 #11
0
        private string LogResult(Dictionary <Oid, AsnType> result)
        {
            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair <Oid, AsnType> kvp in result)
            {
                string s = string.Format("{0}: {1} {2}", kvp.Key.ToString(),
                                         SnmpConstants.GetTypeName(kvp.Value.Type),
                                         kvp.Value.ToString());
                sb.AppendLine(s);
            }
            string strResult = sb.ToString();

            return(strResult);
        }
예제 #12
0
        private void btnGet_Click(object sender, EventArgs e)
        {
            OctetString     community = new OctetString("public");
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;
            IpAddress agent = new IpAddress("127.0.0.1");

            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.1.1.0"); //sysDescr //OID + VALUE
            //pdu.VbList.Add("1.3.6.1.2.1.1.2.0"); //sysObjectID
            //pdu.VbList.Add("1.3.6.1.2.1.1.3.0"); //sysUpTime
            //pdu.VbList.Add("1.3.6.1.2.1.1.4.0"); //sysContact
            //pdu.VbList.Add("1.3.6.1.2.1.1.5.0"); //sysName

            string oid = whatShouldIAdd("Adding new property to PDU list");

            pdu.VbList.Add(oid);

            // Make SNMP request
            SnmpV2Packet result = (SnmpV2Packet)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
                    resultString = String.Format("({0}) ({1}): {2}",
                                                 result.Pdu.VbList[0].Oid.ToString(),
                                                 SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type).ToString(),
                                                 result.Pdu.VbList[0].Value.ToString());
                    MessageBox.Show(resultString);
                }
            }
        }
예제 #13
0
        /// <summary>
        /// Converts the
        /// </summary>
        /// <param name="asnType">The <see cref="AsnType" /> to convert.</param>
        /// <returns>Integer representation of the <see cref="AsnType" />.</returns>
        public static int ToInt(this AsnType asnType)
        {
            if (asnType == null)
            {
                throw new ArgumentNullException(nameof(asnType), "The AsnType to convert to Integer is null");
            }

            int convertedValue;

            if (!int.TryParse(asnType.ToString(), out convertedValue))
            {
                throw new HamnetSnmpException($"Cannot convert an ASN Type '{SnmpConstants.GetTypeName(asnType.Type)}' of value '{asnType.ToString()}' to an integer: Value malformatted or out of range");
            }

            return(convertedValue);
        }
예제 #14
0
        /// <summary>
        /// Converts the
        /// </summary>
        /// <param name="asnType">The <see cref="AsnType" /> to convert.</param>
        /// <param name="converted">Returs the integer representation of the <see cref="AsnType" />.</param>
        /// <returns><c>true</c> if the conversion was successful. Otherwise <c>false</c>.</returns>
        public static bool TryToInt(this AsnType asnType, out int converted)
        {
            if (asnType == null)
            {
                throw new ArgumentNullException(nameof(asnType), "The AsnType to convert to Integer is null");
            }

            converted = int.MinValue;
            if (!int.TryParse(asnType.ToString(), out converted))
            {
                log.Warn($"Cannot convert an ASN Type '{SnmpConstants.GetTypeName(asnType.Type)}' of value '{asnType.ToString()}' to an integer: Value malformatted or out of range");
                return(false);
            }

            return(true);
        }
예제 #15
0
        private string[] readGetResult(Dictionary <Oid, AsnType> result)
        {
            if (result == null)
            {
                return(null);
            }
            var rsltStrings = new string[3];

            foreach (KeyValuePair <Oid, AsnType> kvp in result)
            {
                rsltStrings[0] = kvp.Key.ToString();
                rsltStrings[1] = SnmpConstants.GetTypeName(kvp.Value.Type);
                rsltStrings[2] = kvp.Value.ToString();
            }
            return(rsltStrings);
        }
        public IActionResult Start([FromBody] Setting setting)
        {
            OctetString community = new OctetString(setting.Community);

            AgentParameters param = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;

            IpAddress agent = new IpAddress(setting.AgentAddress);

            UdpTarget target = new UdpTarget((System.Net.IPAddress)agent, 161, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);

            pdu.VbList.Add("1.3.6.1.2.1.1.5.0"); //sysName

            SnmpV2Packet result = (SnmpV2Packet)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
                    return(Json(("Error in SNMP reply. Error {0} index {1}",
                                 result.Pdu.ErrorStatus,
                                 result.Pdu.ErrorIndex)));
                }
                else
                {
                    return(Json(("sysName({0}) ({1}): {2}",
                                 result.Pdu.VbList[4].Oid.ToString(),
                                 SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type),
                                 result.Pdu.VbList[4].Value.ToString())));
                }
            }
            else
            {
                return(Json("No response received from SNMP agent."));
            }
            target.Close();

            return(Json(setting));
        }
예제 #17
0
 private void ShowResult(Dictionary <Oid, AsnType> result, DataGridView target)
 {
     if (result == null)
     {
         ErrorMessageBox.Show("Request failed.");
     }
     else
     {
         foreach (KeyValuePair <Oid, AsnType> entry in result)
         {
             if (entry.Value.ToString().Equals("Null"))
             {
                 ErrorMessageBox.Show("Request failed.");
             }
             else
             {
                 target.Rows.Add(entry.Key.ToString(), entry.Value.ToString(),
                                 SnmpConstants.GetTypeName(entry.Value.Type), DateTime.Now.ToLongTimeString());
             }
         }
     }
 }
예제 #18
0
        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <param name="asnValue">The ASN value.</param>
        /// <param name="targetType">Type of the value.</param>
        /// <returns>.NET value compliant</returns>
        private object GetValue(AsnType asnValue, Type targetType)
        {
            object value = asnValue;

            switch (SnmpConstants.GetTypeName(asnValue.Type))
            {
            case "Integer32":
                value = ((Integer32)value).Value;
                break;

            case "Gauge32":
                value = ((Gauge32)value).Value;
                break;

            case "Counter32":
                value = ((Counter32)value).Value;
                break;

            case "TimeTicks":
                value = TimeSpan.FromMilliseconds(((TimeTicks)value).Milliseconds);
                break;

            case "IPAddress":
                value = IPAddress.Parse(((IpAddress)value).ToString());
                break;

            case "OctetString":
                value = asnValue.ToString();
                if (targetType == typeof(DateTime))
                {
                    value = ParseDateAndTime((string)value);
                }
                break;
            }
            return(value);
        }
예제 #19
0
파일: SNMP.cs 프로젝트: faraanh/miniSNMP
        private void GetDisk()
        {
            OctetString     community = new OctetString(txtConStr.Text);
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver1;
            try
            {
                IpAddress agent  = new IpAddress(txtIPAgent.Text);
                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.1.0");    //sysDescr
                pdu.VbList.Add("1.3.6.1.2.1.1.2.0");    //sysObjectID
                pdu.VbList.Add("1.3.6.1.2.1.1.3.0");    //sysUpTime
                pdu.VbList.Add("1.3.6.1.2.1.1.4.0");    //sysContact
                pdu.VbList.Add("1.3.6.1.2.1.1.5.0");    //sysName
                pdu.VbList.Add("1.3.6.1.2.1.25.1.2.0"); //hrSystemDate
                pdu.VbList.Add("1.3.6.1.2.1.25.1.5.0"); //hrSystemNumUsers
                pdu.VbList.Add("1.3.6.1.2.1.25.1.6.0"); //hrSystemProcesses
                pdu.VbList.Add("1.3.6.1.2.1.25.2.2.0"); //hrMemorySize
                //pdu.VbList.Add("1.3.6.1.2.1.1.5." + n.ToString()); //sysName
                //pdu.VbList.Add("1.3.6.1.2.1.2.1." + n.ToString()); //ifNumbber
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        rtbGuiGet.Text = "Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex;
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        ////////////////////////////////////
                        //rtbAddInfo.Text = "hrSystemDate(" + result.Pdu.VbList[0].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + "):\n\t" + result.Pdu.VbList[0].Value.ToString();
                        //rtbAddInfo.Text += "\n\t-------------------\n\t-------------------\n" + "hrSystemNumUsers(" + result.Pdu.VbList[1].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type) + "): " + result.Pdu.VbList[1].Value.ToString();
                        //rtbAddInfo.Text += "\n\t-------------------\n" + "hrSystemProcesses(" + result.Pdu.VbList[2].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type) + "): " + result.Pdu.VbList[2].Value.ToString();
                        rtbAddInfo.Text += "" + "hrMemorySize(" + result.Pdu.VbList[3].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type) + "): " + result.Pdu.VbList[3].Value.ToString();
                        for (int i = 1; i < 10; i++)
                        {
                            pdu.Reset();
                            pdu.VbList.Add("1.3.6.1.2.1.25.2.3.1.3." + i.ToString());
                            try
                            {
                                result = (SnmpV1Packet)target.Request(pdu, param);
                                if (result.Pdu.VbList[0].Value.ToString() != "Null")
                                {
                                    rtbAddInfo.Text += "\n\t" + "hrStorageDescr." + i.ToString() + "(" + result.Pdu.VbList[0].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + "): " + result.Pdu.VbList[0].Value.ToString();
                                }
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }
                else
                {
                    rtbAddInfo.Text = "No response received from SNMP agent.";
                }
                target.Close();
            }
            catch (Exception ex)
            {
                rtbGuiGet.Text = "Đã xảy ra lỗi: " + ex.Message.ToString();
            }
        }
예제 #20
0
파일: SNMP.cs 프로젝트: faraanh/miniSNMP
        private void GetOne(int n, RichTextBox rtb)
        {
            n++;
            // SNMP community name
            OctetString community = new OctetString(txtConStr.Text);

            // 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
            try
            {
                IpAddress agent = new IpAddress(txtIPAgent.Text);

                // 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.2.2.1.2." + n.ToString()); //ifDescr
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.3." + n.ToString()); //ifType
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.5." + n.ToString()); //ifSpeed
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.6." + n.ToString()); //ifPhysAddress
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.7." + n.ToString()); //ifAdminStatus
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8." + n.ToString()); //ifOperStatus
                // 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

                        rtb.Text = "Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex;
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added to the VbList
                        rtb.Text = "ifDescr(" + result.Pdu.VbList[0].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + "): " + "\n\t" + result.Pdu.VbList[0].Value.ToString();
                        rtb.Text = rtb.Text + "\n" + "ifType(" + result.Pdu.VbList[1].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type) + "): " + "\n\t" + GetType(int.Parse(result.Pdu.VbList[1].Value.ToString()));
                        rtb.Text = rtb.Text + "\n" + "ifSpeed(" + result.Pdu.VbList[2].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type) + "): " + "\n\t" + result.Pdu.VbList[2].Value.ToString();
                        rtb.Text = rtb.Text + "\n" + "ifPhysAddress(" + result.Pdu.VbList[3].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type) + "): " + "\n\t" + result.Pdu.VbList[3].Value.ToString();
                        rtb.Text = rtb.Text + "\n" + "ifAdminStatus(" + result.Pdu.VbList[4].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type) + "): " + "\n\t" + GetStatus(int.Parse(result.Pdu.VbList[4].Value.ToString()));
                        rtb.Text = rtb.Text + "\n" + "ifOperStatus(" + result.Pdu.VbList[5].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[5].Value.Type) + "): " + "\n\t" + GetStatus(int.Parse(result.Pdu.VbList[5].Value.ToString()));
                    }
                }
                else
                {
                    rtb.Text = "No response received from SNMP agent.";
                }
                target.Close();
            }
            catch (Exception ex)
            {
                rtb.Text = "Đã xảy ra lỗi: " + ex.Message.ToString();
            }
        }
예제 #21
0
파일: SNMP.cs 프로젝트: faraanh/miniSNMP
        private void Get(int n)
        {
            OctetString     community = new OctetString(txtConStr.Text);
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver1;
            try
            {
                IpAddress agent  = new IpAddress(txtIPAgent.Text);
                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.1." + n.ToString()); //sysDescr
                pdu.VbList.Add("1.3.6.1.2.1.1.2." + n.ToString()); //sysObjectID
                pdu.VbList.Add("1.3.6.1.2.1.1.3." + n.ToString()); //sysUpTime
                pdu.VbList.Add("1.3.6.1.2.1.1.4." + n.ToString()); //sysContact
                pdu.VbList.Add("1.3.6.1.2.1.1.5." + n.ToString()); //sysName
                pdu.VbList.Add("1.3.6.1.2.1.2.1." + n.ToString()); //ifNumbber
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        rtbGuiGet.Text = "Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex;
                    }
                    else
                    {
                        rtbGuiGet.Text = "sysDescr(" + result.Pdu.VbList[0].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + "): " + result.Pdu.VbList[0].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "sysObjectID(" + result.Pdu.VbList[1].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type) + "): " + result.Pdu.VbList[1].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "sysUpTime(" + result.Pdu.VbList[2].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type) + "): " + result.Pdu.VbList[2].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "sysContact(" + result.Pdu.VbList[3].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type) + "): " + result.Pdu.VbList[3].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "sysName(" + result.Pdu.VbList[4].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type) + "): " + result.Pdu.VbList[4].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "ifNumber(" + result.Pdu.VbList[5].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[5].Value.Type) + "): " + result.Pdu.VbList[5].Value.ToString();
                        GetMore(int.Parse(result.Pdu.VbList[5].Value.ToString()));
                    }
                }
                else
                {
                    rtbGuiGet.Text = "No response received from SNMP agent.";
                }
                target.Close();
            }
            catch (Exception ex)
            {
                rtbGuiGet.Text = "Đã xảy ra lỗi: " + ex.Message.ToString();
            }
        }
예제 #22
0
        public void testWebsiteExample()
        {
            // 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("127.0.0.1");

            // 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.1.1.0"); //sysDescr
            pdu.VbList.Add("1.3.6.1.2.1.1.2.0"); //sysObjectID
            pdu.VbList.Add("1.3.6.1.2.1.1.3.0"); //sysUpTime
            pdu.VbList.Add("1.3.6.1.2.1.1.4.0"); //sysContact
            pdu.VbList.Add("1.3.6.1.2.1.1.5.0"); //sysName

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

            Assert.IsNotNull(result);
            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                      result.Pdu.ErrorStatus,
                                      result.Pdu.ErrorIndex);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    Console.WriteLine("sysDescr({0}) ({1}): {2}",
                                      result.Pdu.VbList[0].Oid.ToString(),
                                      SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                                      result.Pdu.VbList[0].Value.ToString());
                    Console.WriteLine("sysObjectID({0}) ({1}): {2}",
                                      result.Pdu.VbList[1].Oid.ToString(),
                                      SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type),
                                      result.Pdu.VbList[1].Value.ToString());
                    Console.WriteLine("sysUpTime({0}) ({1}): {2}",
                                      result.Pdu.VbList[2].Oid.ToString(),
                                      SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type),
                                      result.Pdu.VbList[2].Value.ToString());
                    Console.WriteLine("sysContact({0}) ({1}): {2}",
                                      result.Pdu.VbList[3].Oid.ToString(),
                                      SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type),
                                      result.Pdu.VbList[3].Value.ToString());
                    Console.WriteLine("sysName({0}) ({1}): {2}",
                                      result.Pdu.VbList[4].Oid.ToString(),
                                      SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type),
                                      result.Pdu.VbList[4].Value.ToString());
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }
            target.Close();
        }
예제 #23
0
        /// <summary>
        /// 将snmp类型的pdu转换为LmtSnmp的pdu
        /// </summary>
        /// <param name="snmpPackage"></param>
        /// <param name="target"></param>
        /// <param name="lmtPdu"></param>
        /// <param name="reason"></param>
        /// <param name="isAsync"></param>
        private bool SnmpPdu2LmtPdu(SnmpV2Packet snmpPackage, UdpTarget target
                                    , CDTLmtbPdu lmtPdu, int reason, bool isAsync)
        {
            string logMsg;

            if (lmtPdu == null)
            {
                Log.Error("参数[lmtPdu]为空");
                return(false);
            }

            // TODO
            // stru_LmtbPduAppendInfo appendInfo;
            logMsg = string.Format("snmpPackage.Pdu.Type = {0}", snmpPackage.Pdu.Type);
            Log.Debug(logMsg);
            logMsg = string.Format("PduType.V2Trap={0}", PduType.V2Trap);
            // TODO
            if (snmpPackage.Pdu.Type != PduType.V2Trap) // Trap
            {
            }
            else
            {
            }

            lmtPdu.Clear();
            lmtPdu.set_LastErrorIndex(snmpPackage.Pdu.ErrorIndex);
            lmtPdu.set_LastErrorStatus(snmpPackage.Pdu.ErrorStatus);
            lmtPdu.SetRequestId(snmpPackage.Pdu.RequestId);

            // ip and port
            IPAddress srcIpAddr = target.Address;
            int       port      = target.Port;

            lmtPdu.set_SourceIp(srcIpAddr.ToString());
            lmtPdu.set_SourcePort(port);

            lmtPdu.set_Reason(reason);
            //lmtPdu.SetPduType(snmpPackage.Pdu.Type);


            // TODO

            /*
             * LMTORINFO* pLmtorInfo = CDTAppStatusInfo::GetInstance()->GetLmtorInfo(csIpAddr);
             * if (pLmtorInfo != NULL && pLmtorInfo->m_isSimpleConnect && pdu.get_type() == sNMP_PDU_TRAP)
             * {
             *  Oid id;
             *  pdu.get_notify_id(id);
             *  CString strTrapOid = id.get_printable();
             *  if (strTrapOid != "1.3.6.1.4.1.5105.100.1.2.2.3.1.1")
             *  {
             *      //如果是简单连接网元的非文件传输结果事件,就不要往上层抛送了
             *      return FALSE;
             *  }
             * }
             */

            //如果是错误的响应,则直接返回
            if (lmtPdu.get_LastErrorStatus() != 0 || reason == -5)
            {
                return(true);
            }

            // 转换vb

            // 对于Trap消息,我们自己额外构造两个Vb,用来装载时间戳和trap Id
            if (snmpPackage.Pdu.Type == PduType.V2Trap) // Trap
            {
                // TODO:
            }

            foreach (Vb vb in snmpPackage.Pdu.VbList)
            {
                logMsg = string.Format("ObjectName={0}, Type={1}, Value={2}"
                                       , vb.Oid.ToString(), SnmpConstants.GetTypeName(vb.Value.Type), vb.Value.ToString());
                Log.Debug(logMsg);

                CDTLmtbVb lmtVb = new CDTLmtbVb();

                lmtVb.set_Oid(vb.Oid.ToString());

                // SnmpConstants.GetSyntaxObject(AsnType.OCTETSTRING);
                // SnmpConstants.GetTypeName(vb.Value.Type);

                // TODO
                // lmtVb.set_Syntax(vb.Value.GetType());

                // TODO:不确定对不对???????
                if (AsnType.OCTETSTRING == vb.Value.Type)
                {
                    /*对于像inetipAddress和DateandTime需要做一下特殊处理,把内存值转换为显示文本*/
                    // CString strNodeType = GetNodeTypeByOIDInCache(csIpAddr, strOID, strMIBPrefix);
                    string strNodeType = "";

                    if ("DateandTime".Equals(strNodeType))
                    {
                    }
                    else if ("inetaddress".Equals(strNodeType))
                    {
                    }
                    else if ("MacAddress".Equals(strNodeType))
                    {
                    }
                    else if ("Unsigned32Array".Equals(strNodeType))
                    {
                    }
                    else if ("Integer32Array".Equals(strNodeType) || "".Equals(strNodeType))
                    {
                    }
                    else if ("MncMccType".Equals(strNodeType))
                    {
                    }
                }

                string value = vb.Value.ToString();

                lmtVb.set_Value(value);

                lmtPdu.AddVb(lmtVb);
            } // end foreach


            //如果得到的LmtbPdu对象里的vb个数为0,说明是是getbulk响应,并且没有任何实例
            //为方便后面统一处理,将错误码设为资源不可得
            if (lmtPdu.VbCount() == 0)
            {
                // TODO: SNMP_ERROR_RESOURCE_UNAVAIL
                lmtPdu.set_LastErrorStatus(13);
                lmtPdu.set_LastErrorIndex(1);
            }


            return(true);
        }
예제 #24
0
        ///<summary>
        ///Actual work in backgroundworker thread
        ///</summary>
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            // Construct a socket and bind it to the trap manager port 10162
            Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep   = new IPEndPoint(IPAddress.Any, 10162);
            EndPoint   ep     = (EndPoint)ipep;

            socket.Bind(ep);
            // Disable timeout processing. Just block until packet is received
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
            bool run = true;
            int  inlen;
            int  ver;

            while (run)
            {
                byte[] indata = new byte[16 * 1024];
                // 16KB receive buffer int inlen = 0;
                IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   inep = (EndPoint)peer;
                try
                {
                    inlen = socket.ReceiveFrom(indata, ref inep);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception {0}", ex.Message);
                    inlen = -1;
                }
                if (inlen > 0)
                {
                    // Check protocol version int
                    ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    if (ver == (int)SnmpVersion.Ver1)
                    {
                        // Parse SNMP Version 1 TRAP packet
                        SnmpV1TrapPacket pkt = new SnmpV1TrapPacket();
                        pkt.decode(indata, inlen);
                        Console.WriteLine("** SNMP Version 1 TRAP received from {0}:", inep.ToString());
                        Console.WriteLine("*** Trap generic: {0}", pkt.Pdu.Generic);
                        Console.WriteLine("*** Trap specific: {0}", pkt.Pdu.Specific);
                        Console.WriteLine("*** Agent address: {0}", pkt.Pdu.AgentAddress.ToString());
                        Console.WriteLine("*** Timestamp: {0}", pkt.Pdu.TimeStamp.ToString());
                        Console.WriteLine("*** VarBind count: {0}", pkt.Pdu.VbList.Count);
                        Console.WriteLine("*** VarBind content:");
                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            Console.WriteLine("**** {0} {1}: {2}", v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString());
                            string   voltage = v.Value.ToString();
                            double   max     = 3.3;
                            string[] values  = voltage.Split('V');
                            _worker.ReportProgress((int)Math.Floor((double)((double.Parse(values[0], CultureInfo.InvariantCulture) / max * 100))));
                            currentVoltage = voltage;
                            double test = double.Parse(values[0]);
                            voltageLine.Points.Add(new DataPoint(double.Parse(pkt.Pdu.TimeStamp.ToString()), double.Parse(values[0], CultureInfo.InvariantCulture)));
                            model.RefreshPlot(true);
                        }
                        Console.WriteLine("** End of SNMP Version 1 TRAP data.");
                    }
                }
                else
                {
                    if (inlen == 0)
                    {
                        Console.WriteLine("Zero length packet received.");
                    }
                }
            }
            Yield(1000000);
        }
예제 #25
0
        public void Start()
        {
            Task.Run(() =>
            {
                this._run = true;

                while (this._run)
                {
                    byte[] indata = new byte[16 * 1024];
                    // 16KB receive buffer int inlen = 0;
                    IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);

                    EndPoint inep = (EndPoint)peer;

                    int inlen = -1;
                    try
                    {
                        inlen = _socket.ReceiveFrom(indata, ref inep);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception {0}", ex.Message);
                        inlen = -1;
                    }
                    if (inlen > 0)
                    {
                        Task.Run(() =>
                        {
                            // Check protocol version int
                            int ver = SnmpPacket.GetProtocolVersion(indata, inlen);

                            // Parse SNMP Version 2 TRAP packet
                            SnmpV2Packet pkt = new SnmpV2Packet();
                            pkt.decode(indata, inlen);
                            Console.WriteLine("** SNMP Version 2 TRAP received from {0}:", inep.ToString());

                            //TrapOID .1.3.6.1.4.1.368.4.1.3.1.3.1.1(TemperatureSensorStatus)

                            //Variable bindings
                            //1.3.6.1.4.1.368.4.1.3.1.3.1.1(TemperatureSensorStatus)->value = 0(NONE), 1(OK), 2(NOK)
                            //1.3.6.1.4.1.368.4.1.3.1.4.1.1(TemperatureSensorValue)->value = [-60, 100]

                            //---------------------- -

                            //TrapOID 1.3.6.1.4.1.368.4.2.0.1(AlarmStatus)

                            //Variable bindings
                            //1.3.6.1.4.1.368.4.2.0.1(AlarmStatus)->value = 0, 1, 2, 3
                            if ((SnmpSharpNet.PduType)pkt.Pdu.Type != PduType.V2Trap)
                            {
                                Console.WriteLine("*** NOT an SNMPv2 trap ****");
                            }
                            else
                            {
                                var valueReceived = pkt.Pdu.VbList.FirstOrDefault(p => p.Oid.ToString().CompareTo(pkt.Pdu.TrapObjectID.ToString()) == 0);
                                RaiseEvent(valueReceived.Oid.ToString().CompareTo(OIDAlarm) == 0 ? "Alarm" : "OperationalStatus", valueReceived.Value.ToString());

                                Console.WriteLine("*** VarBind content:");
                                foreach (Vb v in pkt.Pdu.VbList)
                                {
                                    Console.WriteLine("**** {0} {1}: {2}",
                                                      v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString());
                                }
                                Console.WriteLine("** End of SNMP Version 2 TRAP data.");
                            }
                        });
                    }
                    else
                    {
                        if (inlen == 0)
                        {
                            Console.WriteLine("Zero length packet received.");
                        }
                    }
                }
            });
        }
예제 #26
0
        //GETを取得する
        public void getRequest(Class_InputData input)
        {
            try{
                // コミュニティ名
                OctetString comm = new OctetString(input.community);


                // パラメータクラス
                AgentParameters param = new AgentParameters(comm);
                // バージョン取得
                param.Version = input.versionofSNMPsharp;
                IpAddress agent = new IpAddress(input.hostname);


                // 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(input.oid);
                //バージョン1の時
                if (input.version == "v1" | input.version == "1")
                {
                    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
                        {
                            resultList         = new Dictionary <string, string>();
                            resultList["oid"]  = result.Pdu.VbList[0].Oid.ToString();
                            resultList["type"] = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);

                            //日本語の可能性あり
                            //ifdescの時日本語の可能性あり
                            //1.3.6.1.2.1.2.2.1.2 ifdesc
                            //1.3.6.1.2.1.25.3.2.1.3. hrDeviceDescr
                            if (0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.2") | 0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.25.3.2.1.3"))
                            {
                                resultList["value"] = convertJP(result.Pdu.VbList[0].Value.ToString());
                            }
                            else if (0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.7.") | 0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.8."))
                            {
                                resultList["value"] = Util.convIfStatus(result.Pdu.VbList[0].Oid.ToString());
                            }
                            else
                            {
                                string value = result.Pdu.VbList[0].Value.ToString();

                                //TimeTick型の時はミリ秒も出力する
                                if (resultList["type"] == SnmpConstants.SMI_TIMETICKS_STR)
                                {
                                    TimeTicks timeti = (TimeTicks)result.Pdu.VbList[0].Value;
                                    value = "(" + timeti.Milliseconds.ToString() + "ms)" + result.Pdu.VbList[0].Value.ToString();
                                }

                                resultList["value"] = value;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("SNMP agentからのレスポンスがありません.");
                    }
                }
                // v2以降の時
                else
                {
                    SnmpV2Packet result = (SnmpV2Packet)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
                        {
                            resultList         = new Dictionary <string, string>();
                            resultList["oid"]  = result.Pdu.VbList[0].Oid.ToString();
                            resultList["type"] = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);

                            //日本語の可能性あり
                            //ifdescの時日本語の可能性あり
                            if (0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.2") | 0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.25.3.2.1.3"))
                            {
                                resultList["value"] = convertJP(result.Pdu.VbList[0].Value.ToString());
                            }
                            else if (0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.7.") | 0 <= result.Pdu.VbList[0].Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.8."))
                            {
                                resultList["value"] = Util.convIfStatus(result.Pdu.VbList[0].Oid.ToString());
                            }
                            else
                            {
                                string value = result.Pdu.VbList[0].Value.ToString();

                                //TimeTick型の時はミリ秒も出力する
                                if (resultList["type"] == SnmpConstants.SMI_TIMETICKS_STR)
                                {
                                    TimeTicks timeti = (TimeTicks)result.Pdu.VbList[0].Value;
                                    value = "(" + timeti.Milliseconds.ToString() + "ms)" + result.Pdu.VbList[0].Value.ToString();
                                }
                                resultList["value"] = value;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("SNMP agentからのレスポンスがありません.");
                    }
                }
                target.Close();
            }

            catch (Exception)
            {
                throw;
            }
        }
예제 #27
0
        public JObject Walk()
        {
            JObject output = new JObject();
            JArray  array  = new JArray();

            OctetString     community = new OctetString("public");
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;

            Oid lastOid = (Oid)this.oid.Clone();
            Pdu pdu     = new Pdu(PduType.GetBulk);

            pdu.NonRepeaters = 0;
            while (lastOid != null)
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(lastOid);
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        lastOid = null;
                        throw new SnmpErrorStatusException("Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex, result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            if (this.oid.IsRootOf(v.Oid))
                            {
                                JObject value = new JObject();
                                value.Add("OID", v.Oid.ToString());
                                value.Add("Type", SnmpConstants.GetTypeName(v.Value.Type));
                                value.Add("Value", v.Value.ToString());
                                array.Add(value);

                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid = null;
                                }
                                else
                                {
                                    lastOid = v.Oid;
                                }
                            }
                            else
                            {
                                lastOid = null;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    throw new SnmpNetworkException("No response received from SNMP agent.");
                }
            }

            output.Add("Results", array);

            return(output);
        }
예제 #28
0
        public SNMPResultSet[] Walk(string pOID)
        {
            List <SNMPResultSet> snmpResults = new List <SNMPResultSet>();

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

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

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

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(pOID); // 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))
                            {
                                snmpResults.Add(new SNMPResultSet(v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString()));

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

            return(snmpResults.ToArray());
        }
예제 #29
0
        public SNMPResultSet Get(string pOID)
        {
            SNMPResultSet snmpResult = null;

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

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

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

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

            pdu.VbList.Add(pOID);

            // 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

                    snmpResult = new SNMPResultSet(result.Pdu.VbList[0].Oid.ToString(), SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type), result.Pdu.VbList[0].Value.ToString());
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }
            target.Close();

            return(snmpResult);
        }
예제 #30
0
        private void AcceptTrap()
        {
            if (!isListenTrap)
            {
                return;
            }
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, App.snmpTrapPort);
            EndPoint   ep   = (EndPoint)ipep;

            try
            {
                socket.Bind(ep);
            }
            catch (Exception ex)
            {
                IsListenTrap = false;
                MessageBox.Show(string.Format("打开TRAP监听端口{0}失败\n详细信息:{1}", App.snmpTrapPort, ex.Message));
                return;
            }
            SetTextBlockAsync(tbStatusMessage, string.Format("开始后台接收Trap消息,udp端口{0}", App.snmpTrapPort));
            // Disable timeout processing. Just block until packet is received
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
            IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
            EndPoint   inep = (EndPoint)peer;

            while (isListenTrap)
            {
                // 16KB receive buffer
                byte[] indata = new byte[16 * 1024];
                int    inlen  = 0;
                try
                {
                    inlen = socket.ReceiveFrom(indata, ref inep);//inlen为udp包的负载
                }
                catch (Exception ex)
                {
                    string errorMessage;
                    if (isListenTrap)
                    {
                        errorMessage = string.Format("异常 {0}", ex.Message);
                        SetTextBlockAsync(tbStatusMessage, errorMessage);
                    }
                    else
                    {
                        errorMessage = "后台接收Trap线程被强行终止";
                        SetTextBlockAsync(tbStatusMessage, errorMessage);
                        return;
                    }
                    inlen = -1;
                }
                if (inlen > 0)
                {
                    // Check protocol version
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    //在snmphelper中建立静态函数分别解析V1 V2的trap。。。
                    if (ver == (int)SnmpVersion.Ver1)
                    {
                        // Parse SNMP Version 1 TRAP packet
                        SnmpV1TrapPacket pkt = new SnmpV1TrapPacket();
                        pkt.decode(indata, inlen);
                        Console.WriteLine("** SNMP Version 1 TRAP received from {0}:", inep.ToString());
                        Console.WriteLine("*** Trap generic: {0}", pkt.Pdu.Generic);
                        Console.WriteLine("*** Trap specific: {0}", pkt.Pdu.Specific);
                        Console.WriteLine("*** Agent address: {0}", pkt.Pdu.AgentAddress.ToString());
                        Console.WriteLine("*** Timestamp: {0}", pkt.Pdu.TimeStamp.ToString());
                        Console.WriteLine("*** VarBind count: {0}", pkt.Pdu.VbList.Count);
                        Console.WriteLine("*** VarBind content:");
                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            Console.WriteLine("**** {0} {1}: {2}", v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString());
                        }
                        Console.WriteLine("** End of SNMP Version 1 TRAP data.");
                    }
                    else
                    {
                        // Parse SNMP Version 2 TRAP packet
                        SnmpV2Packet pkt = new SnmpV2Packet();
                        pkt.decode(indata, inlen);
                        Console.WriteLine("** SNMP Version 2 TRAP received from {0}:", inep.ToString());
                        if (pkt.Pdu.Type != PduType.V2Trap)
                        {
                            Console.WriteLine("*** NOT an SNMPv2 trap ****");
                        }
                        else
                        {
                            Console.WriteLine("*** Community: {0}", pkt.Community.ToString());
                            Console.WriteLine("*** VarBind count: {0}", pkt.Pdu.VbList.Count);
                            Console.WriteLine("*** VarBind content:");
                            foreach (Vb v in pkt.Pdu.VbList)
                            {
                                Console.WriteLine("**** {0} {1}: {2}",
                                                  v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString());
                            }
                            Console.WriteLine("** End of SNMP Version 2 TRAP data.");
                        }
                    }
                }
                else
                {
                    if (inlen == 0)
                    {
                        Console.WriteLine("Zero length packet received.");
                    }
                }
            }
            SetTextBlockAsync(tbStatusMessage, "后台接收Trap线程结束");
        }