상속: OctetString, IComparable, ICloneable
예제 #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
0
        public string get(string ip, string oid)
        {
            Pdu pdu = new Pdu(PduType.Get);
            pdu.VbList.Add(oid);
            OctetString community = new OctetString("public");
            AgentParameters param = new AgentParameters(community);
            param.Version = SnmpVersion.Ver1;
            {
                IpAddress agent = new IpAddress(ip);
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {

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

                else
                {
                    return string.Format("No response received from SNMP agent. \r\n");
                }
                target.Dispose();
            }
        }
예제 #3
0
 /// <summary>
 /// Constructor
 /// </summary>
 public CTarget()
 {
     _address = new IpAddress(System.Net.IPAddress.Loopback);
     _port = 161;
     _version = SnmpVersion.Ver2;
     _timeout = 2000;
     _retry = 1;
     _community = "public";
 }
예제 #4
0
        /// <summary>Constructor</summary>
        public TrapPdu()
        {
            _asnType = (byte)PduType.Trap;
            _enterprise = new Oid();
            _agentAddr = new IpAddress();
            _generic = new Integer32();
            _specific = new Integer32();
            _timeStamp = new TimeTicks();

            _variables = new VbCollection();
        }
예제 #5
0
 private SnmpV2Packet GetSNMP()
 {
     IpAddress agent = new IpAddress(textBox3.Text);
     String myOID = textBox1.Text;
     // Define agent parameters class
     AgentParameters param = new AgentParameters(community);
     // Set SNMP version to 2
     param.Version = SnmpVersion.Ver2;
     // Construct target
     UdpTarget target = new UdpTarget((System.Net.IPAddress)agent, 161, 2000, 1);
     // Pdu class used for all requests
     Pdu pdu = new Pdu(PduType.Get);
     pdu.VbList.Add(myOID); //sysDescr
     // Make SNMP request
     SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
     return result;
 }
예제 #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
        /// <summary>Used to create correct variable type object for the specified encoded type</summary>
        /// <param name="asnType">ASN.1 type code</param>
        /// <returns>A new object matching type supplied or null if type was not recognized.</returns>
        public static AsnType GetSyntaxObject(SMIDataTypeCode asnType)
        {
            AsnType obj = null;
            if (asnType == SMIDataTypeCode.Integer)
                obj = new Integer32 ();
            else if (asnType == SMIDataTypeCode.Counter32)
                obj = new Counter32 ();
            else if (asnType == SMIDataTypeCode.Gauge32)
                obj = new Gauge32 ();
            else if (asnType == SMIDataTypeCode.Counter64)
                obj = new Counter64 ();
            else if (asnType == SMIDataTypeCode.TimeTicks)
                obj = new TimeTicks ();
            else if (asnType == SMIDataTypeCode.OctetString)
                obj = new OctetString ();
            else if (asnType == SMIDataTypeCode.Opaque)
                obj = new Opaque ();
            else if (asnType == SMIDataTypeCode.IPAddress)
                obj = new IpAddress ();
            else if (asnType == SMIDataTypeCode.ObjectId)
                obj = new Oid ();
            else if (asnType == SMIDataTypeCode.PartyClock)
                obj = new V2PartyClock ();
            else if (asnType == SMIDataTypeCode.NoSuchInstance)
                obj = new NoSuchInstance ();
            else if (asnType == SMIDataTypeCode.NoSuchObject)
                obj = new NoSuchObject ();
            else if (asnType == SMIDataTypeCode.EndOfMibView)
                obj = new EndOfMibView ();
            else if (asnType == SMIDataTypeCode.Null)
            {
                obj = new Null ();
            }

            return obj;
        }
예제 #8
0
        /// <summary>
        /// Return SNMP type object of the type specified by name. Supported variable types are:
        /// <see cref="Integer32"/>, <see cref="Counter32"/>, <see cref="Gauge32"/>, <see cref="Counter64"/>,
        /// <see cref="TimeTicks"/>, <see cref="OctetString"/>, <see cref="IpAddress"/>, <see cref="Oid"/>, and
        /// <see cref="Null"/>.
        /// 
        /// Type names are the same as support class names compared without case sensitivity (e.g. Integer == INTEGER).
        /// </summary>
        /// <param name="name">Name of the object type (not case sensitive)</param>
        /// <returns>New <see cref="AsnType"/> object.</returns>
        public static AsnType GetSyntaxObject(string name)
        {
            AsnType obj = null;
            if (name.ToUpper ().Equals ("INTEGER32") || name.ToUpper ().Equals ("INTEGER"))
                obj = new Integer32 ();
            else if (name.ToUpper ().Equals ("COUNTER32"))
                obj = new Counter32 ();
            else if (name.ToUpper ().Equals ("GAUGE32"))
                obj = new Gauge32 ();
            else if (name.ToUpper ().Equals ("COUNTER64"))
                obj = new Counter64 ();
            else if (name.ToUpper ().Equals ("TIMETICKS"))
                obj = new TimeTicks ();
            else if (name.ToUpper ().Equals ("OCTETSTRING"))
                obj = new OctetString ();
            else if (name.ToUpper ().Equals ("IPADDRESS"))
                obj = new IpAddress ();
            else if (name.ToUpper ().Equals ("OID"))
                obj = new Oid ();
            else if (name.ToUpper ().Equals ("NULL"))
                obj = new Null ();
            else
                throw new ArgumentException ("Invalid value type name");

            return obj;
        }
예제 #9
0
 /// <summary>
 /// Send SNMP version 1 Trap notification
 /// </summary>
 /// <param name="packet">SNMP v1 Trap packet class</param>
 /// <param name="peer">Manager (receiver) IP address</param>
 /// <param name="port">Manager (receiver) UDP port number</param>
 public void SendV1Trap(SnmpV1TrapPacket packet, IpAddress peer, int port)
 {
     byte[] outBuffer = packet.encode();
     _sock.SendTo(outBuffer, new IPEndPoint((IPAddress)peer, port));
 }
예제 #10
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";
                }
        }
