Ejemplo n.º 1
0
        /// <summary>
        /// Return a table relating to an <paramref name="entryOid"/> with the columns <paramref name="oidColumns"/>.
        /// </summary>
        /// <param name="entryOid">The OID for the table's entries.</param>
        /// <param name="oidColumns">The OIDs for the table's columns.</param>
        /// <returns>A dictionary, keyed by row number, with a dictionary representation of each row.</returns>
        private Dictionary <int, Dictionary <string, AsnType> > FetchTable(string entryOid, Dictionary <string, string> oidColumns)
        {
            //Walk (query all child OIDs) on the given root OID
            Dictionary <Oid, AsnType> result = GetQuerySnmp().Walk(SnmpVersion.Ver1, entryOid);

            //If there is no reply, return nothing.
            if (result == null)
            {
                return(null);
            }
            //Retrieve the child OIDs (rows) for the table.
            string[] suffixes = SnmpHelper.GetSuffixes(result, entryOid);
            //Create a new dictionary to store the generated dictionary representation of the table.
            Dictionary <int, Dictionary <string, AsnType> > table = new Dictionary <int, Dictionary <string, AsnType> >();

            foreach (string suffix in suffixes)
            {
                //Transform the column dictionary into a dictionary representation of the current row.
                Dictionary <string, AsnType> suffixResults = oidColumns.Select(kvp =>
                {
                    //An OID comprised of the column OID and the current suffix.
                    Oid oid = new Oid(kvp.Value + suffix);
                    //Transform the value of the key-value pair to be the result of the SNMP walk if one was given, otherwise an empty string.
                    return(new KeyValuePair <string, AsnType>(kvp.Key, result.ContainsKey(oid) ? result[oid] : new OctetString(string.Empty)));
                }).ToDictionary(x => x.Key, x => x.Value); //Convert the IEnumerable to a Dictionary again.
                //Add this representation to the table created above.
                table.Add(int.Parse(suffix), suffixResults);
            }
            return(table);
        }
