Beispiel #1
0
        public string EjecutaComando(string valor, bool CMTS, string IP)
        {
            string oid    = oids[valor];
            var    salida = "";

            //Si el valor que se desea obtener es de un CMTS o es un cablemodem
            if (CMTS)
            {
                // SNMP community name
                OctetString community = new OctetString(cmts.Comunidad);

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

                // 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);
                        salida = result.Pdu.ErrorStatus.ToString();
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        //Console.WriteLine("sysDescr({0}) ({1}): {2}",
                        //    result.Pdu.VbList[0].Oid.ToString(),
                        //    SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                        //    result.Pdu.VbList[0].Value.ToString());
                        salida = result.Pdu.VbList[0].Value.ToString();
                    }
                }
                else
                {
                    //Console.WriteLine("No response received from SNMP agent.");
                    salida = "---";
                }
                target.Close();
            }
            else
            {
                // SNMP community name
                OctetString community = new OctetString(cmts.ComunidadCablemodem);

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

                // 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);
                        salida = result.Pdu.ErrorStatus.ToString();
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        //Console.WriteLine("sysDescr({0}) ({1}): {2}",
                        //    result.Pdu.VbList[0].Oid.ToString(),
                        //    SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                        //    result.Pdu.VbList[0].Value.ToString());
                        salida = result.Pdu.VbList[0].Value.ToString();
                    }
                }
                else
                {
                    //Console.WriteLine("No response received from SNMP agent.");
                    salida = "---";
                }
                target.Close();
            }
            return(salida);
        }
Beispiel #2
0
        //システム情報の取得
        public void getSystemInfo(Class_InputData input, Class_TextLog log, int tabnum = 1)
        {
            try
            {
                // コミュニティ名
                OctetString comm = new OctetString(input.community);
                // パラメータクラス
                AgentParameters param = new AgentParameters(comm);
                // バージョン取得
                param.Version = input.versionofSNMPsharp;
                IpAddress agent = new IpAddress(input.hostname);

                //System情報の検索
                foreach (KeyValuePair <string, string> systemhs in SYSTEMLIST)
                {
                    //一括のときはやらない
                    if (tabnum == 3 && (systemhs.Key != "sysDescr" && systemhs.Key != "sysName"))
                    {
                        continue;
                    }

                    // 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(systemhs.Value);

                    if (input.version == "v1" | input.version == "1")
                    {
                        SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                        // If result is null then agent didn't reply or we couldn't parse the reply.
                        if (result != null)
                        {
                            // ErrorStatus other then 0 is an error returned by
                            // the Agent - see SnmpConstants for error definitions

                            if (result.Pdu.ErrorStatus != 0)
                            {
                                // agent reported an error with the request
                                log.Write("Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex);
                            }
                            else
                            {
                                string value = result.Pdu.VbList[0].Value.ToString();

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

                                systemhash[systemhs.Key] = value;
                                log.Write("GET項目:" + input.hostname + " : " + systemhs.Key + " " + systemhs.Value + " 値:" + value);
                            }
                        }
                        else
                        {
                            //Console.WriteLine("SNMP agentからのレスポンスがありません.");
                            log.Write("SNMP agentからのレスポンスがありません.");
                        }
                    }
                    // v2以降の時
                    else
                    {
                        SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

                        // If result is null then agent didn't reply or we couldn't parse the reply.
                        if (result != null)
                        {
                            // ErrorStatus other then 0 is an error returned by
                            // the Agent - see SnmpConstants for error definitions

                            if (result.Pdu.ErrorStatus != 0)
                            {
                                // agent reported an error with the request
                                log.Write("Error in SNMP reply. Error " + result.Pdu.ErrorStatus.ToString() + " index " + result.Pdu.ErrorIndex.ToString());

                                //Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                //result.Pdu.ErrorStatus,
                                //result.Pdu.ErrorIndex);
                            }
                            else
                            {
                                string value = result.Pdu.VbList[0].Value.ToString();

                                //TimeTick型の時はミリ秒も出力する
                                if (result.Pdu.VbList[0].Value.Type == SnmpConstants.SMI_TIMETICKS)
                                {
                                    TimeTicks timeti = (TimeTicks)result.Pdu.VbList[0].Value;
                                    value = "(" + timeti.Milliseconds.ToString() + "ms)" + result.Pdu.VbList[0].Value.ToString();
                                }
                                //取得した値を格納
                                _systemhash[systemhs.Key] = value;
                                log.Write("GET項目:" + input.hostname + " : " + systemhs.Key + " " + systemhs.Value + " 値:" + value);
                            }
                        }
                        else
                        {
                            log.Write("SNMP agentからのレスポンスがありません.");
                            //Console.WriteLine("SNMP agentからのレスポンスがありません.");
                        }
                    }

                    target.Close();
                }
            }

            catch (Exception)
            {
                throw;
            }
        }
Beispiel #3
0
        static void DumpBulk(string oid, string host, string communityString, string filename)
        {
            using (StreamWriter sw = new StreamWriter(filename))
            {
                // 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
                            sw.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());
                                    sw.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
                    {
                        sw.WriteLine("No response received from SNMP agent.");
                    }
                }
                target.Close();
            }
        }
Beispiel #4
0
 public SNMPWalk(UdpTarget target, string oid)
 {
     this.target = target;
     this.oid    = new Oid(oid);
 }
