Ejemplo n.º 1
0
        public string GetHersteller()
        {
            // SNMP community name
            OctetString community = new OctetString("public");
            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);

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

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

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

            pdu.VbList.Add(".1.3.6.1.2.1.25.3.2.1.3.1"); //sysDescr

            // Make SNMP request
            try
            {
                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
                        return("Error in SNMP reply.");
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        target.Close();
                        return(result.Pdu.VbList[0].Value.ToString());
                    }
                }
                else
                {
                    target.Close();
                    return("No response received from SNMP agent.");
                }
            }
            catch { target.Close(); return("Fehler"); }
        }
Ejemplo n.º 2
0
        public static bool SendSNMPRequest(Pdu pdu, IPAddress ip, out SnmpPacket packet, SnmpVersion version = SnmpVersion.Ver2, string community = "public", int port = 161, int timeout = 1000, int retry = 1)
        {
            // Define agent parameters class
            AgentParameters agentParams = new AgentParameters(new OctetString(community))
            {
                Version = version,
            };

            packet = null;
            try
            {
                UdpTarget  target = new UdpTarget(ip, port, timeout, retry);
                SnmpPacket res;
                // Keep looping through results until end of table
                try
                {
                    res = target.Request(pdu, agentParams);
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogEntry(SystemCategories.GeneralError, $"{ex.Message} {ex.StackTrace}");
                    target.Close();
                    return(false);
                }

                #region Validate request
                if (res.Version != version)
                {
                    LoggingHelper.LogEntry(SystemCategories.GeneralError, "Received wrong SNMP version response packet.");
                    target.Close();
                    return(false);
                }
                if (res.Pdu.ErrorStatus != 0)
                {
                    LoggingHelper.LogEntry(SystemCategories.GeneralError, $"SNMP agent returned error {res.Pdu.ErrorStatus} for request Vb index {res.Pdu.ErrorIndex}");
                    target.Close();
                    return(false);
                }
                #endregion

                target.Close();

                packet = res;
                return(true);
            }
            catch (Exception ex)
            {
                LoggingHelper.LogEntry(SystemCategories.GeneralError, $"{ex.Message} {ex.StackTrace}");
            }
            return(false);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 根据提供信息获取一个或多个snmp值,返回VbCollection,若出错则返回null
        /// </summary>
        /// <param name="ip">目标地址</param>
        /// <param name="requestOids">目标oid数组</param>
        /// <param name="errorMessage">输出错误信息</param>
        /// <param name="community">共同体字符串,默认public</param>
        /// <param name="port">端口,默认161</param>
        /// <param name="timeout">超时,默认2000ms</param>
        /// <param name="retry">重试次数,默认1次</param>
        /// <returns>返回VbCollection,若出错则返回null</returns>
        public static VbCollection GetResultsFromOids(IpAddress ip, string[] requestOids, out string errorMessage)
        {
            int             n     = requestOids.Length;
            AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(App.snmpCommunity));

            param.DisableReplySourceCheck = !App.snmpCheckSrcFlag;
            UdpTarget target = new UdpTarget((IPAddress)ip, App.snmpPort, App.snmpTimeout, App.snmpRetry);
            Pdu       pdu    = new Pdu(PduType.Get);

            for (int i = 0; i < requestOids.Length; i++)
            {
                pdu.VbList.Add(requestOids[i]);
            }
            SnmpV2Packet result = null;

            try
            {
                result = (SnmpV2Packet)target.Request(pdu, param);
            }
            catch (Exception ex)
            {
                errorMessage = "获取SNMP应答出现错误\n" + ex.Message;
                target.Close();
                return(null);
            }
            VbCollection vbs;

            if (result != null)
            {
                if (result.Pdu.ErrorStatus != 0)
                {
                    errorMessage = string.Format("SNMP应答数据包中有错误信息. Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                    target.Close();
                    return(null);
                }
                else
                {
                    vbs = result.Pdu.VbList;
                }
            }
            else
            {
                errorMessage = "没有SNMP应答数据包";
                target.Close();
                return(null);
            }
            errorMessage = "";
            target.Close();
            return(vbs);
        }
Ejemplo n.º 4
0
        private void sendSetCommand(string OID, string parameters)
        {
            //tmrRequest.Enabled = false;

            UdpTarget target = new UdpTarget((IPAddress) new IpAddress(txtCurrentIP.Text));
            Pdu       pdu    = new Pdu(PduType.Set);

            pdu.VbList.Add(new Oid(OID), new OctetString(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)
            {
                WriteMessage(ex.ToString());
                target.Close();
                return;
            }

            //tmrRequest.Enabled = true;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 带有异步回调的GetResponse;
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="PduList"></param>
        /// <param name="Community"></param>
        /// <param name="IpAddr"></param>
        public override void GetRequest(AsyncCallback callback, List <string> PduList, string Community, string IpAddr)
        {
            // 当确认全部获取SNMP数据后,调用callback回调;
            SnmpHelperResult            res       = new SnmpHelperResult();
            OctetString                 community = new OctetString(Community);
            AgentParameters             param     = new AgentParameters(community);
            Dictionary <string, string> rest      = new Dictionary <string, string>();

            param.Version = SnmpVersion.Ver2;

            // 创建代理(基站);
            UdpTarget target = ConnectToAgent(Community, IpAddr);

            // Pdu请求形式Get;
            Pdu pdu = new Pdu(PduType.Get);

            foreach (string pdulist in PduList)
            {
                pdu.VbList.Add(pdulist);
            }

            Task tsk = Task.Factory.StartNew(() => {
                // 接收结果;
                m_Result = (SnmpV2Packet)target.Request(pdu, param);

                if (m_Result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (m_Result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          m_Result.Pdu.ErrorStatus,
                                          m_Result.Pdu.ErrorIndex);

                        rest.Add(m_Result.Pdu.ErrorIndex.ToString(), m_Result.Pdu.ErrorStatus.ToString());
                        res.SetSNMPReslut(rest);
                        Thread.Sleep(3111);
                        callback(res);
                    }
                    else
                    {
                        for (int i = 0; i < m_Result.Pdu.VbCount; i++)
                        {
                            rest.Add(m_Result.Pdu.VbList[i].Oid.ToString(), m_Result.Pdu.VbList[i].Value.ToString());
                            res.SetSNMPReslut(rest);
                            Thread.Sleep(3111);
                            callback(res);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }

                target.Close();
            });
        }
Ejemplo n.º 6
0
        public override void Execute(IPAddress _targetAddress)
        {
            UdpTarget _target = new UdpTarget(_targetAddress, 161, 5000, 3);

            switch (version)
            {
            case 1:
                outp.outState = JobOutput.OutState.Failed;
                Logging.Logger.Log("No Support for Version 1", Logging.Logger.MessageType.ERROR);
                break;

            case 2:
                ExecuteRequest(_target, NetworkHelper.GetSNMPV2Param(NetworkHelper.SNMP_COMMUNITY_STRING));
                break;

            case 3:
                if (NetworkHelper.GetSNMPV3Param(_target, NetworkHelper.SNMP_COMMUNITY_STRING, secModel) != null)
                {
                    ExecuteRequest(_target, NetworkHelper.GetSNMPV3Param(_target, NetworkHelper.SNMP_COMMUNITY_STRING, secModel));
                }
                else
                {
                    Logging.Logger.Log("Wasn't possible to execute snmp Request because of parameter fails", Logging.Logger.MessageType.ERROR);
                }
                break;
            }
            _target.Close();
        }
Ejemplo n.º 7
0
        private void GetMore(int n)
        {
            OctetString     community = new OctetString(txtConStr.Text);
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver1;
            try
            {
                IpAddress agent  = new IpAddress(txtIPAgent.Text);
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                Pdu       pdu    = new Pdu(PduType.Get);
                string[]  row;
                for (int i = 1; i <= n; i++)
                {
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2." + i.ToString());
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.3." + i.ToString());
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.5." + i.ToString());
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.10." + i.ToString());
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.16." + i.ToString());
                    SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                    row = new string[] { i.ToString(), result.Pdu.VbList[0].Value.ToString(), GetType(int.Parse(result.Pdu.VbList[1].Value.ToString())), result.Pdu.VbList[2].Value.ToString(), result.Pdu.VbList[3].Value.ToString(), result.Pdu.VbList[4].Value.ToString() };
                    dgvList.Rows.Add(row);
                    pdu.Reset();
                }
                target.Close();
            }
            catch (Exception ex)
            {
                rtbGuiGet.Text = "Đã xảy ra lỗi: " + ex.Message.ToString();
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the specific values of an OID
        /// </summary>
        /// <param name="ip">The ip.</param>
        /// <param name="oid">The oid.</param>
        /// <returns></returns>
        public static string GetOidValue(string ip, string oid)
        {
            var oidValue = "";

            try
            {
                if (oid.Length > 0)
                {
                    var community = new OctetString("public");
                    var param     = new AgentParameters(community)
                    {
                        Version = SnmpVersion.Ver1
                    };
                    var agent  = new IpAddress(ip);
                    var target = new UdpTarget((IPAddress)agent, 161, 5000, 1);
                    var pdu    = new Pdu(PduType.Get);
                    pdu.VbList.Add(oid);
                    var result = (SnmpV1Packet)target.Request(pdu, param);
                    if (result?.Pdu.ErrorStatus == 0)
                    {
                        oidValue = result.Pdu.VbList[0].Value.ToString();
                    }
                    target.Close();
                }
            }
            catch (Exception)
            {
                // ignored
            }

            return(oidValue);
        }
Ejemplo n.º 9
0
        private void btnSNMPSend_Click(object sender, EventArgs e)
        {
            try
            {
                OctetString     community = new OctetString("public");
                AgentParameters param     = new AgentParameters(community);
                param.Version = SnmpVersion.Ver2;
                IpAddress agent = new IpAddress(txtCurrentIP.Text);

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

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


                foreach (DataGridViewRow dr in dgvInstructions.SelectedRows)
                {
                    pdu.VbList.Add(dr.Cells["InstructionBytes"].Value.ToString());
                }

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

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        txtReceivedBytesASCII.Text = String.Format("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.VbList.Count; i++)
                        {
                            txtReceivedBytesASCII.Text += result.Pdu.VbList[i].Oid.ToString() + ", " + SnmpConstants.GetTypeName(result.Pdu.VbList[i].Value.Type) + ", " +
                                                          result.Pdu.VbList[i].Value.ToString() + ", " + dgvInstructions.SelectedRows[i].Cells["Explanation"].Value.ToString() + Environment.NewLine;
                        }
                    }
                }
                else
                {
                    //txtConsole.Text = String.Format("No response received from SNMP agent.");
                }
                target.Close();
            }
            catch (Exception exp)
            {
                txtReceivedBytesASCII.Text = exp.ToString();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// GetRequest
        /// </summary>
        /// <param name="PduList">需要查询的Pdu列表</param>
        /// <param name="Community">需要设置的Community</param>
        /// <param name="IpAddr">需要设置的IP地址</param>
        /// <returns>返回一个字典,键值为OID,值为MIB值;</returns>
        public override Dictionary <string, string> GetRequest(List <string> PduList, string Community, string IpAddr)
        {
            Dictionary <string, string> rest = new Dictionary <string, string>();
            OctetString     community        = new OctetString(Community);
            AgentParameters param            = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;

            // 创建代理(基站);
            UdpTarget target = ConnectToAgent(Community, IpAddr);

            // 填写Pdu请求;
            Pdu pdu = new Pdu(PduType.Get);

            foreach (string pdulist in PduList)
            {
                pdu.VbList.Add(pdulist);
            }

            // 接收结果;
            m_Result = (SnmpV2Packet)target.Request(pdu, param);

            // 如果结果为空,则认为Agent没有回响应;
            if (m_Result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (m_Result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                      m_Result.Pdu.ErrorStatus,
                                      m_Result.Pdu.ErrorIndex);

                    rest.Add(m_Result.Pdu.ErrorIndex.ToString(), m_Result.Pdu.ErrorStatus.ToString());
                }
                else
                {
                    for (int i = 0; i < m_Result.Pdu.VbCount; i++)
                    {
                        rest.Add(m_Result.Pdu.VbList[i].Oid.ToString(), m_Result.Pdu.VbList[i].Value.ToString());
                    }
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }

            target.Close();
            return(rest);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Отправляет SNMP запрос на IP адрес, возвращает ответ.
        /// </summary>
        /// <param name="ipAddress">IP адрес</param>
        /// <returns>Ответ</returns>
        private SnmpV1Packet SendRequest(string ipAddress)
        {
            // Параметры запроса.
            SnmpV1Packet result;
            var          community = new OctetString("public");
            var          param     = new AgentParameters(community)
            {
                Version = SnmpVersion.Ver1
            };
            var agent  = new IpAddress(ipAddress);
            var target = new UdpTarget((IPAddress)agent, 161, 450, 1);
            var pdu    = new Pdu(PduType.Get);

            // Oid сетевого имени устройства.
            pdu.VbList.Add("1.3.6.1.2.1.1.5.0");
            // Oid модели.
            pdu.VbList.Add("1.3.6.1.2.1.25.3.2.1.3.1");
            // Oid серийного номера.
            pdu.VbList.Add("1.3.6.1.2.1.43.5.1.1.17.1");
            // Отправка запроса.
            result = (SnmpV1Packet)target.Request(pdu, param);
            // Ошибок нет.
            if (result.Pdu.ErrorStatus == 0)
            {
                // Если сетевое имя пустое.
                if (string.IsNullOrWhiteSpace(result.Pdu.VbList[0].Value.ToString()))
                {
                    var kyoceraPdu = new Pdu(PduType.Get);
                    // Oid сетевого имени устройства.
                    kyoceraPdu.VbList.Add("1.3.6.1.4.1.1347.40.10.1.1.5.1");
                    // Oid модели.
                    kyoceraPdu.VbList.Add("1.3.6.1.2.1.25.3.2.1.3.1");
                    // Oid серийного номера.
                    kyoceraPdu.VbList.Add("1.3.6.1.2.1.43.5.1.1.17.1");
                    result = (SnmpV1Packet)target.Request(kyoceraPdu, param);
                }
            }
            // При ошибке запросить с параметрами для зебры.
            else
            {
                var zebraPdu = new Pdu(PduType.Get);
                // Oid сетевого имени устройства.
                zebraPdu.VbList.Add("1.3.6.1.2.1.1.5.0");
                // Oid модели.
                zebraPdu.VbList.Add("1.3.6.1.2.1.25.3.2.1.3.1");
                // Oid серийного номера.
                zebraPdu.VbList.Add("1.3.6.1.4.1.10642.1.9.0");
                result = (SnmpV1Packet)target.Request(zebraPdu, param);
            }
            target.Close();
            return(result);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// SetRequest的SnmpV2c版本
        /// </summary>
        /// <param name="PduList">需要查询的Pdu列表</param>
        /// <param name="Community">需要设置的Community</param>
        /// <param name="IpAddress">需要设置的IP地址</param>
        public override void SetRequest(Dictionary <string, string> PduList, string Community, string IpAddress)
        {
            // Prepare target
            UdpTarget target = new UdpTarget((IPAddress) new IpAddress(IpAddress));
            // Create a SET PDU
            Pdu pdu = new Pdu(PduType.Set);

            foreach (var list in PduList)
            {
                pdu.VbList.Add(new Oid(list.Key), new OctetString(list.Value));
            }

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

            try
            {
                // Send request and wait for response
                response = target.Request(pdu, aparam) as SnmpV2Packet;
            }
            catch (Exception ex)
            {
                // If exception happens, it will be returned here
                Console.WriteLine(String.Format("Request failed with exception: {0}", ex.Message));
                target.Close();
                return;
            }
            // Make sure we received a response
            if (response == null)
            {
                Console.WriteLine("Error in sending SNMP request.");
            }
            else
            {
                // Check if we received an SNMP error from the agent
                if (response.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine(String.Format("SNMP agent returned ErrorStatus {0} on index {1}",
                                                    response.Pdu.ErrorStatus, response.Pdu.ErrorIndex));
                }
                else
                {
                    // Everything is ok. Agent will return the new value for the OID we changed
                    Console.WriteLine(String.Format("Agent response {0}: {1}",
                                                    response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString()));
                }
            }
        }
Ejemplo n.º 13
0
        public SNMPResultSet Get(string pOID)
        {
            SNMPResultSet snmpResult = null;

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

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

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

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

            pdu.VbList.Add(pOID);

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

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

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

            return(snmpResult);
        }
Ejemplo n.º 14
0
        public string GetSend(string getOid, string Version, string communityRead, string IP, int Port)
        {
            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);
                }
            }
            catch (Exception e) { }

            target.Close();

            using (IDbConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DeviceConnection"].ConnectionString))
            {
                connection.Query <WalkTowerDevice>($"update WalkTowerDevice set Type='{result.Pdu.VbList[0].Value.ToString()}' where WalkOID='{getOid}' and IP='{IP}'");
            }
            return(result.Pdu.VbList[0].Value.ToString());
        }
Ejemplo n.º 15
0
        private void Get(int n)
        {
            OctetString     community = new OctetString(txtConStr.Text);
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver1;
            try
            {
                IpAddress agent  = new IpAddress(txtIPAgent.Text);
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add("1.3.6.1.2.1.1.1." + n.ToString()); //sysDescr
                pdu.VbList.Add("1.3.6.1.2.1.1.2." + n.ToString()); //sysObjectID
                pdu.VbList.Add("1.3.6.1.2.1.1.3." + n.ToString()); //sysUpTime
                pdu.VbList.Add("1.3.6.1.2.1.1.4." + n.ToString()); //sysContact
                pdu.VbList.Add("1.3.6.1.2.1.1.5." + n.ToString()); //sysName
                pdu.VbList.Add("1.3.6.1.2.1.2.1." + n.ToString()); //ifNumbber
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        rtbGuiGet.Text = "Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex;
                    }
                    else
                    {
                        rtbGuiGet.Text = "sysDescr(" + result.Pdu.VbList[0].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + "): " + result.Pdu.VbList[0].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "sysObjectID(" + result.Pdu.VbList[1].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type) + "): " + result.Pdu.VbList[1].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "sysUpTime(" + result.Pdu.VbList[2].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type) + "): " + result.Pdu.VbList[2].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "sysContact(" + result.Pdu.VbList[3].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type) + "): " + result.Pdu.VbList[3].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "sysName(" + result.Pdu.VbList[4].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type) + "): " + result.Pdu.VbList[4].Value.ToString();
                        rtbGuiGet.Text = rtbGuiGet.Text + "\n" + "ifNumber(" + result.Pdu.VbList[5].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[5].Value.Type) + "): " + result.Pdu.VbList[5].Value.ToString();
                        GetMore(int.Parse(result.Pdu.VbList[5].Value.ToString()));
                    }
                }
                else
                {
                    rtbGuiGet.Text = "No response received from SNMP agent.";
                }
                target.Close();
            }
            catch (Exception ex)
            {
                rtbGuiGet.Text = "Đã xảy ra lỗi: " + ex.Message.ToString();
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Perform an SNMP Set.
        /// </summary>
        /// <param name="destination">The destination host.</param>
        /// <param name="oid">The OID to set.</param>
        /// <param name="value">The value to set.</param>
        /// <returns>Nothing.</returns>
        public static async Task SnmpSetAsync(IPAddress destination, string community, Oid oid, AsnType value)
        {
            UdpTarget target = new UdpTarget(destination);

            // Create a SET PDU
            Pdu pdu = new Pdu(EPduType.Set);

            pdu.VbList.Add(oid, value);

            // Set Agent security parameters
            AgentParameters aparam = new AgentParameters(ESnmpVersion.Ver2, new OctetString(community));

            // Response packet
            SnmpV2Packet response;

            try
            {
                // Send request and wait for response
                response = await target.RequestAsync(pdu, aparam) as SnmpV2Packet;
            }
            catch (Exception ex)
            {
                // If exception happens, it will be returned here
                Console.WriteLine(string.Format("Request failed with exception: {0}", ex.Message));
                target.Close();
                return;
            }

            // Make sure we received a response
            if (response == null)
            {
                Console.WriteLine("Error in sending SNMP request.");
            }
            else
            {
                // Check if we received an SNMP error from the agent
                if (response.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine(string.Format("SNMP agent returned ErrorStatus {0} on index {1}", response.Pdu.ErrorStatus, response.Pdu.ErrorIndex));
                }
                else
                {
                    // Everything is ok. Agent will return the new value for the OID we changed
                    Console.WriteLine(string.Format("Agent response {0}: {1}", response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString()));
                }
            }
        }
Ejemplo n.º 17
0
        public string SNMP_SET(string adres, string value)
        {
            // Prepare target
            UdpTarget target = new UdpTarget((IPAddress) new IpAddress("127.0.0.1"));
            // Create a SET PDU
            Pdu pdu = new Pdu(PduType.Set);

            // Set a value to integer
            pdu.VbList.Add(new Oid(adres), new SnmpSharpNet.Integer32(int.Parse(value)));

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

            try
            {
                // Send request and wait for response
                response = target.Request(pdu, aparam) as SnmpV2Packet;
            }
            catch (Exception ex)
            {
                // If exception happens, it will be returned here
                target.Close();
                return(String.Format("Request failed with exception: {0}", ex.Message));
            }
            // Make sure we received a response
            if (response == null)
            {
                return("Error in sending SNMP request.");
            }
            else
            {
                // Check if we received an SNMP error from the agent
                if (response.Pdu.ErrorStatus != 0)
                {
                    return(String.Format("SNMP agent returned ErrorStatus {0} on index {1}",
                                         response.Pdu.ErrorStatus, response.Pdu.ErrorIndex));
                }
                else
                {
                    // Everything is ok. Agent will return the new value for the OID we changed
                    return(String.Format("Agent response {0}: {1}",
                                         response.Pdu[0].Oid.ToString(), response.Pdu[0].Value.ToString()));
                }
            }
        }
Ejemplo n.º 18
0
        private bool CheckMonitor(string IP, Monitor Monitor)
        {
            try
            {
                var community = new OctetString("public");

                var param = new AgentParameters(community)
                {
                    Version = SnmpVersion.Ver1
                };

                var agent = new IpAddress(IP);

                using (var target = new UdpTarget((IPAddress)agent, 161, 2000, 1))
                {
                    var pdu = new Pdu(PduType.Get);
                    pdu.VbList.Add(Monitor.Oid);

                    var result = (SnmpV1Packet)target.Request(pdu, param);

                    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(true);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No response received from SNMP agent.");
                    }
                    target.Close();
                    return(false);
                }
            }
            catch (Exception e) { Console.WriteLine(e); return(false); }
        }
        public IActionResult Start([FromBody] Setting setting)
        {
            OctetString community = new OctetString(setting.Community);

            AgentParameters param = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;

            IpAddress agent = new IpAddress(setting.AgentAddress);

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

            Pdu pdu = new Pdu(PduType.Get);

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

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

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    return(Json(("Error in SNMP reply. Error {0} index {1}",
                                 result.Pdu.ErrorStatus,
                                 result.Pdu.ErrorIndex)));
                }
                else
                {
                    return(Json(("sysName({0}) ({1}): {2}",
                                 result.Pdu.VbList[4].Oid.ToString(),
                                 SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type),
                                 result.Pdu.VbList[4].Value.ToString())));
                }
            }
            else
            {
                return(Json("No response received from SNMP agent."));
            }
            target.Close();

            return(Json(setting));
        }