예제 #11
0
        /// <summary>
        /// Reset the class. Initialize all member values to class defaults.
        /// </summary>
        public void Reset()
        {
            _address = new IpAddress(System.Net.IPAddress.Loopback);
            _port = 161;
            _version = SnmpVersion.Ver3;
            _timeout = 2000;
            _retry = 1;

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

            _engineTimeStamp = DateTime.MinValue;

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

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

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

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

            _reportable = true;
        }
예제 #12
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("");
         }
     }
 }
예제 #13
0
        static List <BulkResult> GatherBulk(string oid, string host, string communityString)
        {
            var returnValue = new List <BulkResult>();

            // SNMP community name
            OctetString community = new OctetString(communityString);

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

            // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
            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(host);

            // 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(oid);

            // 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))
                            {
                                //returnValue.Add(v.Value.ToString());
                                returnValue.Add(new BulkResult(v.Oid.ToString(), v.Value.ToString()));
                                //Console.WriteLine("{0} ({1}): {2}",
                                //    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(returnValue);
        }
예제 #14
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;
        }
예제 #15
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;
        }
예제 #16
0
        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();
        }
예제 #17
0
 /// <summary>
 /// Send SNMP Trap notification
 /// </summary>
 /// <remarks>
 /// Helper function to allow for seamless sending of SNMP notifications for all protocol versions.
 /// 
 /// packet parameter should be appropriately formatted SNMP notification in SnmpV1TrapPacket,
 /// SnmpV2Packet or SnmpV3Packet class cast as SnmpPacket class.
 /// 
 /// Function will determine which version of the notification is to be used by checking the type
 /// of the packet parameter and call appropriate TrapAgent member function to send it.
 /// </remarks>
 /// <param name="packet">SNMP trap packet</param>
 /// <param name="peer">Manager (receiver) IP address</param>
 /// <param name="port">Manager (receiver) UDP port number</param>
 public static void SendTrap(SnmpPacket packet, IpAddress peer, int port)
 {
     TrapAgent agent = new TrapAgent();
     if (packet is SnmpV1TrapPacket)
         agent.SendV1Trap((SnmpV1TrapPacket)packet, peer, port);
     else if (packet is SnmpV2Packet)
         agent.SendV2Trap((SnmpV2Packet)packet, peer, port);
     else if (packet is SnmpV3Packet)
         agent.SendV3Trap((SnmpV3Packet)packet, peer, port);
     else
         throw new SnmpException("Invalid SNMP packet type.");
 }