Beispiel #5
0
        public PartialViewResult WalkSend(int?page, string presetName, string TowerName, string IP, string DeviceName)
        {
            Checked.Clear();
            Time.Clear();
            walkSearch.Clear();
            SearchNameWalk = "";

            if (presetName == "Preset")
            {
                PresetIND = 0;
                walkList.Clear();
                IPadrress  = IP;
                ViewBag.IP = IPadrress;

                //var devicename = db.devicesTypes.Where(d => d.Name == DeviceName).FirstOrDefault();
                //var walkOid = db.MibTreeInformations.Where(m => m.DeviceID == devicename.ID).FirstOrDefault();
                //deviceTypeID = devicename.ID;
                OctetString community = new OctetString("public");

                AgentParameters param = new AgentParameters(community);
                param.Version = SnmpVersion.Ver2;

                IpAddress agent = new IpAddress("192.168.24.12");

                UdpTarget target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                Oid       rootOid = new Oid(".1.3.6.1.4.1"); // ifDescr
                                                             //Oid rootOid = new Oid(".1.3.6.1.4.1.23180.2.1.1.1"); // ifDescr

                Oid lastOid = (Oid)rootOid.Clone();

                Pdu pdu = new Pdu(PduType.GetNext);

                while (lastOid != null)
                {
                    try {
                        if (pdu.RequestId != 0)
                        {
                            pdu.RequestId += 1;
                        }
                        pdu.VbList.Clear();
                        pdu.VbList.Add(lastOid);
                        SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                        if (result != null)
                        {
                            if (result.Pdu.ErrorStatus != 0)
                            {
                                lastOid = null;
                                break;
                            }
                            else
                            {
                                foreach (Vb v in result.Pdu.VbList)
                                {
                                    if (rootOid.IsRootOf(v.Oid))
                                    {
                                        WalkDevice walk = new WalkDevice();
                                        ID++;
                                        walk.ID     = ID;
                                        walk.WalkID = ID;
                                        string oid = "." + v.Oid.ToString();
                                        var    OidMibdescription = db.MibTreeInformations.Where(m => m.OID == oid).FirstOrDefault();
                                        if (OidMibdescription == null)
                                        {
                                            oid = oid.Remove(oid.Length - 1);
                                            oid = oid.Remove(oid.Length - 1);
                                            OidMibdescription = db.MibTreeInformations.Where(o => o.OID == oid).FirstOrDefault();
                                        }
                                        if (OidMibdescription == null)
                                        {
                                            oid = oid.Remove(oid.Length - 1);
                                            oid = oid.Remove(oid.Length - 1);
                                            OidMibdescription = db.MibTreeInformations.Where(o => o.OID == oid).FirstOrDefault();
                                            if (OidMibdescription != null)
                                            {
                                                walk.WalkDescription = OidMibdescription.Description;
                                            }
                                        }
                                        else
                                        {
                                            walk.WalkDescription = OidMibdescription.Description;
                                        }
                                        if (OidMibdescription != null)
                                        {
                                            walk.WalkDescription = OidMibdescription.Description;
                                        }

                                        walk.WalkOID = v.Oid.ToString();
                                        walk.Type    = v.Value.ToString();
                                        walk.value   = SnmpConstants.GetTypeName(v.Value.Type);
                                        walk.Time    = 60;
                                        walkList.Add(walk);
                                        lastOid = v.Oid;
                                    }
                                    else
                                    {
                                        lastOid = null;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e) { }
                }

                target.Close();
            }
            else
            {
                var presetname = db.Presets.Where(p => p.PresetName == presetName).FirstOrDefault();
                walkList = db.WalkDevices.Where(w => w.PresetID == presetname.ID).ToList();
            }

            //for (int i = 0; i < 120; i++)
            //{
            //    WalkInformation walk = new WalkInformation();
            //    ID++;
            //    walk.ID = ID;
            //    walk.OIDName = "1.2.2.3.50.20.21.2.2.3.50.20.21.2.2.3.50.20.21.2.2.3.50.20.2";
            //    walk.Value = "mrt_____mrt_____mrt_____mrt_____mrt_____mrt_____";
            //    walk.Time = 60;
            //    walkList.Add(walk);
            //}
            EditInd      = 0;
            ViewBag.Edit = EditInd;
            return(PartialView("_WalkView", walkList.ToPagedList(page ?? 1, viewSearch)));
        }
Beispiel #6
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");
                }
            }
        }
Beispiel #7
0
        private System.Collections.Generic.Dictionary <string, string> ReceiveResponseWithTableVB(TableVarBinding tableVb, Pdu pdu, UdpTarget target, IAgentParameters param)
        {
            if (string.IsNullOrEmpty(tableVb.TableEntryOid))
            {
                throw new System.ArgumentNullException("The TableEntryOid can not be null or empty.");
            }
            Oid oid  = new Oid(tableVb.TableEntryOid);
            Oid oid2 = null;

            if (string.IsNullOrEmpty(tableVb.ColumnOid))
            {
                oid2 = (Oid)oid.Clone();
            }
            else
            {
                oid2 = new Oid(tableVb.ColumnOid);
            }
            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            while (oid2 != null)
            {
                pdu.VbList.Clear();
                pdu.VbList.Add(oid2);
                SnmpPacket snmpPacket = target.Request(pdu, param);
                this.validateResponse(snmpPacket, pdu);
                foreach (Vb current in snmpPacket.Pdu.VbList)
                {
                    if (!oid.IsRootOf(current.Oid))
                    {
                        oid2 = null;
                        break;
                    }
                    if (current.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                    {
                        oid2 = null;
                        break;
                    }
                    string key = current.Oid.ToString();
                    if (!dictionary.ContainsKey(key))
                    {
                        dictionary.Add(key, current.Value.ToString());
                        oid2 = current.Oid;
                    }
                }
            }
            return(dictionary);
        }
Beispiel #8
0
        public static void GetAllInfo(IPAddress ip, IDictionary <string, object> userSet)
        {
            if (!CheckIfAny(userSet))
            {
                return;
            }

            try
            {
                OctetString community = new OctetString("public");

                // Define agent parameters class
                AgentParameters param = new AgentParameters(community)
                {
                    Version = SnmpVersion.Ver1
                };
                // Set SNMP version to 1 (or 2)
                // 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

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

                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.Get);
                if (userSet.ContainsKey(ParameterSet.SnmpDesc))
                {
                    pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); //sysDescr
                }
                if (userSet.ContainsKey(ParameterSet.SnmpObjId))
                {
                    pdu.VbList.Add("1.3.6.1.2.1.1.2.0"); //sysObjectID
                }
                if (userSet.ContainsKey(ParameterSet.SnmpUpTime))
                {
                    pdu.VbList.Add("1.3.6.1.2.1.1.3.0"); //sysUpTime
                }
                if (userSet.ContainsKey(ParameterSet.SnmpContact))
                {
                    pdu.VbList.Add("1.3.6.1.2.1.1.4.0"); //sysContact
                }
                if (userSet.ContainsKey(ParameterSet.SnmpHostName))
                {
                    pdu.VbList.Add("1.3.6.1.2.1.1.5.0"); //sysName
                }
                // 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
                        throw new RemoteSnmpException(
                                  $"Error in SNMP reply. Error {result.Pdu.ErrorStatus} index {result.Pdu.ErrorIndex}");
                    }

                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    var id = 0;
                    if (userSet.ContainsKey(ParameterSet.SnmpDesc))
                    {
                        userSet[ParameterSet.SnmpDesc] = result.Pdu.VbList[id++].Value.ToString();
                    }
                    if (userSet.ContainsKey(ParameterSet.SnmpObjId))
                    {
                        userSet[ParameterSet.SnmpObjId] = result.Pdu.VbList[id++].Value.ToString();
                    }
                    if (userSet.ContainsKey(ParameterSet.SnmpUpTime))
                    {
                        userSet[ParameterSet.SnmpUpTime] = result.Pdu.VbList[id++].Value.ToString();
                    }
                    if (userSet.ContainsKey(ParameterSet.SnmpContact))
                    {
                        userSet[ParameterSet.SnmpContact] = result.Pdu.VbList[id++].Value.ToString();
                    }
                    if (userSet.ContainsKey(ParameterSet.SnmpHostName))
                    {
                        userSet[ParameterSet.SnmpHostName] = result.Pdu.VbList[id].Value.ToString();
                    }
                }
                else
                {
                    throw new RemoteSnmpException("No response received from SNMP agent.");
                }
                target.Close();
            }
            catch (Exception e)
            {
                throw new RemoteSnmpException(e.Message, e);
            }
        }
        private void Save_Click(object sender, EventArgs e)
        {
            IPAddress address;

            if (!IPAddress.TryParse(ComboBoxIpAddressCisco.Text, out address))
            {
                MessageBox.Show("Введите корректно IP адрес");
                return;
            }

            //Проверяем существует ли такой ip адрес
            if (ComboBoxIpAddressCisco.FindString(ComboBoxIpAddressCisco.Text) != -1)
            {
                MessageBox.Show("Cisco с таким IPадресом уже добавлена");
                return;
            }

            //идет ли пинг
            try
            {
                Ping      pingSender = new Ping();
                PingReply reply      = pingSender.Send(ComboBoxIpAddressCisco.Text);
            }

            catch
            {
                MessageBox.Show("IP адрес не доступен");
                return;
            }

            //правильно ли указан community, то бишь может ли она получить доступ по SNMP
            UdpTarget target = new UdpTarget((IPAddress) new IpAddress(ComboBoxIpAddressCisco.Text), 161, 500, 0);
            Pdu       pdu    = new Pdu(PduType.Get);

            pdu.VbList.Add(".1.3.6.1.2.1.1.6.0");
            AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString(TextBoxCommunity.Text));
            SnmpV2Packet    response;

            try
            {
                response = target.Request(pdu, aparam) as SnmpV2Packet;
            }

            catch (Exception ex)
            {
                MessageBox.Show("connection failed");
                MessageBox.Show(ex.Message);
                target.Close();
                return;
            }


            var value = new IPCom(ComboBoxIpAddressCisco.Text, TextBoxCommunity.Text);

            var serviceContext = new WaterGateServiceContext();
            var list           = StaticValues.CiscoList.ToList();

            list.Add(value);

            Save.Enabled   = false;
            Delete.Enabled = false;
            Change.Enabled = false;
            Cursor         = Cursors.AppStarting;
            serviceContext.UpdateCiscoRouters(list, (error) =>
            {
                if (error != null)
                {
                    MessageBox.Show("Произошла ошибка при соединении с сервером, проверьте наличие соединения.",
                                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    Invoke(new Action(() =>
                    {
                        MessageBox.Show("Запись успешно добавлена.",
                                        "Готово", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //добавляем в наш массив
                        StaticValues.CiscoList.Add(value);

                        //добавляем в Combobox
                        this.ComboBoxIpAddressCisco.Items.Add(ComboBoxIpAddressCisco.Text);

                        TextBoxCommunity.Clear();
                        ComboBoxIpAddressCisco.ResetText();
                    }));
                }


                Invoke(new Action(() =>
                {
                    Save.Enabled   = true;
                    Delete.Enabled = true;
                    Change.Enabled = true;
                    Cursor         = Cursors.Arrow;
                }));
            });
        }
Beispiel #10
0
        private System.Collections.Generic.Dictionary <string, string> ReceiveResponseWithLeafVB(LeafVarBinding leafVb, Pdu pdu, UdpTarget target, IAgentParameters param)
        {
            if (leafVb.VarBindings.Count < 1)
            {
                throw new System.ArgumentNullException("The variables for the " + pdu.Type + " opertion is emtpy.");
            }
            pdu.VbList.Clear();
            this.configPduVb(leafVb, pdu);
            SnmpPacket snmpPacket = target.Request(pdu, param);

            this.validateResponse(snmpPacket, pdu);
            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            foreach (Vb current in snmpPacket.Pdu.VbList)
            {
                if (current.Value.Type != SnmpConstants.SMI_NOSUCHINSTANCE && current.Value.Type != SnmpConstants.SMI_NOSUCHOBJECT && current.Value.Type != SnmpConstants.SMI_ENDOFMIBVIEW)
                {
                    string key = current.Oid.ToString();
                    if (!dictionary.ContainsKey(key))
                    {
                        dictionary.Add(key, current.Value.ToString());
                    }
                }
            }
            return(dictionary);
        }
        private void Change_Click(object sender, EventArgs e)
        {
            //правильно ли указан community, то бишь может ли она получить доступ по SNMP
            UdpTarget target = new UdpTarget((IPAddress) new IpAddress(ComboBoxIpAddressCisco.Text), 161, 500, 0);
            Pdu       pdu    = new Pdu(PduType.Get);

            pdu.VbList.Add(".1.3.6.1.2.1.1.6.0");
            AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString(TextBoxCommunity.Text));
            SnmpV2Packet    response;

            try
            {
                response = target.Request(pdu, aparam) as SnmpV2Packet;
            }

            catch (Exception ex)
            {
                MessageBox.Show("Скорее всего введен неверный Community");
                MessageBox.Show(ex.Message);
                target.Close();
                this.ComboBoxIpAddressCisco.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDown;
                return;
            }



            var oldValue = StaticValues.CiscoList.FirstOrDefault(item => item.IP.Contains(ComboBoxIpAddressCisco.Text));

            if (oldValue == null)
            {
                return;
            }

            var newValue = new IPCom(ComboBoxIpAddressCisco.Text, TextBoxCommunity.Text);


            var serviceContext = new WaterGateServiceContext();
            var list           = StaticValues.CiscoList.ToList();

            list.Remove(oldValue);
            list.Add(newValue);

            Save.Enabled   = false;
            Delete.Enabled = false;
            Change.Enabled = false;
            Cursor         = Cursors.AppStarting;



            foreach (var item in StaticValues.JDSUCiscoArray)
            {
                if (item.CiscoIPCom.IP == ComboBoxIpAddressCisco.Text)
                {
                    item.CiscoIPCom.Com = TextBoxCommunity.Text;
                }
            }

            //   var serviceContext = new WaterGateServiceContext();
            serviceContext.UpdatePorts(StaticValues.JDSUCiscoArray, (error) =>
            {
                if (error != null)
                {
                    Invoke(new Action(() =>
                                      MessageBox.Show(
                                          "Произошла ошибка при соединении с сервером, проверьте наличие соединения.",
                                          "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)));
                }
            });



            serviceContext.UpdateCiscoRouters(list, (error) =>
            {
                if (error != null)
                {
                    MessageBox.Show("Произошла ошибка при соединении с сервером, проверьте наличие соединения.",
                                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Invoke(new Action(() =>
                {
                    MessageBox.Show("Запись успешно изменена.",
                                    "Готово", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    //удаляем старый ip и community
                    StaticValues.CiscoList.Remove(oldValue);

                    //и добавляем в наш массив новые данные и все должно работать =)
                    StaticValues.CiscoList.Add(newValue);


                    ComboBoxIpAddressCisco.SelectedIndex      = -1;
                    this.ComboBoxIpAddressCisco.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDown;
                    TextBoxCommunity.Clear();
                }));

                Invoke(new Action(() =>
                {
                    Save.Enabled   = true;
                    Delete.Enabled = true;
                    Change.Enabled = true;
                    Cursor         = Cursors.Arrow;
                }));
            });
        }
Beispiel #12
0
        private bool DiscoverAgents(IPAddress cameraAddress, IList <UdpTarget> targets)
        {
            bool recoveredInformation = false;

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


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

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

            pdu.VbList.Add("1.3.6.1.2.1.1.1.0");             //sysDescr
            pdu.VbList.Add("1.3.6.1.2.1.1.2.0");             //sysObjectID
            pdu.VbList.Add("1.3.6.1.2.1.1.3.0");             //sysUpTime
            pdu.VbList.Add("1.3.6.1.2.1.1.4.0");             //sysContact
            pdu.VbList.Add("1.3.6.1.2.1.1.5.0");             //sysName

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

            //TrapManager trapManager = new TrapManager();
            //Task.Run(()=> trapManager.CreateTrapManager());


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

            param.Version = SnmpVersion.Ver2;
            IpAddress agent  = new IpAddress(ipaddr);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            Pdu       pdu    = new Pdu(PduType.Get);
            Pdu       pdu1   = new Pdu(PduType.Get);
            Pdu       pdu2   = new Pdu(PduType.Get);
            Pdu       pdu3   = new Pdu(PduType.Get);
            Pdu       pdu4   = new Pdu(PduType.Get);
            Pdu       pdu5   = new Pdu(PduType.Get);

            pdu.VbList.Add(".1.3.6.1.2.1.47.1.1.1.1.13.1"); //model
            pdu.VbList.Add(".1.3.6.1.2.1.1.3.0");           //uptime
            pdu.VbList.Add(".1.3.6.1.2.1.2.1.0");           // number of interfaces
            pdu.VbList.Add(".1.3.6.1.2.1.47.1.1.1.1.10.1"); // IOS
            pdu.VbList.Add(".1.3.6.1.2.1.1.5.0");           //hostname

            SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

            Console.ForegroundColor = ConsoleColor.White;
            Console.Write("Model name: ");
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine(result.Pdu.VbList[0].Value.ToString());

            Console.ForegroundColor = ConsoleColor.White;
            Console.Write("IOS: ");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine(result.Pdu.VbList[3].Value.ToString());

            Console.ForegroundColor = ConsoleColor.White;
            Console.Write("Uptime: ");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine(result.Pdu.VbList[1].Value.ToString());

            Console.ForegroundColor = ConsoleColor.White;
            Console.Write("Hostname: ");
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.WriteLine(result.Pdu.VbList[4].Value.ToString());


            numint = int.Parse(result.Pdu.VbList[2].Value.ToString());

            for (int i = 0; i < numint; i++)
            {
                pdu1.VbList.Add(".1.3.6.1.2.1.2.2.1.2." + (i + 1));  // name interface
                pdu2.VbList.Add(".1.3.6.1.2.1.2.2.1.7." + (i + 1));  // admin state
                pdu3.VbList.Add(".1.3.6.1.2.1.2.2.1.8." + (i + 1));  // link
                pdu4.VbList.Add(".1.3.6.1.2.1.2.2.1.14." + (i + 1)); // input errors
                pdu5.VbList.Add(".1.3.6.1.2.1.2.2.1.20." + (i + 1)); // output errors
                SnmpV2Packet result1 = (SnmpV2Packet)target.Request(pdu1, param);
                SnmpV2Packet result2 = (SnmpV2Packet)target.Request(pdu2, param);
                SnmpV2Packet result3 = (SnmpV2Packet)target.Request(pdu3, param);
                SnmpV2Packet result4 = (SnmpV2Packet)target.Request(pdu4, param);
                SnmpV2Packet result5 = (SnmpV2Packet)target.Request(pdu5, param);
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Interface: ");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(result1.Pdu.VbList[i].Value.ToString());

                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write("       -- link: ");
                Console.ForegroundColor = ConsoleColor.Green;
                if (Convert.ToInt32(result3.Pdu.VbList[i].Value.ToString()) == 1)
                {
                    Console.WriteLine("up");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("down");
                }

                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write("       -- admin status: ");
                Console.ForegroundColor = ConsoleColor.Green;
                if (Convert.ToInt32(result2.Pdu.VbList[i].Value.ToString()) == 1)
                {
                    Console.WriteLine("up");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red; Console.Write("down");
                }

                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write("       -- input errors(CRC): ");
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.WriteLine(result4.Pdu.VbList[i].Value.ToString());

                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write("       -- output errors: ");
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.WriteLine(result5.Pdu.VbList[i].Value.ToString());
            }
            Console.ReadLine();
        }
Beispiel #14
0
        private void button11_Click(object sender, EventArgs e)
        {
            //SnmpTest snt = new SnmpTest(tbAddress.Text, "public", ".1.3.6.1.4.1.38446");
            //string[] t=  {".1.3.6.1.4.1.38446"};
            //snt.Test();



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

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

            Pdu pdu2 = new Pdu(PduType.GetBulk);

            pdu2.VbList.Add(".1.3.6.1.4.1.38446.1.1.2.1.13");

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

            int i = result2.Pdu.VbCount;

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

            return;



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

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

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

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

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

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                Console.WriteLine("{0} ({1}): {2}",
                                                  v.Oid.ToString(),
                                                  SnmpConstants.GetTypeName(v.Value.Type),
                                                  v.Value.ToString());
                                lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Dispose();
        }
Beispiel #15
0
        private System.Collections.Generic.Dictionary <string, string> SendPacket(SnmpOperationType pduType, System.Collections.Generic.List <VarBinding> variables)
        {
            if (variables == null || variables.Count < 1)
            {
                throw new System.ArgumentNullException("The variables for the " + pduType + " operation is null or empty.");
            }
            UdpTarget        udpTarget       = null;
            IAgentParameters agentParameters = null;
            Pdu pdu = null;

            System.Collections.Generic.Dictionary <string, string> result3;
            try
            {
                udpTarget = new UdpTarget(System.Net.IPAddress.Parse(this.config.AgentIp), this.config.Port, this.config.Timeout, this.config.Retry);
                if (this.config.Version == SnmpVersionType.Ver3)
                {
                    agentParameters = new SecureAgentParameters();
                    SecureAgentParameters secureAgentParameters = agentParameters as SecureAgentParameters;
                    if (!udpTarget.Discovery(secureAgentParameters))
                    {
                        throw new SnmpException("Discovery failed: The device with ip(" + this.config.AgentIp + ") is unreachable.");
                    }
                    pdu = new ScopedPdu();
                    SnmpV3Config snmpV3Config = this.config as SnmpV3Config;
                    secureAgentParameters.SecurityName.Set(snmpV3Config.UserName);
                    secureAgentParameters.Authentication = (AuthenticationDigests)snmpV3Config.Authentication;
                    secureAgentParameters.AuthenticationSecret.Set(snmpV3Config.AuthSecret);
                    secureAgentParameters.Privacy = (PrivacyProtocols)snmpV3Config.Privacy;
                    secureAgentParameters.PrivacySecret.Set(snmpV3Config.PrivacySecret);
                    secureAgentParameters.Reportable = true;
                }
                else
                {
                    if (this.config.Version == SnmpVersionType.Ver1)
                    {
                        OctetString community = new OctetString(((SnmpV1Config)this.config).Community);
                        agentParameters = new AgentParameters(SnmpVersion.Ver1, community);
                    }
                    else
                    {
                        OctetString community = new OctetString(((SnmpV2Config)this.config).Community);
                        agentParameters = new AgentParameters(SnmpVersion.Ver2, community);
                    }
                    pdu = new Pdu();
                }
                DictionaryUtil dictionaryUtil = new DictionaryUtil();
                foreach (VarBinding current in variables)
                {
                    try
                    {
                        if (current is LeafVarBinding)
                        {
                            if (pduType.Equals(SnmpOperationType.GetTable) || pduType.Equals(SnmpOperationType.Walk))
                            {
                                pdu.Type = PduType.Get;
                            }
                            else
                            {
                                pdu.Type = (PduType)pduType;
                                if (pduType.Equals(SnmpOperationType.GetBulk))
                                {
                                    this.configBulkPdu(pdu, current.MaxRepetition);
                                }
                            }
                            System.Collections.Generic.Dictionary <string, string> result = this.ReceiveResponseWithLeafVB((LeafVarBinding)current, pdu, udpTarget, agentParameters);
                            dictionaryUtil.Add(result);
                        }
                        else
                        {
                            if (agentParameters.Version == SnmpVersion.Ver1)
                            {
                                pdu.Type = PduType.GetNext;
                            }
                            else
                            {
                                pdu.Type = PduType.GetBulk;
                                this.configBulkPdu(pdu, current.MaxRepetition);
                            }
                            System.Collections.Generic.Dictionary <string, string> result2 = this.ReceiveResponseWithTableVB((TableVarBinding)current, pdu, udpTarget, agentParameters);
                            dictionaryUtil.Add(result2);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        if (!ex.Message.Contains("Invalid ASN.1 type encountered 0x00. Unable to continue decoding."))
                        {
                            throw new SnmpException(ex.Message);
                        }
                    }
                }
                result3 = dictionaryUtil.Result;
            }
            catch (System.Exception ex2)
            {
                throw new SnmpException(ex2.Message);
            }
            finally
            {
                if (udpTarget != null)
                {
                    udpTarget.Close();
                }
            }
            return(result3);
        }
Beispiel #16
0
        public static Dictionary <string, string> getWalkValue_v3(string host, int port, int snmpver, string comm, string irootOid)
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();
            // SNMP community name
            OctetString community = new OctetString(comm);

            // 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.Ver3;
            // 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, port, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(irootOid); // 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 = 1000;
            try
            {
                // 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
                    SnmpV3Packet result = new SnmpV3Packet();
                    result.authPriv(ASCIIEncoding.UTF8.GetBytes("milan"),
                                    ASCIIEncoding.UTF8.GetBytes("myAuthSecret"), AuthenticationDigests.MD5,
                                    ASCIIEncoding.UTF8.GetBytes("myPrivSecret"), PrivacyProtocols.DES);
                    result = (SnmpV3Packet)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)
                        {
                            // 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))
                                {
                                    dic.Add(v.Oid.ToString(), v.Value.ToString());
                                }
                                else
                                {
                                    // we have reached the end of the requested
                                    // MIB tree. Set lastOid to null and exit loop
                                    lastOid = null;
                                }
                            }
                        }
                    }
                }
                target.Close();
                return(dic);
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                target.Close();
                return(dic);
            }
        }
Beispiel #17
0
        }//将对应id的条目的状态栏设置为橘红色

        private void GetSNMPResponse(object input_id)
        {
            //inputmodel temp =new inputmodel();
            //temp = (inputmodel)mod;
            //CancellationTokenSource token = temp.canceltoken;
            string id     = (string)input_id;
            string ipaddr = null;

            for (int i = 0; i < Common.dt_snmp.Rows.Count; i++)
            {
                string tmp = Common.dt_snmp.Rows[i]["Id"].ToString();
                if (tmp == (string)id)
                {
                    ipaddr = Common.dt_snmp.Rows[i]["dev_ip"].ToString();
                }
            }
            int feq = Common.getfequency((string)id);
            //填充snmp包头信息
            OctetString community = new OctetString("public");
            //社区
            AgentParameters param = new AgentParameters(community);

            //版本
            param.Version = SnmpVersion.Ver1;
            //ip地址代理
            IpAddress agent = new IpAddress(ipaddr);
            //定义udp包
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            Pdu       pdu    = new Pdu(PduType.Get);

            //填充pdu列表
            pdu.VbList.Add(".1.3.6.1.2.1.1.3.0");    //设备名的OID号
            for (; ;)
            {
                if (canceltokensource.IsCancellationRequested == true)
                {
                    Common.writetologfrm(string.Format("SNMP 设备ID:{1} 线程{0}终止", Thread.CurrentThread.ManagedThreadId, id.ToString()));
                    target.Dispose();
                    this.Close();
                    break;//若收到cancellationToken消息则取消此线程
                }
                Dictionary <string, string> output_cache = new Dictionary <string, string>();
                try
                {
                    //创建snmp请求
                    SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                    if (result != null)
                    {
                        //errorstatus不等于0则错误
                        if (result.Pdu.ErrorStatus != 0)
                        {
                            this.Invoke(new MethodInvoker(() => show_failed((string)id)));
                        }
                        else
                        {    //正确则返回pdu数据
                            for (int x = 0; x < result.Pdu.VbList.Count; x++)
                            {
                                this.Invoke(new MethodInvoker(() => show_success((string)id)));
                                output_cache.Add(result.Pdu.VbList[x].Oid.ToString(), result.Pdu.VbList[x].Value.ToString());
                            }
                        }
                    }
                    else
                    {
                        this.Invoke(new MethodInvoker(() => show_failed((string)id)));
                    }
                }
                catch (Exception e)
                {
                    this.Invoke(new MethodInvoker(() => Common.writetologfrm(string.Format("SNMP异常 ID:{0} 描述:{1} ", id.ToString(), e.Message))));
                    this.Invoke(new MethodInvoker(() => show_failed((string)id)));
                    continue;
                }
                finally
                {
                    Thread.Sleep(Common.getfequency((string)id));
                }
            }
            //target.Dispose();
        }//SNMP线程工作内容
        /// <summary>
        /// Performs SNMP walk using Ver 1 GetNext operation.
        /// </summary>
        /// <param name="interfaceIdWalkRootOid">The retrievable value to start walking at. The actual OID is resolved from the device database.</param>
        /// <returns>A <see cref="VbCollection" /> with the received data.</returns>
        /// <remarks>Derived from example code at <see href="http://www.snmpsharpnet.com/?page_id=108" />.</remarks>
        private VbCollection DoWalkGetNext(Oid interfaceIdWalkRootOid)
        {
            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)interfaceIdWalkRootOid.Clone();

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

            VbCollection returnCollection = new VbCollection();

            // 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.
                Interlocked.CompareExchange(ref nextRequestId, 0, int.MaxValue); // wrap the request ID
                pdu.RequestId = Interlocked.Increment(ref nextRequestId);

                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();

                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);

                SnmpV1Packet result;
                using (var target = new UdpTarget((IPAddress)this.Address, this.Options.Port, Convert.ToInt32(this.Options.Timeout.TotalMilliseconds), this.Options.Retries))
                {
                    // Make SNMP request
                    result = (SnmpV1Packet)target.Request(pdu, this.QueryParameters);
                }

                SnmpAbstraction.RecordSnmpRequest(this.Address, pdu, result);

                // You should catch exceptions in the Request if using in real application.
                // [DJ3MU] : Yeah - cool idea - but I still wouldn't know what else to do with them.
                //           So for now, let fly them out to our caller.

                // 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
                        log.Warn($"Error in SNMP reply of device '{this.Address}': Error status {result.Pdu.ErrorStatus} at index {result.Pdu.ErrorIndex}");
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (interfaceIdWalkRootOid.IsRootOf(v.Oid))
                            {
                                returnCollection.Add(v);

                                lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    throw new HamnetSnmpException($"No response received from SNMP agent for device '{this.Address}'", this.Address?.ToString());
                }
            }

            return(returnCollection);
        }