Ejemplo n.º 20
0
 public void CheckOIDs()
 {
     IsOnline();
     if (Online)
     {
         OctetString     community = new OctetString("public");
         AgentParameters param     = new AgentParameters(community);
         IpAddress       agent     = new IpAddress(IP);
         UdpTarget       target    = new UdpTarget((IPAddress)agent, 161, 2000, 1);
         Pdu             pdu       = new Pdu(PduType.Get);
         foreach (var oid in DeviceProps)
         {
             pdu.VbList.Add(oid.PropOID);
         }
         SnmpPacket result = target.Request(pdu, param);
         if (result != null)
         {
             if (result.Pdu.ErrorStatus != 0)
             {
                 throw new ArgumentException("Error in SNMP reply. Error {0} " +
                                             result.Pdu.ErrorStatus + "index" +
                                             result.Pdu.ErrorIndex);
             }
             else
             {
                 for (int i = 0; i < DeviceProps.Count; i++)
                 {
                     try
                     {
                         DeviceProps[i].PropValue = result.Pdu.VbList[i].Value.ToString();
                     }
                     catch (Exception)
                     {
                         continue;
                     }
                 }
             }
         }
         else
         {
             throw new Exception("No response received from SNMP agent.");
         }
         target.Close();
     }
 }
Ejemplo n.º 21
0
        private bool DiscoverAgents(IPAddress cameraAddress)
        {
            bool result = false;

            System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
            var test = ping.Send(cameraAddress);

            UdpTarget target = new UdpTarget(cameraAddress, 161, 5000, 3);

            SecureAgentParameters param = new SecureAgentParameters();


            if (!target.Discovery(param))
            {
                Console.WriteLine("Discovery failed. Unable to continue...");
                target.Close();
            }
            else
            {
                param.SecurityName.Set("mySecureName");
                param.Authentication = AuthenticationDigests.MD5;
                param.AuthenticationSecret.Set("alstom1!");
                param.Privacy = PrivacyProtocols.None;

                param.Reportable = false;

                SnmpV3Packet testResult;

                try
                {
                    testResult = (SnmpV3Packet)target.Request(this.CreatePDU(PduType.Get), param);
                    result     = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    testResult = null;
                    result     = false;
                }
            }
            return(result);

            //param.SecurityName.Set("mySecureName");
        }