예제 #18
0
        /// <summary>
        /// Construct and send SNMP v3 authPriv Trap
        /// </summary>
        /// <param name="receiver">Trap receiver IP address</param>
        /// <param name="receiverPort">Trap receiver UDP port number</param>
        /// <param name="engineId">Sender SNMP engineId</param>
        /// <param name="senderEngineBoots">Sender SNMP engine boots</param>
        /// <param name="senderEngineTime">Sender SNMP engine time</param>
        /// <param name="senderUserName">Security (user) name</param>
        /// <param name="senderUpTime">Sender upTime</param>
        /// <param name="trapObjectID">Trap object ID</param>
        /// <param name="varList">Variable binding list</param>
        /// <param name="authDigest">Authentication digest. See <see cref="AuthenticationDigests"/> enumeration for
        /// available digests</param>
        /// <param name="authSecret">Authentication secret</param>
        /// <param name="privProtocol">Privacy protocol. See <see cref="PrivacyProtocols"/> enumeration for
        /// available privacy protocols.</param>
        /// <param name="privSecret">Privacy secret</param>
        public void SendV3Trap(IpAddress receiver, int receiverPort, byte[] engineId, Int32 senderEngineBoots,
			Int32 senderEngineTime, string senderUserName, UInt32 senderUpTime, Oid trapObjectID, VbCollection varList,
			AuthenticationDigests authDigest, byte[] authSecret, PrivacyProtocols privProtocol, byte[] privSecret)
        {
            SnmpV3Packet packet = new SnmpV3Packet();
            packet.Pdu.Type = PduType.V2Trap;
            packet.authPriv(ASCIIEncoding.UTF8.GetBytes(senderUserName), authSecret, authDigest,privSecret, privProtocol);
            packet.SetEngineId(engineId);
            packet.SetEngineTime(senderEngineBoots, senderEngineTime);
            packet.ScopedPdu.TrapObjectID.Set(trapObjectID);
            packet.ScopedPdu.TrapSysUpTime.Value = senderUpTime;
            packet.ScopedPdu.VbList.Add(varList);
            packet.MsgFlags.Reportable = false;
            SendV3Trap(packet, receiver, receiverPort);
        }
예제 #19
0
        /// <summary>
        /// Construct and send SNMP v3 noAuthNoPriv Trap
        /// </summary>
        /// <param name="receiver">Trap receiver IP address</param>
        /// <param name="receiverPort">Trap receiver UDP port number</param>
        /// <param name="engineId">Sender SNMP engineId</param>
        /// <param name="senderEngineBoots">Sender SNMP engine boots</param>
        /// <param name="senderEngineTime">Sender SNMP engine time</param>
        /// <param name="senderUserName">Security (user) name</param>
        /// <param name="senderUpTime">Sender upTime</param>
        /// <param name="trapObjectID">Trap object ID</param>
        /// <param name="varList">Variable binding list</param>
        public void SendV3Trap(IpAddress receiver, int receiverPort, byte[] engineId, Int32 senderEngineBoots,
			Int32 senderEngineTime, string senderUserName, UInt32 senderUpTime, Oid trapObjectID, VbCollection varList)
        {
            SnmpV3Packet packet = new SnmpV3Packet();
            packet.Pdu.Type = PduType.V2Trap;
            packet.NoAuthNoPriv(ASCIIEncoding.UTF8.GetBytes(senderUserName));
            packet.SetEngineId(engineId);
            packet.SetEngineTime(senderEngineBoots, senderEngineTime);
            packet.ScopedPdu.TrapObjectID.Set(trapObjectID);
            packet.ScopedPdu.TrapSysUpTime.Value = senderUpTime;
            packet.ScopedPdu.VbList.Add(varList);
            packet.MsgFlags.Reportable = false;
            SendV3Trap(packet, receiver, receiverPort);
        }
