Ejemplo n.º 1
0
        /// <summary>
        /// Converts the given byte array to an OID.<br/>
        /// Optionally, the constructed OID will be appended at the end of the <paramref name="rootOid" />.paramref name="rootOid"<br/>
        /// For example: byte[] { 0xb8, 0x27, 0xeb, 0x97, 0xb6, 0x39 } will convert to "184.39.235.151.182.57".
        /// </summary>
        /// <param name="bytes">The byte array to convert.</param>
        /// <param name="rootOid">The root OID to append the converted byte array to.</param>
        /// <returns>A byte array with the hex values of the string.</returns>
        public static Oid ToDottedDecimalOid(this byte[] bytes, Oid rootOid = null)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes), "The bytes array to convert is null");
            }

            Oid returnOid = (Oid)rootOid?.Clone() ?? new Oid();

            returnOid.Add(bytes.ToDottedDecimalString());

            return(returnOid);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Executa uma requisição do tipo Set
        /// </summary>
        /// <param name="setValue">Valor a set definido</param>
        public void Send(AsnType setValue)
        {
            using (var target = new UdpTarget(Host.IP, Host.Port, TimeOut, Retries))
            {
                var agentp = new AgentParameters(SnmpVersion.Ver2, new OctetString(Host.Community));

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

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

                // Adiciona dados da requisição
                switch (RequestData.Type)
                {
                case PduType.Get:
                    RequestData.VbList.Add(oid);
                    break;

                case PduType.Set:
                    RequestData.VbList.Add(oid, setValue);
                    break;

                default:
                    throw new InvalidOperationException("unsupported");
                }
                try
                {
                    if (LogRequests)
                    {
                        Logger.Self.Log(this);
                    }
                    Timestamp = DateTime.Now;

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

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

                        ResponseValue = item.Value;
                        if (LogRequests)
                        {
                            Logger.Self.Log(item);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (LogRequests)
                    {
                        Logger.Self.Log(ex);
                    }
                    throw new SnmpException("Não foi possível realizar a operação");
                }
            }
        }
Ejemplo n.º 3
0
        public Tabela pobierzTabele()
        {
            /*! 
		     *Pobiera tabele SNMP.
             */
            Tabela tabela1 = new Tabela();
            AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(community));
            IpAddress peer = new IpAddress(host);
            if (!peer.Valid)
            {
                Console.WriteLine("Zły adres.");
                //return false;
            }
            UdpTarget target = new UdpTarget((IPAddress)peer);
            Oid startOid = new Oid("1.3.6.1.2.1.6.13");
            startOid.Add(1);
            Pdu bulkPdu = Pdu.GetBulkPdu();
            bulkPdu.VbList.Add(startOid);
            bulkPdu.NonRepeaters = 0;
            bulkPdu.MaxRepetitions = 100;
            Oid curOid = (Oid)startOid.Clone();
            while (startOid.IsRootOf(curOid))
            {
                SnmpPacket res = null;
                try
                {
                    res = target.Request(bulkPdu, param);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Zapytanie nieudane {0}", ex.Message);
                    target.Close();
                    //return false;
                }
                if (res.Version != SnmpVersion.Ver2)
                {
                    Console.WriteLine("Otrzymano inną wersję SNMP w odpowiedzi.");
                    target.Close();
                    //return false;
                }
                if (res.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine("SNMP agent zwrócił błąd {0} dla zapytania {1}", res.Pdu.ErrorStatus, res.Pdu.ErrorIndex);
                    target.Close();
                    //return false;
                }
                foreach (Vb v in res.Pdu.VbList)
                {
                    curOid = (Oid)v.Oid.Clone();
                    if (startOid.IsRootOf(v.Oid))
                    {
                        uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid);
                        uint[] instance = new uint[childOids.Length - 1];
                        Array.Copy(childOids, 1, instance, 0, childOids.Length - 1);
                        String strInst = InstanceToString(instance);
                        uint column = childOids[0];
                        if (!tabelaKolumn.Contains(column))
                            tabelaKolumn.Add(column);
                        if (slownikRezultatu.ContainsKey(strInst))
                        {
                            slownikRezultatu[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else {
                            slownikRezultatu[strInst] = new Dictionary<uint, AsnType>();
                            slownikRezultatu[strInst][column] = (AsnType)v.Value.Clone();
                        }
                    }
                    else {
                        break;
                    }
                }
                if (startOid.IsRootOf(curOid))
                {
                    bulkPdu.VbList.Clear();
                    bulkPdu.VbList.Add(curOid);
                    bulkPdu.NonRepeaters = 0;
                    bulkPdu.MaxRepetitions = 100;
                }
            }
            target.Close();

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

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

                        i++;
                    }
                }
            }

            /*/BUDOWA DRZEWA
            foreach (KeyValuePair<string,Dictionary<uint,AsnType>> kvp in slownikRezultatu)
            {
                tabela1.tcpAddress.Add(kvp.Key);
                tabela1.tcpConnLocalAddress.Add(kvp.Value[0].ToString());
                tabela1.tcpConnLocalPort.Add(kvp.Value[1].ToString());
                tabela1.tcpConnRemAddress.Add(kvp.Value[2].ToString());
                tabela1.tcpConnRemPort.Add(kvp.Value[3].ToString());
                tabela1.tcpConnState.Add(kvp.Value[4].ToString());
            }*/
            return tabela1;
        }