Beispiel #19
0
        public static void Check(CredentialsSnmp credentials)
        {
            // Populate the List of OID's to Get
            var asnItems = new Dictionary <string, SnmpAsnItem>
            {
                { BaseOid + "1.1.0", new SnmpAsnItem("Model") },
                { BaseOid + "1.2.0", new SnmpAsnItem("Serial Number") },
                { BaseOid + "1.5.0", new SnmpAsnItem("Software Version") },
                { BaseOid + "2.1.0", new SnmpAsnItem("Battery Status") },
                { BaseOid + "2.3.0", new SnmpAsnItem("Estimated Runtime") },
                { BaseOid + "6.1.0", new SnmpAsnItem("Alarms Present") },
                { BaseOid + "7.1.0", new SnmpAsnItem("UPS Status") },
                { BaseOid + "10.1.0", new SnmpAsnItem("Temperature") },
                { BaseOid + "10.2.0", new SnmpAsnItem("Humidity") }
            };

            var asnItemsLookup = new Dictionary <string, Vb>();

            // SNMP Query
            var snmpCommunity = new OctetString(credentials.Community);
            var agentParams   = new AgentParameters(snmpCommunity)
            {
                Version = SnmpVersion.Ver2
            };

            var agent  = new IpAddress(credentials.Host);
            var target = new UdpTarget((IPAddress)agent, Port, 2000, 1);

            var pdu = new Pdu(PduType.Get);

            foreach (var item in asnItems)
            {
                pdu.VbList.Add(item.Key);
            }

            var result = new SnmpV2Packet();

            try
            {
                result = (SnmpV2Packet)target.Request(pdu, agentParams);
            }
            catch (Exception ex)
            {
                if (ex.Message == "Request has reached maximum retries.")
                {
                    Error.WriteOutput("SNMP Request to " + credentials.Host + " with community " + credentials.Community + " has exceeded the maximum number of retries.");
                    return;
                }
            }

            if (result != null)
            {
                // Populate Results
                foreach (var item in result.Pdu.VbList)
                {
                    if (asnItems.ContainsKey(item.Oid.ToString()))
                    {
                        asnItems[item.Oid.ToString()].Vb = item;
                    }
                }

                // Build Reverse Lookup Dictionary
                foreach (var item in asnItems)
                {
                    asnItemsLookup.Add(item.Value.Description, item.Value.Vb);
                }

                var output = new Result();
                var model  = asnItemsLookup["Model"].Value.ToString();

                var message = model;
                message += " SN " + asnItemsLookup["Serial Number"].Value;
                message += " (SW v" + asnItemsLookup["Software Version"].Value + ")";

                Channel channel;

                // Humidity
                var tempStr = asnItemsLookup["Humidity"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    if (tempStr != "Null" && tempStr != "SNMP No-Such-Instance")
                    {
                        var humidity = Convert.ToInt32(tempStr) / 10;
                        channel = new Channel
                        {
                            Description     = "Humidity",
                            Unit            = Unit.Percent,
                            Value           = humidity.ToString(),
                            LimitMinError   = "5",
                            LimitMinWarning = "10",
                            LimitMaxWarning = "90",
                            LimitMaxError   = "95",
                            LimitMode       = "1"
                        };
                        output.Channels.Add(channel);
                    }
                }

                // Temperature
                tempStr = asnItemsLookup["Temperature"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    if (tempStr != "Null" && tempStr != "SNMP No-Such-Instance")
                    {
                        var temp = Convert.ToInt32(tempStr) / 10;
                        channel = new Channel
                        {
                            Description     = "Temperature",
                            Unit            = Unit.Temperature,
                            Value           = temp.ToString(),
                            LimitMinError   = "10",
                            LimitMinWarning = "15",
                            LimitMaxWarning = "50",
                            LimitMaxError   = "55",
                            LimitMode       = "1"
                        };
                        output.Channels.Add(channel);
                    }
                }

                // UPS Status
                tempStr = asnItemsLookup["UPS Status"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    channel = new Channel
                    {
                        Description = "UPS Status",
                        Unit        = Unit.Custom,
                        Value       = tempStr
                    };

                    switch (Convert.ToInt32(tempStr))
                    {
                    case 1:
                        channel.Warning = "1";
                        message        += " Standby On";
                        output.Error    = true;
                        break;

                    case 2:
                        channel.Warning = "1";
                        message        += " Standby Off";
                        output.Error    = true;
                        break;

                    case 3:
                        message += " Eco Mode";
                        break;

                    case 4:
                        break;

                    case 5:
                        channel.Warning = "1";
                        message        += " Alarm Reset";
                        break;

                    case 6:
                        channel.Warning = "1";
                        message        += " On Bypass";
                        break;

                    case 7:
                        channel.Warning = "1";
                        message        += " On Inverter";
                        break;

                    default:
                        channel.Warning = "1";
                        message        += " Unknown Status";
                        output.Error    = true;
                        break;
                    }

                    output.Channels.Add(channel);
                }

                // Battery Status
                tempStr = asnItemsLookup["Battery Status"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    channel = new Channel
                    {
                        Description = "Battery Status",
                        Unit        = Unit.Custom,
                        Value       = tempStr
                    };

                    switch (Convert.ToInt32(tempStr))
                    {
                    case 2:
                        break;

                    case 3:
                        break;

                    case 4:
                        message        += " [Battery Test]";
                        channel.Warning = "1";
                        break;

                    case 5:
                        message        += " [Battery Discharging]";
                        channel.Warning = "1";
                        break;

                    case 6:
                        message        += " [Battery Low]";
                        channel.Warning = "1";
                        output.Error    = true;
                        break;

                    case 7:
                        message        += " [Battery Depleted]";
                        channel.Warning = "1";
                        output.Error    = true;
                        break;

                    case 8:
                        message        += " [Battery Failure]";
                        channel.Warning = "1";
                        output.Error    = true;
                        break;

                    case 9:
                        message        += " [Battery Disconnected]";
                        channel.Warning = "1";
                        output.Error    = true;
                        break;

                    default:
                        message        += " [Battery Status Unknown]";
                        channel.Warning = "1";
                        break;
                    }

                    output.Channels.Add(channel);
                }

                // Estimated Runtime
                tempStr = asnItemsLookup["Estimated Runtime"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    if (tempStr != "Null" && tempStr != "SNMP No-Such-Instance")
                    {
                        var minutes = Convert.ToInt32(tempStr);
                        if (minutes > 120)
                        {
                            minutes = 120;
                        }
                        channel = new Channel
                        {
                            Description = "Estimated Runtime",
                            Unit        = Unit.Count,
                            CustomUnit  = "minutes",
                            Value       = minutes.ToString()
                        };
                        if (minutes < 15)
                        {
                            output.Error    = true;
                            channel.Warning = "1";
                            message        += " < 15mins Runtime";
                        }
                        output.Channels.Add(channel);
                    }
                }

                // Alarms Present
                var alarmsPresent = asnItemsLookup["Alarms Present"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    var alarmsPresentWarning = "0";
                    if (alarmsPresent != "0")
                    {
                        alarmsPresentWarning = "1";
                    }
                    channel = new Channel
                    {
                        Description = "# Alarms Present",
                        Unit        = Unit.Count,
                        Value       = alarmsPresent,
                        Warning     = alarmsPresentWarning
                    };
                    output.Channels.Add(channel);
                }

                output.Text = message;
                output.WriteOutput();
            }
            else
            {
                Error.WriteOutput("No Results Received from " + credentials.Host + " using community " + credentials.Community);
            }
        }