예제 #20
0
 /// <summary>
 /// WALk方法
 /// </summary>
 /// <param name="Ip_OID">ip-oid</param>
 /// <param name="outinfo">输出到那个字典</param>
 public void SnmpWalk(Dictionary<string, List<string>> Ip_OID, Dictionary<string, Dictionary<string, string>> outinfo)
 {
     foreach (string address in Ip_OID.Keys)
     {
         Dictionary<string, string> Info = new Dictionary<string, string>();
         try
         {
             {
                 Pdu pdu = new Pdu(PduType.Get);
                 foreach (string a in Ip_OID[address])
                 {
                     pdu.VbList.Add(a);
                 }
                 OctetString community = new OctetString("public");
                 AgentParameters param = new AgentParameters(community);
                 param.Version = SnmpVersion.Ver2;
                 IpAddress agent = new IpAddress(address);
                 UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                 SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                 if (result != null)
                 {
                     if (result.Pdu.ErrorStatus != 0)
                     {
                         Console.WriteLine("Error in SNMP reply. Error {0} index {1} \r\n",
                         result.Pdu.ErrorStatus,
                         result.Pdu.ErrorIndex);
                     }
                     else
                     {
                         for (int i = 0; i < pdu.VbCount; i++)
                         {
                             Info.Add(result.Pdu.VbList[i].Oid.ToString(), result.Pdu.VbList[i].Value.ToString());
                         }
                         if (outinfo.ContainsKey(address) == false)
                         {
                             outinfo.Add(address, Info);
                         }
                         else
                         {
                             outinfo[address] = Info;
                         }
                     }
                 }
                 else
                 {
                     Console.WriteLine("No response received from SNMP agent. \r\n");
                     msg.SaveTempMessage("", DateTime.Now.ToString(), "No response received from SNMP agent. \r\n");
                 }
                 target.Dispose();
             }
         }
         catch (Exception ex)
         {
             msg.SaveTempMessage(ex.Source.ToString(), ex.Message.ToString(), DateTime.Now.ToString());
         }
     }
 }
예제 #21
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;
        }
예제 #22
0
        public void GetInfoOID(DataTable dtInterfaceGauge,out DataTable dt)
        {
            dt = dtInterfaceGauge.Copy();
            if (dtInterfaceGauge.Rows.Count > 0)
            {
                // SNMP community name
                OctetString community = new OctetString(_community);

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

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

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

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

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

                        for (int i = 0; i < dtInterfaceGauge.Rows.Count; i++)
                        {
                            dtInterfaceGauge.Rows[i]["InBandwidth"] = result.Pdu.VbList[i+i].Value.ToString();
                            dtInterfaceGauge.Rows[i]["OutBandwidth"] = result.Pdu.VbList[i+i+1].Value.ToString();
                        }
                        dt = dtInterfaceGauge;
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
                target.Close();
            }
        }
예제 #23
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("");
                    }
                }
            }
        }
예제 #24
0
        private void button11_Click(object sender, EventArgs e)
        {
            //SnmpTest snt = new SnmpTest(tbAddress.Text, "public", ".1.3.6.1.4.1.38446");
            //string[] t=  {".1.3.6.1.4.1.38446"};
            //snt.Test();

            


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

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

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

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











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

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

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

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

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

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by 
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                            result.Pdu.ErrorStatus,
                            result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                Console.WriteLine("{0} ({1}): {2}",
                                    v.Oid.ToString(),
                                    SnmpConstants.GetTypeName(v.Value.Type),
                                    v.Value.ToString());
                                lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Dispose();
        }