Ejemplo n.º 4
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("");
         }
     }
 }
Ejemplo n.º 5
0
        public void GetTable(string OID)
        {
            this.param.Version = SnmpVersion.Ver2;
            Oid startOid = new Oid(OID);

            startOid.Add(1);
            Console.WriteLine(startOid);
            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("Request failed: {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 returned error {0} for request Vb index {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 (!tableColumns.Contains(column))
                        {
                            tableColumns.Add(column);
                        }
                        if (results.ContainsKey(strInst))
                        {
                            results[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else
                        {
                            results[strInst]         = new Dictionary <uint, AsnType>();
                            results[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;
                }
            }
        }
Ejemplo n.º 6
0
        public void pobierzTabeleDoUsuniecia()
        {
            /*! 
		     *Pobiera tabele SNMP.
             */
            Dictionary<String, Dictionary<uint, AsnType>> tabela_rezultat = new Dictionary<string, Dictionary<uint, AsnType>>();
            List<uint> tabeleKolumy = new List<uint>();
            AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(community));
            IpAddress peer = new IpAddress(host);
            if (!peer.Valid)
            {
                Console.WriteLine("Zły adres.");
                return;
            }

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

            //przygotowanie zapytania
            Pdu bulkPdu = Pdu.GetBulkPdu();
            bulkPdu.VbList.Add(startOid);
            bulkPdu.NonRepeaters = 0;
            bulkPdu.MaxRepetitions = 100;
            Oid curOid = (Oid)startOid.Clone();
            while (startOid.IsRootOf(curOid))
            {
                SnmpPacket res = null;
                try
                {
                    res = target.Request(bulkPdu, param);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Zapytanie nieudane {0}", ex.Message);
                    target.Close();
                    return;
                }
                if (res.Version != SnmpVersion.Ver2)
                {
                    Console.WriteLine("Received wrong SNMP version response packet.");
                    target.Close();
                    return;
                }
                if (res.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine("SNMP agent zwrócił błąd {0} dla zapytania {1}", res.Pdu.ErrorStatus, res.Pdu.ErrorIndex);
                    target.Close();
                    return;
                }
                foreach (Vb v in res.Pdu.VbList)
                {
                    curOid = (Oid)v.Oid.Clone();
                    if (startOid.IsRootOf(v.Oid))
                    {
                        uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid);
                        uint[] instance = new uint[childOids.Length - 1];
                        Array.Copy(childOids, 1, instance, 0, childOids.Length - 1);
                        String strInst = InstanceToString(instance);
                        uint column = childOids[0];
                        if (!tabeleKolumy.Contains(column))
                            tabeleKolumy.Add(column);
                        if (tabela_rezultat.ContainsKey(strInst))
                        {
                            tabela_rezultat[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else
                        {
                            tabela_rezultat[strInst] = new Dictionary<uint, AsnType>();
                            tabela_rezultat[strInst][column] = (AsnType)v.Value.Clone();
                        }
                    }
                    else
                    {
                        break; //bo koniec tabeli ;)
                    }
                }
                if (startOid.IsRootOf(curOid))
                {
                    bulkPdu.VbList.Clear();
                    bulkPdu.VbList.Add(curOid);
                    bulkPdu.NonRepeaters = 0;
                    bulkPdu.MaxRepetitions = 100;
                }
                target.Close();
                if (tabela_rezultat.Count <= 0)
                {
                    Console.WriteLine("Żadnych rezlutatów nie zwrócono");
                }
                else
                {
                    Console.WriteLine("Instance");
                    foreach (uint column in tabeleKolumy)
                    {
                        Console.Write("\tColumn id {0}", column);
                    }
                    Console.WriteLine("");
                    foreach (KeyValuePair<string, Dictionary<uint, AsnType>> kvp in tabela_rezultat)
                    {
                        Console.Write("{0}", kvp.Key);
                        foreach (uint column in tabeleKolumy)
                        {
                            if (kvp.Value.ContainsKey(column))
                            {
                                Console.Write("\t{0} ({1})", kvp.Value[column].ToString(), SnmpConstants.GetTypeName(kvp.Value[column].Type));
                            }
                            else
                            {
                                Console.Write("\t-");
                            }
                        }
                        Console.WriteLine("");
                    }
                }
            }
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            // Delete file if it exists.
            if (File.Exists(@".\\SnmpDump.txt"))
            {
                File.Delete(@".\\SnmpDump.txt");
            }
            if (args.Length != 3)
            {
                Console.WriteLine("Syntax: SnmpTable.exe <host> <community> <table oid>");
                return;
            }
            Dictionary <String, Dictionary <uint, AsnType> > result = new Dictionary <String, Dictionary <uint, AsnType> >();
            List <uint>     tableColumns = new List <uint>();
            AgentParameters param        = new AgentParameters(SnmpVersion.Ver2, new OctetString(args[1]));
            IpAddress       peer         = new IpAddress(args[0]);

            if (!peer.Valid)
            {
                Console.WriteLine("Unable to resolve name or error in address for peer: {0}", args[0]);
                return;
            }
            UdpTarget target   = new UdpTarget((IPAddress)peer);
            Oid       startOid = new Oid(args[2]);

            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("Request failed: {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 returned error {0} for request Vb index {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 (!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
                    {
                        break;
                    }
                }
                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
            {
                foreach (uint column in tableColumns)
                {
                    //Console.Write("\tColumn id {0}", column);
                }
                Console.WriteLine("");
                foreach (KeyValuePair <string, Dictionary <uint, AsnType> > kvp in result)
                {
                    //Console.WriteLine("{0}", kvp.Key);
                    string Entry = "";
                    foreach (uint column in tableColumns)
                    {
                        if (kvp.Value.ContainsKey(column))
                        {
                            //Console.WriteLine("\t{0} ({1})", kvp.Value[column].ToString(),SnmpConstants.GetTypeName(kvp.Value[column].Type));
                            Entry += kvp.Value[column].ToString() + ";";
                        }
                        else
                        {
                            Console.Write("\t-");
                        }
                    }
                    using (StreamWriter sw = File.AppendText(path))
                    {
                        Console.WriteLine(Entry);
                        sw.WriteLine(Entry);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public static void GetTable(string host, string community, string oid, DataGridView table)
        {
            string type;

            Program.mibObjectsTypes.TryGetValue(Program.mibObjects.FirstOrDefault(x => x.Value == oid).Key, out type);
            if (type != "T")
            {
                MessageBox.Show("Selected position is not a table!");
                return;
            }

            table.Rows.Clear();
            table.Refresh();

            Dictionary <String, Dictionary <uint, AsnType> > result = new Dictionary <String, Dictionary <uint, AsnType> >();
            List <uint>   tableColumns = new List <uint>();
            List <string> tableRows    = new List <string>();

            AgentParameters param;
            IpAddress       peer;

            try
            {
                param = new AgentParameters(SnmpVersion.Ver2, new OctetString(community));
                peer  = new IpAddress(host);
            }
            catch (Exception e)
            {
                MessageBox.Show("Invalid IP/port or community settings");
                return;
            }


            if (!peer.Valid)
            {
                MessageBox.Show("Unable to resolve name or error in address for peer: {0}", host);
                return;
            }

            UdpTarget target   = new UdpTarget((System.Net.IPAddress)peer);
            Oid       startOid = new Oid(oid);

            startOid.Add(1);
            Pdu           getNextPdu  = Pdu.GetNextPdu();
            Oid           curOid      = (Oid)startOid.Clone();
            List <string> columnNames = new List <string>();

            string searchOid = "." + startOid.ToString();

            foreach (KeyValuePair <string, string> kvp in Program.mibObjects)
            {
                if (kvp.Value.Contains(searchOid) && !kvp.Value.Equals(searchOid))
                {
                    columnNames.Add(kvp.Key);
                }
            }

            while (startOid.IsRootOf(curOid))
            {
                SnmpPacket res = null;
                try
                {
                    res = target.Request(getNextPdu, param);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Request failed: {0}", ex.Message);
                    target.Close();
                    return;
                }

                if (res.Pdu.ErrorStatus != 0)
                {
                    MessageBox.Show("SNMP agent returned error " + res.Pdu.ErrorStatus + " for request Vb index " + 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 (!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
                    {
                        break;
                    }
                }

                if (startOid.IsRootOf(curOid))
                {
                    getNextPdu.VbList.Clear();
                    getNextPdu.VbList.Add(curOid);
                }
            }
            target.Close();

            if (result.Count <= 0)
            {
                MessageBox.Show("No results returned.");
            }
            else
            {
                table.ColumnCount     = tableColumns.Count + 1;
                table.Columns[0].Name = "Instance";
                for (int i = 0; i < tableColumns.Count; i++)
                {
                    table.Columns[i + 1].Name = columnNames[i];
                    //table.Columns[i + 1].Name = "Column id " + tableColumns[i];
                }
                foreach (KeyValuePair <string, Dictionary <uint, AsnType> > kvp in result)
                {
                    tableRows.Add(kvp.Key);
                    foreach (uint column in tableColumns)
                    {
                        if (kvp.Value.ContainsKey(column))
                        {
                            tableRows.Add(kvp.Value[column].ToString());
                        }
                        else
                        {
                            tableRows.Add("");
                        }
                    }
                    table.Rows.Add(tableRows.ToArray());
                    tableRows.Clear();
                }
            }
        }
Ejemplo n.º 9
0
        private void GetTable(String host, AgentParameters param, String tableOID, DataGridView table)
        {
            table.Rows.Clear();
            table.Refresh();
            Dictionary <String, Dictionary <uint, AsnType> > result = new Dictionary <String, Dictionary <uint, AsnType> >();
            List <uint>   tableColumns = new List <uint>();
            List <string> tableRows    = new List <string>();
            IpAddress     peer         = new IpAddress(host);

            if (!peer.Valid)
            {
                MessageBox.Show("Unable to resolve name or error in address for peer: {0}", host);
                return;
            }
            UdpTarget target   = new UdpTarget((IPAddress)peer);
            Oid       startOid = new Oid(tableOID);

            startOid.Add(1);
            Pdu nextPdu = Pdu.GetNextPdu();

            nextPdu.VbList.Add(startOid);
            Oid           curOid    = (Oid)startOid.Clone();
            List <string> colNames  = new List <string>();
            string        searchOid = "." + startOid.ToString();

            foreach (KeyValuePair <string, string> kvp in Program.MIbsList)
            {
                if (kvp.Value.Contains(searchOid) && !kvp.Value.Equals(searchOid))
                {
                    colNames.Add(kvp.Key);
                }
            }

            while (startOid.IsRootOf(curOid))
            {
                SnmpPacket res = null;

                try
                {
                    res = target.Request(nextPdu, param);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Request failed: {0}", e.Message);
                    target.Close();
                    return;
                }

                if (res.Pdu.ErrorStatus != 0)
                {
                    MessageBox.Show("SNMP agent returned error " + res.Pdu.ErrorStatus + " for request Vb index " + 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 (!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
                    {
                        break;
                    }
                }

                if (startOid.IsRootOf(curOid))
                {
                    nextPdu.VbList.Clear();
                    nextPdu.VbList.Add(curOid);
                }
            }
            target.Close();

            if (result.Count <= 0)
            {
                MessageBox.Show("No results returned.");
            }
            else
            {
                table.ColumnCount     = tableColumns.Count + 1;
                table.Columns[0].Name = "Instance";

                for (int i = 0; i < tableColumns.Count; i++)
                {
                    //table.Columns[i + 1].Name = "Column id " + tableColumns[i];
                    table.Columns[i + 1].Name = colNames[i];
                }

                foreach (KeyValuePair <string, Dictionary <uint, AsnType> > kvp in result)
                {
                    tableRows.Add(kvp.Key);
                    foreach (uint column in tableColumns)
                    {
                        if (kvp.Value.ContainsKey(column))
                        {
                            tableRows.Add(kvp.Value[column].ToString());
                        }
                        else
                        {
                            tableRows.Add("");
                        }
                    }
                    table.Rows.Add(tableRows.ToArray());
                    tableRows.Clear();
                }
            }
        }
Ejemplo n.º 10
0
        private void GetTable(Oid oid)
        {
            SnmpV2Packet localResult = new SnmpV2Packet();

            //table[n] wskazuje kolumny
            //table[n][m] wskazuje konkretne komórki
            List <List <String> > table     = new List <List <String> >();
            List <string>         columnOID = new List <string>();

            // This is the table OID supplied on the command line
            Oid startOid = oid;

            // Each table OID is followed by .1 for the entry OID. Add it to the table OID
            // Add Entry OID to the end of the table OID
            startOid.Add(1);

            // Current OID will keep track of the last retrieved OID and be used as
            //  indication that we have reached end of table
            Oid currentOid = (Oid)startOid.Clone();
            Oid prevOid    = null;

            // Keep looping through results until end of table
            // startOid.IsRootOf(curOid)
            // Compares the passed object identifier against self to determine if self is the root of the passed object.
            // If the passed object is in the same root tree as self then a true value is returned.
            // Otherwise a false value is returned from the object.
            while (true)
            {
                //make GetNext
                localResult = _mainForm.GetNextRequest(currentOid);

                //set prev before changing current
                prevOid = currentOid;
                uint[] prevChildOids = Oid.GetChildIdentifiers(startOid, prevOid);

                //set OID result to currentOid
                currentOid = localResult.Pdu.VbList[0].Oid;

                // Make sure we are dealing with an OID that is part of the table
                if (startOid.IsRootOf(currentOid))
                {
                    //get every childOid start from startOID to currentOID
                    // if startOid = .1.1 and currentOid = .1.1.2.1 result will be [0] = 2 [1] = 1
                    uint[] currentChildOids = Oid.GetChildIdentifiers(startOid, currentOid);

                    //first column
                    if ((prevOid == startOid))
                    {
                        table.Add(new List <string>());
                        Oid columnOid = (Oid)startOid.Clone();
                        columnOid.Add(currentChildOids[0]);
                        columnOID.Add(columnOid.ToString());
                    }


                    //next columns
                    if (currentChildOids != null && prevChildOids != null)
                    {
                        //the first element is always name of column (new parameter in table)
                        if ((currentChildOids[0] > prevChildOids[0]))
                        {
                            //it means, currentOid is showing another column (parameter)
                            //adding another column!
                            table.Add(new List <string>());
                            Oid columnOid = (Oid)startOid.Clone();
                            columnOid.Add(currentChildOids[0]);
                            columnOID.Add(columnOid.ToString());
                        }
                    }

                    //saving the values
                    table[table.Count - 1].Add(localResult.Pdu.VbList[0].Value.ToString());
                }
                else
                {
                    // We've reached the end of the table. No point continuing the loop
                    //wychodzi z pętli tylko wtedy, gdy wyszlismy poza korzeń czyli długość curOid jest taka sama jak start i nie sa równe
                    break;
                }
            }//end of while

            /*
             * startOid - początkowe .1.0
             * prevOid - Oid z poprzedniego wywołania (służy do patrzenia, czy jesteśmy jeszcze w tej samej kolumnie czy już w nastepnej
             * currentOid - otrzymane OID z metody GetNext
             *
             * curOid musi zawierać całe startOid i być dłuższe aby while działał
             *
             */

            ShowTable(columnOID, table);
        }
Ejemplo n.º 11
-1
        /// <summary>
        /// Executa uma requisição do tipo Set
        /// </summary>
        /// <param name="setValue">Valor a set definido</param>
        public void Send(AsnType setValue)
        {
            using (var target = new UdpTarget(Host.IP, Host.Port, TimeOut, Retries))
            {
                var agentp = new AgentParameters(SnmpVersion.Ver2, new OctetString(Host.Community));

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

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

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

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

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

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