Ejemplo n.º 2
0
        private void btnLock_Click(object sender, EventArgs e)
        {
            sh = new SnmpHelper(txtHostName.Text, Int32.Parse(txtPort.Text), txtCommunity.Text, 2);

            txtHostName.Enabled  = false;
            txtPort.Enabled      = false;
            txtCommunity.Enabled = false;

            foreach (Control ctl in this.Controls)
            {
                if (ctl is Button)
                {
                    ctl.Enabled = true;
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 探测网络拓扑全过程,应该要在新线程中工作,后面改
        /// </summary>
        private void StartDetecNetwork(Object stateInfo)
        {
            string       strIP;
            VbCollection equipInfo;

            AddMessage("网络拓扑探测和绘制开始");
            while (WaitForDetectList.Count > 0)
            {
                if (!isDetecting)
                {
                    AddMessage("网络拓扑探测和绘制被强制结束");
                    return;
                }
                WaitForDetectInfomation waitInfo = WaitForDetectList[0];
                IpAddress ip        = waitInfo.Ip;
                Equipment lastEquip = waitInfo.Equip;
                int       step      = waitInfo.Step;
                WaitForDetectList.RemoveAt(0);
                //需要获取的单个snmp变量信息包括设备描述、objectid(enterprises.311.1.1.3.1.2,可用来判断设备厂家,待验证)

                /*objectid验证整理    enterprises = 1.3.6.1.4.1
                 * 虚拟机2003操作系统:enterprises.311.1.1.3.1.2
                 */

                if (ipAlreadyFindList.ContainsKey(ip))
                {   //这里应该不可能执行到,试一下
//                     MessageBox.Show("这里应该不可能执行到,试一下");
//                     continue;
                    //下一跳设备已经存在,只画线即可
                    if (ipAlreadyFindList[ip].Equip.AdminIPAddress.ToString() == "67.250.5.1" && lastEquip.AdminIPAddress.ToString() == "3.250.5.1")
                    {
                    }
                    DrawLine(ipAlreadyFindList[ip].Equip, lastEquip);
                    AddMessage("直接画线" + ip.ToString() + "到" + lastEquip.AdminIPAddress.ToString());
                    continue;
                }
                equipInfo = SnmpHelper.GetResultsFromOids(ip, equipInfoRequestOids, out tipMessage);
                if (equipInfo == null)
                {
                    AddMessage(string.Format("出错,错误信息:{0}", tipMessage));
                    AddMessage(string.Format("SNMP获取ip:{0}设备system信息失败,进入下一轮", ip.ToString()));
                    continue;
                }
                string sysDescr    = equipInfo[0].Value.ToString();
                string sysObjectID = equipInfo[1].Value.ToString();
                byte   sysServices = Convert.ToByte(equipInfo[2].Value.ToString());//可以根据此值尝试获取设备类型,当数据库中没有值的时候使用此猜测值。

                //开始建立ucequip,equipment,搜索静态列表是否有这个设备,取得名字等信息
                strIP = ip.ToString();
                Equipment equip = GetEquipment(strIP, sysDescr, lastEquip);
                equip.EquipBrand = SnmpHelper.GetBrandFromObjectID(sysObjectID);
                if (equip == null)
                {
                    AddMessage(string.Format("SNMP获取ip:{0}设备信息失败,进入下一轮", strIP));
                    continue;
                }
                equipAlreadyFindList.Add(equip.Index, equip);
                AddMessage("发现设备信息,设备名称:" + equip.Name);

                UCEquipIcon ucEquipIcon = GetUCEquipIcon(equip);
                if (ucEquipIcon == null)
                {
                    AddMessage(string.Format("添加设备{0}图标、定位失败,进入下一轮", strIP));
                    continue;
                }
                AddMessage(string.Format("添加设备图标,坐标x:{0},y:{1}", equip.X, equip.Y));
                //GetTextBlock(ucEquipIcon);
                FilterRouteInfo(equip, step);
                if (equip.AdminIPAddress.ToString() == "67.250.5.1" && lastEquip.AdminIPAddress.ToString() == "3.250.5.1")
                {
                }
                if (lastEquip != null)
                {
                    DrawLine(equip, lastEquip);
                }
            }
            IsDetecting = false;
            AddMessage("网络拓扑发现和绘制完毕");
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            SnmpHelper sh = new SnmpHelper("192.168.0.107", 161, "public", 2);

            Single abc = 0;

            while (false)
            {
                var currentAbc = sh.GetSystemCpuUsage();
                if (currentAbc != abc)
                {
                    Console.WriteLine(DateTime.Now.ToString() + ":  CPU   " + currentAbc);
                    abc = currentAbc;
                }
                Thread.Sleep(100);
            }

            while (true)
            {
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("系统描述:" + sh.GetSystemDescription());
                Console.WriteLine("系统名称:" + sh.GetSystemName());
                //Console.WriteLine("系统启动时间:" + aaaSoft.Helpers.DateTimeHelper.ConvertTimespanToString(sh.GetSystemUpTime()));
                Console.WriteLine("系统进程数:" + sh.GetSystemProcessCount());
                Console.WriteLine("      -----内存部分----");
                var ramInfo = sh.GetPhysicalMemoryInfo();
                //Console.WriteLine("物理内存大小:" + aaaSoft.Helpers.IoHelper.GetFileLengthLevelString(ramInfo.StorageSize, 1));
                Console.WriteLine("物理内存占用率:" + ramInfo.StorageUsage + "%");
                var vramInfo = sh.GetVirtualMemoryInfo();
                //Console.WriteLine("虚拟内存大小:" + aaaSoft.Helpers.IoHelper.GetFileLengthLevelString(vramInfo.StorageSize, 1));
                Console.WriteLine("虚拟内存占用率:" + vramInfo.StorageUsage + "%");

                Console.WriteLine("      -----磁盘部分----");
                var fixedDiskInfos = sh.GetFixedDiskStorageInfo();

                Console.WriteLine("分区描述  分区大小  已使用大小  使用率");
                foreach (var info in fixedDiskInfos)
                {
                    /*
                     * Console.WriteLine(String.Format(
                     *  "{0}        {1}     {2}     {3}%"
                     *  , info.hrStorageDescr
                     *  , aaaSoft.Helpers.IoHelper.GetFileLengthLevelString(info.StorageSize,1)
                     *  , aaaSoft.Helpers.IoHelper.GetFileLengthLevelString(info.StorageUsed,1)
                     *  , info.StorageUsage));
                     */
                }
                Console.WriteLine("      -----网卡部分----");
                var interfaceInfoArray = sh.GetPhysicalInterfaceInfo();
                Console.WriteLine("接口描述\t速率\t物理地址\t接收数据\t发送数据");
                foreach (var item in interfaceInfoArray)
                {
                    Console.WriteLine(String.Format(
                                          "{0}\t{1}\t{2}\t{3}\t{4}"
                                          , item.ifDescr
                                          , item.ifSpeed
                                          , item.ifPhysAddress
                                          , item.ifInOctets
                                          , item.ifOutOctets
                                          ));
                }

                Console.WriteLine("      -----其他----");
                Console.WriteLine("系统CPU占用率:" + sh.GetSystemCpuUsage() + "%");


                Console.ReadLine();
            }
        }
Ejemplo n.º 5
0
        private void ConstructListByIP(IpAddress agentIP, string equipName)
        {
            if (string.IsNullOrEmpty(equipName))
            {
                try
                {
                    equipName = App.idAndEquipList[App.ipAndIPinfoList[agentIP.ToString()].EquipIndex].Name;
                }
                catch { }
            }
            ocInterfaces.Clear();
            OctetString     community = new OctetString(App.snmpCommunity);
            AgentParameters param     = new AgentParameters(community);

            param.DisableReplySourceCheck = !App.snmpCheckSrcFlag;
            // 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, App.snmpPort, App.snmpTimeout, App.snmpRetry);

            // 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.1"); // ifIndex

            // 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 = null;
                try
                {
                    result = (SnmpV2Packet)target.Request(pdu, param);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("获取SNMP应答出现错误\n" + ex.Message);
                    target.Close();
                    return;
                }
                // 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
                        MessageBox.Show(string.Format("SNMP应答数据包中有错误。 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))
                            {
                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid = null;
                                }
                                else
                                {
                                    lastOid = v.Oid;
                                }
                                Integer32 f    = v.Value as Integer32;
                                Interface intf = new Interface(agentIP);
                                intf.EquipName = equipName;
                                //intf.TimerInteral = double.Parse(cbbTimerInterval.Text);
                                ocInterfaces.Add(f, intf);
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                                break; // 每个数据包获取5个值,一旦有一个不是这一列的数据,后面的应该都不是了
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("指定网管代理未返回有效信息");
                }
            }
            target.Close();
            string errorMessage;

            foreach (Integer32 i in ocInterfaces.Keys)
            {
                string       strOid = "1.3.6.1.2.1.2.2.1.2." + i.ToString();
                VbCollection vbc    = SnmpHelper.GetResultsFromOids(agentIP, new string[] { strOid }, out errorMessage);
                ocInterfaces[i].Descr   = vbc[0].Value.ToString();
                ocInterfaces[i].IfIndex = i;
            }
        }