예제 #25
0
        /// <summary>Used to create correct variable type object for the specified encoded type</summary>
        /// <param name="asnType">ASN.1 type code</param>
        /// <returns>A new object matching type supplied or null if type was not recognized.</returns>
        public static AsnType GetSyntaxObject(SMIDataTypeCode asnType)
        {
            AsnType obj = null;

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

            return(obj);
        }
예제 #26
0
        public void init()
        {
            Console.Write("please input agent ip[" + ip + "]:");
            String tmp = Console.ReadLine();
            if (tmp.StartsWith("debug"))
            {
                for (int i = 0; i < oids.Length; i++)
                {
                    Console.WriteLine(oids[i][0]);
                }
                Console.Write("please input agent ip[" + ip + "]:");
                tmp = Console.ReadLine();
            }
            ip = tmp.Length > 0 ? tmp.Trim() : ip;

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

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

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

            OctetString community = new OctetString(rc);
            param = new AgentParameters(community);
            param.Version = SnmpVersion.Ver2;
            IpAddress agent = new IpAddress(ip);
            target = new UdpTarget((IPAddress)agent, int.Parse(port), 10000, 2);
        }
예제 #27
0
        /// <summary>Used to create correct variable type object for the specified encoded type</summary>
        /// <param name="asnType">ASN.1 type code</param>
        /// <returns>A new object matching type supplied or null if type was not recognized.</returns>
        public static AsnType GetSyntaxObject(byte asnType)
        {
            AsnType obj = null;
            if (asnType == SnmpConstants.SMI_INTEGER)
                obj = new Integer32();
            else if (asnType == SnmpConstants.SMI_COUNTER32)
                obj = new Counter32();
            else if (asnType == SnmpConstants.SMI_GAUGE32)
                obj = new Gauge32();
            else if (asnType == SnmpConstants.SMI_COUNTER64)
                obj = new Counter64();
            else if (asnType == SnmpConstants.SMI_TIMETICKS)
                obj = new TimeTicks();
            else if (asnType == SnmpConstants.SMI_STRING)
                obj = new OctetString();
            else if (asnType == SnmpConstants.SMI_OPAQUE)
                obj = new Opaque();
            else if (asnType == SnmpConstants.SMI_IPADDRESS)
                obj = new IpAddress();
            else if (asnType == SnmpConstants.SMI_OBJECTID)
                obj = new Oid();
            else if (asnType == SnmpConstants.SMI_PARTY_CLOCK)
                obj = new V2PartyClock();
            else if (asnType == SnmpConstants.SMI_NOSUCHINSTANCE)
                obj = new NoSuchInstance();
            else if (asnType == SnmpConstants.SMI_NOSUCHOBJECT)
                obj = new NoSuchObject();
            else if (asnType == SnmpConstants.SMI_ENDOFMIBVIEW)
                obj = new EndOfMibView();
            else if (asnType == SnmpConstants.SMI_NULL)
            {
                obj = new Null();
            }

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

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

            return(obj);
        }
예제 #30
0
        public Dictionary<string, string> Query(String oid, string Type)
        {
            Dictionary<string, string> Res = new Dictionary<string, string>();
            // SNMP community name
            OctetString community = new OctetString(Community);

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

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

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

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

            target.Close();
            return Res;
        }
예제 #31
0
    /// <summary>
    /// Will get the rest of the variables, parts and percentages
    /// </summary>
    private Dictionary<String, String> getData()
    {
        Dictionary<String, String> dictionary = new Dictionary<String, String>();
        OctetString community = new OctetString( "public" );
        AgentParameters param = new AgentParameters( community );
        param.Version = SnmpVersion.Ver1;
        IpAddress agent = new IpAddress( printerName );

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

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

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

        return dictionary;
    }
예제 #32
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;
                }
        }