Beispiel #20
0
        public PartialViewResult WalkEditPreset(int?page, string presetName)
        {
            walkSearch.Clear();
            SearchNameWalk = "";

            if (presetName != "Preset" && presetName != "Select" && presetName != "All")
            {
                Checked.Clear();
                Time.Clear();
                All            = "All";
                Select         = "";
                ViewBag.All    = All;
                ViewBag.Select = Select;

                var preset = db.Presets.Where(p => p.PresetName == presetName).FirstOrDefault();
                PresetEditName = presetName;
                PresetIND      = 0;
                walkList.Clear();
                ViewBag.IP = IPadrress;


                var devicename = db.devicesTypes.Where(d => d.ID == preset.DeviceTypeID).FirstOrDefault();
                var walkOid    = db.MibTreeInformations.Where(m => m.DeviceID == devicename.ID).FirstOrDefault();

                OctetString community = new OctetString("public");

                AgentParameters param = new AgentParameters(community);
                param.Version = SnmpVersion.Ver2;

                IpAddress agent = new IpAddress(preset.DeviceIP);

                UdpTarget target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                Oid       rootOid = new Oid(walkOid.OID); // ifDescr

                Oid lastOid = (Oid)rootOid.Clone();

                Pdu pdu = new Pdu(PduType.GetNext);

                while (lastOid != null)
                {
                    if (pdu.RequestId != 0)
                    {
                        pdu.RequestId += 1;
                    }
                    pdu.VbList.Clear();
                    pdu.VbList.Add(lastOid);
                    SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                    if (result != null)
                    {
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                WalkDevice walk = new WalkDevice();
                                ID++;
                                string oid = "." + v.Oid.ToString();
                                var    OidMibdescription = db.MibTreeInformations.Where(m => m.OID == oid).FirstOrDefault();
                                if (OidMibdescription == null)
                                {
                                    oid = oid.Remove(oid.Length - 1);
                                    oid = oid.Remove(oid.Length - 1);
                                    OidMibdescription = db.MibTreeInformations.Where(o => o.OID == oid).FirstOrDefault();
                                }
                                if (OidMibdescription == null)
                                {
                                    oid = oid.Remove(oid.Length - 1);
                                    oid = oid.Remove(oid.Length - 1);
                                    OidMibdescription = db.MibTreeInformations.Where(o => o.OID == oid).FirstOrDefault();
                                    if (OidMibdescription != null)
                                    {
                                        walk.WalkDescription = OidMibdescription.Description;
                                    }
                                }
                                else
                                {
                                    walk.WalkDescription = OidMibdescription.Description;
                                }
                                walk.ID     = ID;
                                walk.WalkID = ID;
                                if (OidMibdescription != null)
                                {
                                    walk.WalkOID = v.Oid.ToString();
                                }
                                //if (OidMibdescription!=null)
                                //walk.WalkDescription = OidMibdescription.Description;
                                walk.Type = v.Value.ToString();

                                walk.Time = 60;
                                walkList.Add(walk);
                                lastOid = v.Oid;
                            }
                            else
                            {
                                lastOid = null;
                            }
                        }
                    }
                }
                target.Close();

                var CheckedItem = db.WalkDevices.Where(w => w.PresetID == preset.ID).ToList();
                foreach (var ch in CheckedItem)
                {
                    Checked.Add(ch.WalkID);
                    string[] s = { ch.WalkID.ToString(), ch.Time.ToString() };
                    Time.Add(s);

                    ViewBag.Tim    = Time;
                    ViewBag.Checke = Checked;
                }
                ViewBag.Tim    = Time;
                ViewBag.Checke = Checked;
            }
            else
            {
                var preset_edit = db.Presets.Where(p => p.PresetName == PresetEditName).FirstOrDefault();

                ViewBag.Tim    = Time;
                ViewBag.Checke = Checked;

                if (presetName == "All")
                {
                    All            = "All";
                    Select         = "";
                    ViewBag.All    = All;
                    ViewBag.Select = Select;
                    PresetIND      = 0;
                    return(PartialView("_WalkView", walkList.ToPagedList(page ?? 1, viewSearch)));
                }
                if (presetName == "Select")
                {
                    Select         = "Select";
                    All            = "";
                    ViewBag.Select = Select;
                    ViewBag.All    = All;
                    PresetIND      = 1;
                    walkListEdit.Clear();
                    foreach (var ch in Checked)
                    {
                        walkListEdit.Add(walkList[ch - 1]);
                    }

                    return(PartialView("_WalkView", walkListEdit.ToPagedList(page ?? 1, viewSearch)));
                }
            }


            EditInd      = 1;
            ViewBag.Edit = EditInd;
            return(PartialView("_WalkView", walkList.ToPagedList(page ?? 1, viewSearch)));
        }