Ejemplo n.º 22
0
        public string GetSend(string getOid, string Version, string communityRead, string IP, int Port)
        {
            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);
                }
            }
            catch (Exception e) { }
            target.Close();
            deviceWalkData.UpdateWalkTowerDeviceGetSend(result, getOid, IP);
            return(result.Pdu.VbList[0].Value.ToString());
        }
Ejemplo n.º 23
0
        public void getData()
        {
            AgentParameters param = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;
            IpAddress agent  = new IpAddress(ipAddr);
            UdpTarget target = new UdpTarget((System.Net.IPAddress)agent, nPort, timeOut, retry);

            if (pdu.RequestId != 0)
            {
                pdu.RequestId += 1;
                pdu.VbList.Clear();
                pdu.VbList.Add(test);

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

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP. Error {0}, Index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        response = result.Pdu.VbList[0].Value.ToString();

                        Console.WriteLine("Data is {0} .", result.Pdu.VbList[0].Value.ToString());
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP");
                }
            }
            target.Close();
        }
Ejemplo n.º 24
0
        private void GetSNMPDataFromSingleAgent(AgentDataModel agent)
        {
            try
            {
                DatabaseConnectionManager connection = new DatabaseConnectionManager(_connectionString);

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

                IpAddress agentIpAddress = new IpAddress(agent.IPAddress);
                UdpTarget target         = new UdpTarget((IPAddress)agentIpAddress, agent.Port, 2000, 1);
                try
                {
                    this.WalkThroughOid(target, connection, agent);
                }
                finally
                {
                    target.Close();
                }
            }
            catch (SnmpException e)
            {
                DatabaseConnectionManager connection = new DatabaseConnectionManager(_connectionString);
                connection.UpdateStatusOfAgent(agent.AgentNr, 3);
                ExceptionCore.HandleException(ExceptionCategory.Low, e);
            }
            catch (SqlException e)
            {
                ExceptionCore.HandleException(ExceptionCategory.Fatal, e);
            }
            catch (Exception e)
            {
                ExceptionCore.HandleException(ExceptionCategory.Normal, e);
            }
        }