예제 #33
0
    /// <summary>
    /// Gets the model of the printer requested
    /// </summary>
    private void getModel()
    {
        // SNMP community name
        OctetString community = new OctetString( "public" );

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

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

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

        // Make SNMP request
        SnmpV1Packet result = null;
        try
        {
            result = (SnmpV1Packet)target.Request( pdu, param );
        }
        catch
        {
        }
        // If result is null then agent didn't reply or we couldn't parse the reply.
        if ( result != null )
        {
            // ErrorStatus other then 0 is an error returned by
            // the Agent - see SnmpConstants for error definitions
            if ( result.Pdu.ErrorStatus != 0 )
            {
                // agent reported an error with the request
                Console.WriteLine( "Error in SNMP reply. Error {0} index {1}",
                    result.Pdu.ErrorStatus,
                    result.Pdu.ErrorIndex );
            }
            else
            {
                // Reply variables are returned in the same order as they were added
                //  to the VbList
                printerModel = result.Pdu.VbList[0].Value.ToString();
            }
        }
        else
        {
            Console.WriteLine( "No response received from SNMP agent." );
        }
        target.Close();
    }
예제 #34
0
        /// <summary>
        /// Return SNMP type object of the type specified by name. Supported variable types are:
        /// * <see cref="Integer32"/>
        /// * <see cref="Counter32"/>
        /// * <see cref="Gauge32"/>
        /// * <see cref="Counter64"/>
        /// * <see cref="TimeTicks"/>
        /// * <see cref="OctetString"/>
        /// * <see cref="IpAddress"/>
        /// * <see cref="Oid"/>
        /// * <see cref="Null"/>
        /// </summary>
        /// <param name="name">Name of the object type</param>
        /// <returns>New <see cref="AsnType"/> object.</returns>
        public static AsnType GetSyntaxObject(string name)
        {
            AsnType obj = null;
            if (name == "Integer32")
                obj = new Integer32();
            else if (name == "Counter32")
                obj = new Counter32();
            else if (name == "Gauge32")
                obj = new Gauge32();
            else if (name == "Counter64")
                obj = new Counter64();
            else if (name == "TimeTicks")
                obj = new TimeTicks();
            else if (name == "OctetString")
                obj = new OctetString();
            else if (name == "IpAddress")
                obj = new IpAddress();
            else if (name == "Oid")
                obj = new Oid();
            else if (name == "Null")
                obj = new Null();
            else
                throw new ArgumentException("Invalid value type name");

            return obj;
        }
예제 #35
0
        /// <summary>
        /// Compare value against IPAddress, byte array, UInt32, IpAddress of OctetString class value.
        /// </summary>
        /// <param name="obj">Type: <see cref="System.Net.IPAddress"/> or byte <see cref="Array"/> or <see cref="UInt32"/> or <see cref="IpAddress"/> or <see cref="OctetString"/></param>
        /// <returns>0 if class values are the same, -1 if current class value is less then or 1 if greater then the class value
        /// we are comparing against.</returns>
        public int CompareTo(object obj)
        {
            byte[] b = null;
            if (obj == null)
            {
                return(-1);
            }

            if (obj is IPAddress)
            {
                IPAddress ipa = (IPAddress)obj;
                b = ipa.GetAddressBytes();
            }
            else if (obj is byte[])
            {
                b = (byte[])obj;
            }
            else if (obj is UInt32)
            {
                IpAddress ipa = new IpAddress((UInt32)obj);
                b = ipa.ToArray();
            }
            else if (obj is IpAddress)
            {
                b = ((IpAddress)obj).ToArray();
            }
            else if (obj is OctetString)
            {
                b = ((OctetString)obj).ToArray();
            }
            if (_data == null)
            {
                return(-1);
            }

            if (b.Length != _data.Length)
            {
                if (_data.Length < b.Length)
                {
                    return(-1);
                }
                else
                {
                    return(1);
                }
            }
            else
            {
                for (int i = 0; i < _data.Length; i++)
                {
                    if (_data[i] < b[i])
                    {
                        return(-1);
                    }
                    else if (_data[i] > b[i])
                    {
                        return(1);
                    }
                }
                return(0);
            }
        }