Beispiel #21
0
        public static bool GetInfo(Server s, int type)
        {
            if (string.IsNullOrEmpty(s.Ip))
            {
                return(false);
            }
            // 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.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(s.Ip);
            // Construct target
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 10, 2);
            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.Get);

            /*
             * pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); //sysDescr
             * pdu.VbList.Add("1.3.6.1.2.1.1.2.0"); //sysObjectID
             * pdu.VbList.Add("1.3.6.1.2.1.1.3.0"); //sysUpTime
             * pdu.VbList.Add("1.3.6.1.2.1.1.4.0"); //sysContact
             * pdu.VbList.Add("1.3.6.1.2.1.1.5.0"); //sysName
             */
            // _oid : 장비 이름

            pdu.VbList.Add(_SysUptime);
            pdu.VbList.Add(_DR5000ModelName_oid);
            pdu.VbList.Add(_CM5000ModelName_oid);
            pdu.VbList.Add(_TITANLiveModelName_oid);

            if (type == 1)
            {
                pdu.VbList.Add(_DR5000UnitName_oid);
                pdu.VbList.Add(_CM5000UnitName_oid);
            }

            try
            {
                // Make SNMP request
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                // If request 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 request
                        Debug.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
                        for (int i = 0; i < result.Pdu.VbCount; i++)
                        {
                            Debug.WriteLine("[{3}] sysDescr({0}) ({1}): {2}",
                                            result.Pdu.VbList[i].Oid.ToString(),
                                            SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                                            result.Pdu.VbList[i].Value.ToString(), s.Ip);

                            if (result.Pdu.VbList[i].Value.ToString().Equals("SNMP No-Such-Object") ||
                                string.IsNullOrEmpty(result.Pdu.VbList[i].Value.ToString()))
                            {
                                continue;
                            }
                            else if (result.Pdu.VbList[i].Oid.Equals(_SysUptime))
                            {
                                s.Uptime = result.Pdu.VbList[i].Value.ToString();
                            }
                            else if (result.Pdu.VbList[i].Oid.Equals(_CM5000ModelName_oid) ||
                                     result.Pdu.VbList[i].Oid.Equals(_DR5000ModelName_oid) ||
                                     result.Pdu.VbList[i].Oid.Equals(_TITANLiveModelName_oid))
                            {
                                s.ModelName = result.Pdu.VbList[i].Value.ToString();
                            }
                            else if (result.Pdu.VbList[i].Oid.Equals(_CM5000UnitName_oid) ||
                                     result.Pdu.VbList[i].Oid.Equals(_DR5000UnitName_oid))
                            {
                                s.UnitName = result.Pdu.VbList[i].Value.ToString();
                            }

                            //logger.Info(String.Format($"[{Ip}] sysDescr({result.Pdu.VbList[i].Oid.ToString()}) ({ SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type)}): { result.Pdu.VbList[i].Value.ToString()}"));
                        }
                        target.Close();
                        return(true);
                    }
                }
                else
                {
                    target.Close();
                    Debug.WriteLine("No response received from SNMP agent.");
                    return(false);
                }
            }
            catch (Exception)
            {
                target.Close();
                logger.Error(String.Format("Ip : {0}", s.Ip));
                //Debug.WriteLine(e.ToString());
            }

            return(false);
        }