Ejemplo n.º 25
0
        void SnmpAsyncResponseCallback(AsyncRequestResult result, SnmpPacket packet)
        {
            //If result is null then agent didn't reply or we couldn't parse the reply.
            if (result == AsyncRequestResult.NoError && packet != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (packet.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    TipMessage  = string.Format("SNMP应答数据包中有错误信息. Error {0} index {1}", packet.Pdu.ErrorStatus, packet.Pdu.ErrorIndex);
                    errorStatus = false;
                    NotifyPropertyChanged("TotalStatus");
                }
                else
                {
                    errorStatus = true;
                    //ifAdminStatus//ifOperStatus//ifInOctets //ifOutOctets
                    bool tempAdminStatus, tempOperStatus;
                    if (packet.Pdu.VbList[0].Value as Integer32 == 1)
                    {
                        tempAdminStatus = true;
                    }
                    else
                    {
                        tempAdminStatus = false;
                    }
                    if (packet.Pdu.VbList[1].Value as Integer32 == 1)
                    {
                        tempOperStatus = true;
                    }
                    else
                    {
                        tempOperStatus = false;
                    }
                    if (tempAdminStatus != adminStatus || tempOperStatus != operStatus)
                    {
                        adminStatus = tempAdminStatus;
                        operStatus  = tempOperStatus;
                        NotifyPropertyChanged("Status");
                        NotifyPropertyChanged("StatusDescr");
                        NotifyPropertyChanged("TotalStatus");
                        if (inSpeed != -1)
                        {
                            TipMessage = string.Format("AdminStatus:{0}\nOperStatus:{1}", adminStatus ? "up" : "down", operStatus ? "up" : "down");
                        }
                    }

                    if (inSpeed == -1)
                    {
                        //这次是第一次获取数据
                        oldInOctets   = packet.Pdu.VbList[2].Value as Counter32;
                        oldIOutOctets = packet.Pdu.VbList[3].Value as Counter32;
                        oldTime       = DateTime.Now;
                        inSpeed       = 0;
                        outSpeed      = 0;
                    }
                    else
                    {
                        newInOctets  = packet.Pdu.VbList[2].Value as Counter32;
                        newOutOctets = packet.Pdu.VbList[3].Value as Counter32;
                        DateTime now      = DateTime.Now;
                        double   interval = (now - oldTime).TotalSeconds;
                        oldTime       = now;
                        inSpeed       = Math.Round((newInOctets - oldInOctets) * 0.008 / interval, 2); //结果为 kb/s
                        outSpeed      = Math.Round((newOutOctets - oldIOutOctets) * 0.008 / interval, 2);
                        SpeedRealTime = string.Format("In: {0}kb/s; Out: {1}kb/s", inSpeed, outSpeed);
                        oldInOctets   = newInOctets;
                        oldIOutOctets = newOutOctets;
                        uiDispatcher.Invoke(new Action(() =>
                        {
                            DataPoint dpIn  = new DataPoint();
                            dpIn.XValue     = DateTime.Now;
                            dpIn.YValue     = inSpeed;
                            DataPoint dpOut = new DataPoint();
                            dpOut.XValue    = DateTime.Now;
                            dpOut.YValue    = outSpeed;
                            if (InSpeedDataPointList.Count >= 30)
                            {
                                InSpeedDataPointList.RemoveAt(0);
                            }
                            InSpeedDataPointList.Add(dpIn);
                            if (OutSpeedDataPointList.Count >= 30)
                            {
                                OutSpeedDataPointList.RemoveAt(0);
                            }
                            OutSpeedDataPointList.Add(dpOut);
                        }));
                        if (IsShowSpeedAlarm)
                        {
                            //SpeedAlarmStatus
                            bool tempSpeedAlarmStatus = (inSpeed <= maxInSpeed) && (outSpeed <= maxOutSpeed);
                            if (tempSpeedAlarmStatus != SpeedAlarmStatus)
                            {
                                SpeedAlarmStatus = tempSpeedAlarmStatus;
                                TipMessage       = string.Format("In:{0}kb/s{1};Out:{2}kb/s{3}", inSpeed, (inSpeed <= maxInSpeed) ? "正常" : "超限!", outSpeed, (outSpeed <= maxOutSpeed) ? "正常" : "超限!");
                            }
                        }
                    }
                }
            }
            else
            {
                TipMessage = "没有SNMP应答数据包";
            }
            target.Close();
        }