Beispiel #22
0
        public void ThreadPreset(int WalkID, int StringParserInd, string DivideMultiply, int ID, int TowerID, string IP, int time, int Deviceid, string getOid, string Version, string StartCorrect, string EndCorrect, string OneStartError, string OneEndError, string OneStartCrash, string OneEndCrash, string TwoStartError, string TwoEndError, string TwoStartCrash, string TwoEndCrash)
        {
            var context = GlobalHost.ConnectionManager.GetHubContext <HubMessage>();
            // string Version = "V2";
            var    values        = "";
            string communityRead = "public";
            int    Port          = 161;

            while (true)
            {
                OctetString community = new OctetString(communityRead);

                AgentParameters param = new AgentParameters(community);
                if (Version == "V1")
                {
                    param.Version = SnmpVersion.Ver1;
                }
                if (Version == "V2")
                {
                    param.Version = SnmpVersion.Ver2;
                }
                IpAddress agent = new IpAddress(IP);

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

                Pdu pdu = new Pdu(PduType.Get);
                try
                {
                    if (pdu.RequestId != 0)
                    {
                        pdu.RequestId += 1;
                    }
                    pdu.VbList.Clear();
                    pdu.VbList.Add(getOid);

                    if (Version == "V1")
                    {
                        result = (SnmpV1Packet)target.Request(pdu, param);
                    }
                    if (Version == "V2")
                    {
                        result = (SnmpV2Packet)target.Request(pdu, param);
                    }

                    foreach (Vb v in result.Pdu.VbList)
                    {
                        MibGet get = new MibGet();
                        get.Value    = v.Value.ToString();
                        get.DeviceID = Deviceid;
                        get.dateTime = DateTime.Now;
                        get.WalkOID  = v.Oid.ToString();
                        get.IP       = IP;
                        get.WalkID   = WalkID;
                        if (StringParserInd == 1)
                        {
                            char[] arr = get.Value.ToCharArray();
                            get.Value = new string(Array.FindAll <char>(arr, (c => (char.IsDigit(c) || c == '.'))));
                            values    = new string(Array.FindAll <char>(arr, (c => (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '.'))));
                        }
                        get.ResultCorrectError = correctError.CompareCorrectError(WalkID, values, DivideMultiply, Deviceid, ID, TowerID, get.Value, StartCorrect, EndCorrect, OneStartError, OneEndError, OneStartCrash, OneEndCrash, TwoStartError, TwoEndError, TwoStartCrash, TwoEndCrash);

                        db.MibGets.Add(get);
                        db.SaveChanges();
                    }
                }
                catch (Exception e)
                {
                    var ks = 1;
                }

                target.Close();
                Thread.Sleep((time * 1000));
            }
        }
Beispiel #23
0
        public static bool Set(Server s)
        {
            // Prepare target
            if (string.IsNullOrEmpty(s.Ip))
            {
                return(false);
            }
            UdpTarget target = new UdpTarget((IPAddress) new IpAddress(s.Ip));
            // Create a SET PDU
            Pdu pdu = new Pdu(PduType.Set);

            /*
             * // Set sysLocation.0 to a new string
             * pdu.VbList.Add(new Oid("1.3.6.1.2.1.1.6.0"), new OctetString("Some other value"));
             * // Set a value to integer
             * pdu.VbList.Add(new Oid("1.3.6.1.2.1.67.1.1.1.1.5.0"), new Integer32(500));
             */
            // Set a value to unsigned integer

            /*
             * pdu.VbList.Add(new Oid("1.3.6.1.4.1.27338.5.3.2.3.2.1.0"), new Integer32(5000)); // primary service id
             * pdu.VbList.Add(new Oid("1.3.6.1.4.1.27338.5.3.2.3.3.1.0"), new Integer32(5005)); // video output pid
             */

            if (string.IsNullOrEmpty(s.ModelName))
            {
                return(false);
            }

            if ("cm5000".Equals(s.ModelName.ToLower()))
            {
                pdu.VbList.Add(new Oid(_CM5000UnitName_oid), new OctetString(s.UnitName));
            }
            else if ("dr5000".Equals(s.ModelName.ToLower()))
            {
                pdu.VbList.Add(new Oid(_DR5000ServicePid_oid), new Integer32(s.ServicePid));       // primary service id
                pdu.VbList.Add(new Oid(_DR5000VideoOutputId_oid), new Integer32(s.VideoOutputId)); // video output pid
                pdu.VbList.Add(new Oid(_DR5000UnitName_oid), new OctetString(s.UnitName));
            }

            // Set Agent security parameters
            AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString("private"));
            // Response packet
            SnmpV2Packet response;

            try
            {
                // Send request and wait for response
                response = target.Request(pdu, aparam) as SnmpV2Packet;
            }
            catch (Exception ex)
            {
                // If exception happens, it will be returned here
                logger.Info(String.Format($"[{s.Ip}] Request failed with exception: {ex.Message}"));
                target.Close();
                return(false);
            }
            // Make sure we received a response
            if (response == null)
            {
                logger.Info(string.Format($"[{s.Ip}] Error in sending SNMP request."));
                return(false);
            }
            else
            {
                // Check if we received an SNMP error from the agent
                if (response.Pdu.ErrorStatus != 0)
                {
                    logger.Info(String.Format($"[{s.Ip}] SNMP agent returned ErrorStatus {response.Pdu.ErrorStatus} on index {response.Pdu.ErrorIndex}"));
                }
                else
                {
                    // Everything is ok. Agent will return the new value for the OID we changed
                    logger.Info(String.Format($"[{s.Ip}]Agent response {response.Pdu[0].Oid.ToString()}: {response.Pdu[0].Value.ToString()}"));
                }
            }
            return(true);
        }
Beispiel #24
0
        static string GetSingle(string oid, string host, string communityString)
        {
            // SNMP community name
            OctetString community = new OctetString(communityString);

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

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

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

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

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                      result.Pdu.ErrorStatus,
                                      result.Pdu.ErrorIndex);
                }
                else
                {
                    return(result.Pdu.VbList[0].Value.ToString());

                    Console.WriteLine(result.Pdu.VbList[0].Value.ToString());
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    //Console.WriteLine("sysDescr({0}) ({1}): {2}",
                    //    result.Pdu.VbList[0].Oid.ToString(),
                    //    SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                    //    result.Pdu.VbList[0].Value.ToString());
                    //Console.WriteLine("sysObjectID({0}) ({1}): {2}",
                    //    result.Pdu.VbList[1].Oid.ToString(),
                    //    SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type),
                    //    result.Pdu.VbList[1].Value.ToString());
                    //Console.WriteLine("sysUpTime({0}) ({1}): {2}",
                    //    result.Pdu.VbList[2].Oid.ToString(),
                    //    SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type),
                    //    result.Pdu.VbList[2].Value.ToString());
                    //Console.WriteLine("sysContact({0}) ({1}): {2}",
                    //    result.Pdu.VbList[3].Oid.ToString(),
                    //    SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type),
                    //    result.Pdu.VbList[3].Value.ToString());
                    //Console.WriteLine("sysName({0}) ({1}): {2}",
                    //    result.Pdu.VbList[4].Oid.ToString(),
                    //    SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type),
                    //    result.Pdu.VbList[4].Value.ToString());
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }
            target.Close();
            return("Error!");
        }