Ejemplo n.º 26
0
        public SNMPResultSet[] Walk(string pOID)
        {
            List <SNMPResultSet> snmpResults = new List <SNMPResultSet>();

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

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

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

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

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

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

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

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

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

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

            return(snmpResults.ToArray());
        }
        static void Main(string[] args)
        {
            // SNMP community name
            OctetString community = new OctetString("public");

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

            // Set SNMP version to 1 (or 2)
            param.Version = SnmpVersion.Ver1;
            // Construct the agent address object
            //IpAddress agent = new IpAddress("127.0.0.1"); //Taylor: Change the 127.0.0.1 to the IP address of your own controller's
            IpAddress agent = new IpAddress("192.168.2.109");                 //Taylor: Change the 127.0.0.1 to the IP address of your own controller's
            // Construct target
            UdpTarget target = new UdpTarget((IPAddress)agent, 501, 2000, 0); //Taylor: 503 should be the same NTCIP port in your controller's network setting. You may change to other port numbers (but be consistent with your controller) Other numbers do not matter

            // Pdu class used for all relevant requests
            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 pdu6  = new Pdu(PduType.Get);
            Pdu pdu7  = new Pdu(PduType.Get);
            Pdu pdu8  = new Pdu(PduType.Get);
            Pdu pdu9  = new Pdu(PduType.Get);
            Pdu pdu10 = new Pdu(PduType.Get);
            Pdu pdu11 = new Pdu(PduType.Get);
            Pdu pdu12 = new Pdu(PduType.Get);
            Pdu pdu13 = new Pdu(PduType.Get);
            Pdu pdu14 = new Pdu(PduType.Get);
            Pdu pdu15 = new Pdu(PduType.Get);
            Pdu pdu16 = new Pdu(PduType.Get);

            //pdu class for set //taylor: add in May 2019
            Pdu pdu17 = new Pdu(PduType.Set);
            Pdu pdu18 = new Pdu(PduType.Set);
            Pdu pdu19 = new Pdu(PduType.Set);
            Pdu pdu20 = new Pdu(PduType.Set);
            Pdu pdu21 = new Pdu(PduType.Set);
            Pdu pdu22 = new Pdu(PduType.Set);


            pdu1.VbList.Add("1.3.6.1.4.1.1206.4.2.1.1.4.1.4.1"); //Taylor: green status of Phase 1-8;it will be a decimal integer. you need to convert it a 9-bit binary. for each bit, 1 is current green 0 is not green
            pdu2.VbList.Add("1.3.6.1.4.1.1206.4.2.1.1.4.1.4.2"); //Taylor: Phase 9-16; if not activated, then the returned value is zero
            pdu3.VbList.Add("1.3.6.1.4.1.1206.4.2.1.1.4.1.3.1"); //Taylor: yellow status of Phase 1-8; convert the returned decimal integer to binary. if a bit is 1, then currently that phase is yellow. otherwise is not yellow
            pdu4.VbList.Add("1.3.6.1.4.1.1206.4.2.1.1.4.1.3.2"); //Taylor: yellow phase 9-16; if the phase is no activated, then return value is zero
            //Taylor: no need to poll red since if neither green nor yellow, then it's red

            /////////////////////Ped phase status
            pdu5.VbList.Add("1.3.6.1.4.1.1206.4.2.1.1.4.1.7.1"); //Taylor: walk status of Ped Phase 1-8; convert the returned decimal integer to binary. if a bit is 1, then currently that phase is yellow. otherwise is not yellow
            pdu6.VbList.Add("1.3.6.1.4.1.1206.4.2.1.1.4.1.7.2"); //Taylor: walk status of Ped Phase 9-16; convert the returned decimal integer to binary. if a bit is 1, then currently that phase is yellow. otherwise is not yellow
            pdu7.VbList.Add("1.3.6.1.4.1.1206.4.2.1.1.4.1.6.1"); //Taylor: ped clearance status of Ped Phase 1-8; convert the returned decimal integer to binary. if a bit is 1, then currently that phase is yellow. otherwise is not yellow
            pdu8.VbList.Add("1.3.6.1.4.1.1206.4.2.1.1.4.1.6.2"); //Taylor: ped clearance of Ped Phase 9-16; convert the returned decimal integer to binary. if a bit is 1, then currently that phase is yellow. otherwise is not yellow
            //if a ped phase is neither walk nor ped clearance. then it's solid "don't walk"

            //Poll dets status
            pdu9.VbList.Add("1.3.6.1.4.1.1206.4.2.1.2.4.1.2.1");  //Taylor: det status of channel 1-8; returned a decimal integer. converted to a binary first
            pdu10.VbList.Add("1.3.6.1.4.1.1206.4.2.1.2.4.1.2.2"); //Taylor: det status of channel 9-16; returned a decimal integer. converted to a binary first
            pdu11.VbList.Add("1.3.6.1.4.1.1206.4.2.1.2.4.1.2.3"); //Taylor: det status of channel 17-24; returned a decimal integer. converted to a binary first
            pdu12.VbList.Add("1.3.6.1.4.1.1206.4.2.1.2.4.1.2.4"); //Taylor: det status of channel 25-32; returned a decimal integer. converted to a binary first
            pdu13.VbList.Add("1.3.6.1.4.1.1206.4.2.1.2.4.1.2.5"); //Taylor: det status of channel 33-40; returned a decimal integer. converted to a binary first
            pdu14.VbList.Add("1.3.6.1.4.1.1206.4.2.1.2.4.1.2.6"); //Taylor: det status of channel 41-48; returned a decimal integer. converted to a binary first
            pdu15.VbList.Add("1.3.6.1.4.1.1206.4.2.1.2.4.1.2.7"); //Taylor: det status of channel 49-56; returned a decimal integer. converted to a binary first
            pdu16.VbList.Add("1.3.6.1.4.1.1206.4.2.1.2.4.1.2.8"); //Taylor: det status of channel 57-64; returned a decimal integer. converted to a binary first

            //Phase controls //
            pdu17.VbList.Add(new Oid("1.3.6.1.4.1.1206.4.2.1.1.5.1.2.1"), new Integer32(255)); //Taylor: phase 1~8 omit (if binary, from right to left: phase 1-8, but you will need to input the corresponding decimal). e.g., if you wish to omit 3 and 7. the binary value will be 01000100 and the decimal value is 68. replace the last digit in the 1.3.6.xxxx.2.1 with 2 if you wish to omit 9~16
            pdu18.VbList.Add(new Oid("1.3.6.1.4.1.1206.4.2.1.1.5.1.3.1"), new Integer32(68));  //Taylor: Ped 1-8 omits
            pdu19.VbList.Add(new Oid("1.3.6.1.4.1.1206.4.2.1.1.5.1.4.1"), new Integer32(68));  //Taylor: Phase 1-8 hold . 1.3....4."1". can be relaced with 2 for phase 9~16
            pdu20.VbList.Add(new Oid("1.3.6.1.4.1.1206.4.2.1.1.5.1.5.1"), new Integer32(68));  //taylor place or lift phase 1-8 force-off (if you wish to force phase 1 and 5, the binary will be 00010001 and the decmial is 17
            pdu21.VbList.Add(new Oid("1.3.6.1.4.1.1206.4.2.1.1.5.1.6.1"), new Integer32(68));  //Taylor: place (1) or lift (0)phase 1-8 vehicle call
            pdu21.VbList.Add(new Oid("1.3.6.1.4.1.1206.4.2.1.1.5.1.7.1"), new Integer32(68));  //Taylor: place or lift ped call


            // Taylor: Just use the green 1-8 and yellow 1-8 and det 1-8 as illustration. Please extend to others PDU as defined above if needed
            SnmpV1Packet result1 = (SnmpV1Packet)target.Request(pdu1, param);

            // green status of phase 1-8
            if (result1 != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result1.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                      result1.Pdu.ErrorStatus,
                                      result1.Pdu.ErrorIndex);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    String green1to8 = result1.Pdu.VbList[0].Value.ToString();//Taylor: Using https://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html  to convert decimal to binary (from right to left, phase 1 to 8). You may need a function to do this in the code
                }
            }
            // yellow status of phase 1-8
            SnmpV1Packet result3 = (SnmpV1Packet)target.Request(pdu3, param);

            if (result3 != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result3.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                      result3.Pdu.ErrorStatus,
                                      result3.Pdu.ErrorIndex);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    String yellow1to8 = result3.Pdu.VbList[0].Value.ToString();
                }
            }
            // Status of det 1-8
            SnmpV1Packet result9 = (SnmpV1Packet)target.Request(pdu9, param);

            if (result9 != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result9.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                      result9.Pdu.ErrorStatus,
                                      result9.Pdu.ErrorIndex);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    String det1to8 = result9.Pdu.VbList[0].Value.ToString();
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }

            //Set (write) example: phase 1-8 omit
            //SnmpV1Packet result17 = (SnmpV1Packet)target.Request(pdu17, param);
            SnmpV1Packet result17 = target.Request(pdu17, param) as SnmpV1Packet;// Taylor: I set the omit value 255 (1111111). it means all 8 phases are omit and you should be able to see this status on your front panel

            //                                                                                                            ^ (from left to right means the status of phase 8, 7,...,2,1)
            //If you wish to
            if (result17 != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result17.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}", result17.Pdu.ErrorStatus, result17.Pdu.ErrorIndex);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    String phaseomit1to8 = result17.Pdu.VbList[0].Value.ToString();
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }

            target.Close();
        }