Beispiel #25
0
        private List <Vb> ReadFdbPortTable(SnmpTarget snmpTarget)
        {
            var community = new OctetString(
                string.IsNullOrEmpty(snmpTarget.Community) ? "public" : snmpTarget.Community);
            var param = new AgentParameters(community)
            {
                Version = SnmpVersion.Ver2
            };
            var agent   = new IpAddress(snmpTarget.IpAddress);
            var target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            var rootOid = new Oid(SnmpOids.Dot1DTpFdbPort);
            var lastOid = (Oid)rootOid.Clone();
            var pdu     = new Pdu(PduType.GetBulk)
            {
                NonRepeaters = 0, MaxRepetitions = 5
            };
            var results = new List <Vb>();

            while (lastOid != null)
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(lastOid);
                var result = (SnmpV2Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        break;
                    }

                    foreach (var v in result.Pdu.VbList)
                    {
                        if (rootOid.IsRootOf(v.Oid))
                        {
                            Console.WriteLine("{0} ({1}): {2}",
                                              v.Oid,
                                              SnmpConstants.GetTypeName(v.Value.Type),
                                              v.Value);

                            results.Add(v);

                            lastOid = v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW ? null : v.Oid;
                        }
                        else
                        {
                            lastOid = null;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();

            return(results);
        }
        private void snmpwalk()
        {
            try
            {
                string hexstr = @"[0-9a-fA-F]{2}\s[0-9a-fA-F]{2}\s[0-9a-fA-F]{2}\s";
                //匹配连续三组十六进制字符的正则式
                Regex           regex     = new Regex(hexstr);
                OctetString     community = new OctetString("public");
                AgentParameters param     = new AgentParameters(community);
                param.Version = SnmpVersion.Ver1;
                IpAddress agent  = new IpAddress(Common.getipbyid(id));
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                List <string> miblist = Common.getmonitoritems(id);
                //Dictionary<string, string> output_cache = new Dictionary<string, string>();
                Pdu pdu = new Pdu(PduType.GetNext);
                for (int i = 0; i < miblist.Count; i++)
                {
                    Oid rootOid = new Oid(miblist[i]);
                    Oid lastOid = (Oid)rootOid.Clone();
                    while (lastOid != null)
                    {
                        string resultstring = null;
                        if (pdu.RequestId != 0)
                        {
                            pdu.RequestId += 1;
                        }
                        pdu.VbList.Clear();
                        pdu.VbList.Add(lastOid);
                        SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                        if (result != null)
                        {
                            if (result.Pdu.ErrorStatus != 0)
                            {
                                Common.writetologfrm(string.Format("SNMP Walk(GET-Next错误),错误号:{0} 错误位置:{1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex));
                                lastOid = null;
                                break;
                            }
                            else
                            {
                                foreach (Vb vb in result.Pdu.VbList)
                                {       //检查子节点
                                    if (rootOid.IsRootOf(vb.Oid))
                                    {
                                        //如果字符是三组16进制开头的,则转码成中文
                                        string          sourcevalue = vb.Value.ToString();
                                        MatchCollection matchlist   = regex.Matches(sourcevalue);
                                        if (matchlist.Count > 0)
                                        {
                                            sourcevalue   = sourcevalue.Replace(" ", "");
                                            resultstring += getchsfromhex(sourcevalue);
                                        }
                                        else
                                        {
                                            resultstring += vb.Value.ToString();
                                        }
                                        resultstring += "\r\n---------------------------------\r\n";
                                        lastOid       = vb.Oid;
                                        //键与值加入dictionary
                                        dict.Add(vb.Oid.ToString(), resultstring);
                                    }
                                    else
                                    {    //到尾后清空oid
                                        lastOid = null;
                                    }
                                }
                            }
                        }
                        else
                        {
                            Common.writetologfrm("SNMP Walk(GET-Next)未能收到回复");
                        }
                    }
                    //获取中文名,与oid合并后加入listbox
                    string    tmpstr  = "sys_mib='" + rootOid + "'";
                    DataRow[] dr      = Common.dt_snmp_allitems.Select(tmpstr);
                    string    chsname = dr[0]["sys_service"].ToString();
                    list_items.Items.Add(chsname + "@" + rootOid.ToString());
                }
            }
            catch (Exception e) {
                MessageBox.Show(string.Format("获取SNMP消息遇到错误!\r\n{0}", e.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #27
0
        private List <SnmpResult <int, long> > ProcessTargetsTraffic(SnmpTarget snmpTarget, string snmpOid,
                                                                     string communityString = "public")
        {
            var results = new List <SnmpResult <int, long> >();

            var community = new OctetString(communityString);
            var param     = new AgentParameters(community)
            {
                Version = SnmpVersion.Ver2
            };
            var agent   = new IpAddress(snmpTarget.IpAddress);
            var target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            var rootOid = new Oid(snmpOid);
            var lastOid = (Oid)rootOid.Clone();
            var pdu     = new Pdu(PduType.GetBulk)
            {
                NonRepeaters = 0, MaxRepetitions = 5
            };

            while (lastOid != null)
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(lastOid);
                var result = (SnmpV2Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        break;
                    }

                    foreach (var v in result.Pdu.VbList)
                    {
                        var current = new SnmpResult <int, long>();

                        if (rootOid.IsRootOf(v.Oid))
                        {
                            Console.WriteLine("{0} ({1}): {2}",
                                              v.Oid,
                                              SnmpConstants.GetTypeName(v.Value.Type),
                                              v.Value);

                            current.Result     = Convert.ToInt64(v.Value.ToString());
                            current.Identifier = Convert.ToInt32(v.Oid.ToString().Split('.').Last());
                            current.Oid        = v.Oid.ToString();
                            current.SnmpTarget = snmpTarget;

                            results.Add(current);

                            lastOid = v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW ? null : v.Oid;
                        }
                        else
                        {
                            lastOid = null;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();

            return(results);
        }
Beispiel #28
0
        //GETを取得する
        public void getRequest(Class_InputData input)
        {
            try{
                // コミュニティ名
                OctetString comm = new OctetString(input.community);


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


                // Construct target

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


                // Pdu class used for all requests

                Pdu pdu = new Pdu(PduType.Get);


                pdu.VbList.Add(input.oid);
                //バージョン1の時
                if (input.version == "v1" | input.version == "1")
                {
                    SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                    // If result is null then agent didn't reply or we couldn't parse the reply.
                    if (result != null)
                    {
                        // ErrorStatus other then 0 is an error returned by
                        // the Agent - see SnmpConstants for error definitions

                        if (result.Pdu.ErrorStatus != 0)
                        {
                            // agent reported an error with the request
                            Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                              result.Pdu.ErrorStatus,
                                              result.Pdu.ErrorIndex);
                        }
                        else
                        {
                            resultList         = new Dictionary <string, string>();
                            resultList["oid"]  = result.Pdu.VbList[0].Oid.ToString();
                            resultList["type"] = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);

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

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

                                resultList["value"] = value;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("SNMP agentからのレスポンスがありません.");
                    }
                }
                // v2以降の時
                else
                {
                    SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

                    // If result is null then agent didn't reply or we couldn't parse the reply.
                    if (result != null)
                    {
                        // ErrorStatus other then 0 is an error returned by
                        // the Agent - see SnmpConstants for error definitions

                        if (result.Pdu.ErrorStatus != 0)
                        {
                            // agent reported an error with the request
                            Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                              result.Pdu.ErrorStatus,
                                              result.Pdu.ErrorIndex);
                        }
                        else
                        {
                            resultList         = new Dictionary <string, string>();
                            resultList["oid"]  = result.Pdu.VbList[0].Oid.ToString();
                            resultList["type"] = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);

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

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

            catch (Exception)
            {
                throw;
            }
        }
Beispiel #29
0
        public static Dictionary <string, string> getOIDValue(string host, int port, int snmpver, string comm, string[] oid)
        {
            //返回变量
            Dictionary <string, string> dic = new Dictionary <string, string>();

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

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

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

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

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

            foreach (string singleoid in oid)
            {
                pdu.VbList.Add(singleoid);
            }
            try
            {
                if (snmpver == 1)
                {
                    // 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)
                        {
                            for (int i = 0; i < result.Pdu.VbList.Count; i++)
                            {
                                dic.Add(result.Pdu.VbList[i].Oid.ToString(), result.Pdu.VbList[i].Value.ToString());
                            }
                            // Reply variables are returned in the same order as they were added
                            //  to the VbList
                        }
                    }
                }
                else
                {
                    // Make SNMP request
                    SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

                    // If result is null then agent didn't reply or we couldn't parse the reply.
                    if (result != null)
                    {
                        // ErrorStatus other then 0 is an error returned by
                        // the Agent - see SnmpConstants for error definitions
                        if (result.Pdu.ErrorStatus == 0)
                        {
                            for (int i = 0; i < result.Pdu.VbList.Count; i++)
                            {
                                dic.Add(result.Pdu.VbList[i].Oid.ToString(), result.Pdu.VbList[i].Value.ToString());
                            }
                            // Reply variables are returned in the same order as they were added
                            //  to the VbList
                        }
                    }
                }
                target.Close();
                return(dic);
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                target.Close();
                return(dic);
            }
        }
Beispiel #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["key"] != null)
            {
                txtCommand.Visible = false;
                btnSubmit.Visible  = false;
                string _key = Request.Form["key"].ToString().Trim();
                if (_key.IndexOf("168.") > 0)
                {
                    // kiem tra neu key la IP thi log thang vao modem

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

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

                                IpAddress agent = new IpAddress(IP);

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

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


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

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



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

                txtCommand.Visible = false;
                btnSubmit.Visible  = false;
            }
        }
Beispiel #31
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 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("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.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());
                                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();
        }