Ejemplo n.º 28
0
        public void GetInfoOID(DataTable dtInterfaceGauge, out DataTable dt)
        {
            dt = dtInterfaceGauge.Copy();
            if (dtInterfaceGauge.Rows.Count > 0)
            {
                // SNMP community name
                OctetString community = new OctetString(_community);

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

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

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

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

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

                        for (int i = 0; i < dtInterfaceGauge.Rows.Count; i++)
                        {
                            dtInterfaceGauge.Rows[i]["InBandwidth"]  = result.Pdu.VbList[i + i].Value.ToString();
                            dtInterfaceGauge.Rows[i]["OutBandwidth"] = result.Pdu.VbList[i + i + 1].Value.ToString();
                        }
                        dt = dtInterfaceGauge;
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
                target.Close();
            }
        }
Ejemplo n.º 29
0
        private void GetDisk()
        {
            OctetString     community = new OctetString(txtConStr.Text);
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver1;
            try
            {
                IpAddress agent  = new IpAddress(txtIPAgent.Text);
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add("1.3.6.1.2.1.1.1.0");    //sysDescr
                pdu.VbList.Add("1.3.6.1.2.1.1.2.0");    //sysObjectID
                pdu.VbList.Add("1.3.6.1.2.1.1.3.0");    //sysUpTime
                pdu.VbList.Add("1.3.6.1.2.1.1.4.0");    //sysContact
                pdu.VbList.Add("1.3.6.1.2.1.1.5.0");    //sysName
                pdu.VbList.Add("1.3.6.1.2.1.25.1.2.0"); //hrSystemDate
                pdu.VbList.Add("1.3.6.1.2.1.25.1.5.0"); //hrSystemNumUsers
                pdu.VbList.Add("1.3.6.1.2.1.25.1.6.0"); //hrSystemProcesses
                pdu.VbList.Add("1.3.6.1.2.1.25.2.2.0"); //hrMemorySize
                //pdu.VbList.Add("1.3.6.1.2.1.1.5." + n.ToString()); //sysName
                //pdu.VbList.Add("1.3.6.1.2.1.2.1." + n.ToString()); //ifNumbber
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

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

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

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

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

                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2." + n.ToString()); //ifDescr
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.3." + n.ToString()); //ifType
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.5." + n.ToString()); //ifSpeed
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.6." + n.ToString()); //ifPhysAddress
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.7." + n.ToString()); //ifAdminStatus
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8." + n.ToString()); //ifOperStatus
                // Make SNMP request
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

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

                        rtb.Text = "Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex;
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added to the VbList
                        rtb.Text = "ifDescr(" + result.Pdu.VbList[0].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + "): " + "\n\t" + result.Pdu.VbList[0].Value.ToString();
                        rtb.Text = rtb.Text + "\n" + "ifType(" + result.Pdu.VbList[1].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type) + "): " + "\n\t" + GetType(int.Parse(result.Pdu.VbList[1].Value.ToString()));
                        rtb.Text = rtb.Text + "\n" + "ifSpeed(" + result.Pdu.VbList[2].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type) + "): " + "\n\t" + result.Pdu.VbList[2].Value.ToString();
                        rtb.Text = rtb.Text + "\n" + "ifPhysAddress(" + result.Pdu.VbList[3].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type) + "): " + "\n\t" + result.Pdu.VbList[3].Value.ToString();
                        rtb.Text = rtb.Text + "\n" + "ifAdminStatus(" + result.Pdu.VbList[4].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type) + "): " + "\n\t" + GetStatus(int.Parse(result.Pdu.VbList[4].Value.ToString()));
                        rtb.Text = rtb.Text + "\n" + "ifOperStatus(" + result.Pdu.VbList[5].Oid.ToString() + ") (" + SnmpConstants.GetTypeName(result.Pdu.VbList[5].Value.Type) + "): " + "\n\t" + GetStatus(int.Parse(result.Pdu.VbList[5].Value.ToString()));
                    }
                }
                else
                {
                    rtb.Text = "No response received from SNMP agent.";
                }
                target.Close();
            }
            catch (Exception ex)
            {
                rtb.Text = "Đã xảy ra lỗi: " + ex.Message.ToString();
            }
        }
Ejemplo n.º 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();
        }