如何列出连接交换机的端口和 Mac 地址 (Cisco) C#

2023-12-02

大家好我想问一下如何使用C#列出连接到交换机的设备的端口和mac地址。 我找到了适用于戴尔交换机的代码。我需要它用于思科交换机

using SnmpSharpNet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
namespace PortMapper
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
 
        List<KeyValuePair<string, string>> portList = new List<KeyValuePair<string, string>>();
        List<Portmap> portMaps = new List<Portmap>();
 
        public class Portmap
        {
            public string Hostname { get; set; }
            public string Port { get; set; }
            public string IP { get; set; }
            public string MAC { get; set; }
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            IPAddress ip = IPAddress.Parse("192.168.0.2");
            IPAddress ip2 = IPAddress.Parse("192.168.0.3");
            SnmpWalk(ip, "community", "1.3.6.1.2.1.17.7.1.2.2.1.2.1", "1");
            SnmpWalk(ip2, "community","1.3.6.1.2.1.17.7.1.2.2.1.2.1", "2");
            DhcpQuery("netsh", "dhcp server \\\\servername scope 192.168.0.0 show clients", "192");
            List<Portmap> gridResults = new List<Portmap>();
            //Example of filtering uplink ports from other switches
            foreach(Portmap portMap in portMaps)
            {
                if (portMap.Port != "1/2/48" && portMap.Port != "2/1/48")
                {
                    gridResults.Add(portMap);
                }
            }
            PortMapGrid.ItemsSource = gridResults;
        }
         
        //Use NETSH to retrieve a list of DHCP MAC and IP addresses
        private void DhcpQuery(string cmd, string args, string subnet)
        {
            ProcessStartInfo procStartInfo = new ProcessStartInfo();
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute = false;
            procStartInfo.FileName = cmd;
            procStartInfo.Arguments = args;
            procStartInfo.CreateNoWindow = true;
            string output;
            using (Process proc = Process.Start(procStartInfo))
            {
                output = proc.StandardOutput.ReadToEnd();
                proc.WaitForExit();
            }
 
            //Find valid leases in command output
            string[] lines = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            List<string> leases = new List<string>();
            foreach (string line in lines)
            {
                if (line.StartsWith(subnet))
                {
                   leases.Add(line);
                }
            }
 
            //Create threads
            Thread[] threadArray = new Thread[leases.Count];
            int threadcount = 0;
 
            //Loop each Dhcp Lease
            foreach (string line in leases)
            {
                string[] pieces = line.Split('-');
                string ipAddress = pieces[0].Trim();
                string mac = "";
                string hostname = "";
                foreach (string piece in pieces)
                {
                    if (piece.Trim().Length == 2)
                    {
                        mac += piece;
                    }
                }
 
                ThreadStart start = delegate
                {
                    hostname = GetHost(ipAddress);
                    foreach (KeyValuePair<string, string> port in portList)
                    {
                        if (port.Key.ToUpper().Trim() == mac.ToUpper().Trim())
                        {
                            Portmap portMap = new Portmap();
                            portMap.IP = ipAddress;
                            portMap.MAC = mac.ToUpper();
                            portMap.Port = port.Value;
                            portMap.Hostname = hostname;
                            portMaps.Add(portMap);
                        }
                    }
                };
                threadArray[threadcount] = new Thread(start);
                threadArray[threadcount].Start();
                threadcount = threadcount + 1;
            }
 
            //Join all threads in the array to wait for results
            for (int i = 0; i < threadcount; i++)
            {
                threadArray[i].Join();
            }
        }
 
        //SNMPWALK the ports on a switch or stack of switches. Ports will be labeled SwitchNum/Stack Number/Port Numbers.
        private void SnmpWalk(IPAddress ip, string snmpCommunity, string oid, string switchNum)
        {
            UdpTarget target = new UdpTarget(ip);
 
            // SNMP community name
            OctetString community = new OctetString(snmpCommunity);
            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);
            // Set SNMP version to 1
            param.Version = SnmpVersion.Ver1;
 
 
            // Define Oid that is the root of the MIB tree you wish to retrieve
            Oid rootOid = new Oid(oid);
 
            // This Oid represents last Oid returned by the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();
 
            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetNext);
 
            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to a random value
                // that needs to be incremented on subsequent requests made using the
                // same instance of the Pdu class.
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                // You should catch exceptions in the Request if using in real application.
 
                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by 
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                            result.Pdu.ErrorStatus,
                            result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                //Convert OID to MAC
                                string[] macs = v.Oid.ToString().Split('.');
                                string mac = "";
                                int counter = 0;
                                foreach (string chunk in macs)
                                {
                                    if (counter >= macs.Length - 6)
                                    {
                                        mac += string.Format("{0:X2}", int.Parse(chunk));
                                    }
                                    counter += 1;
                                }
 
                                //Assumes a 48 port switch (52 actual). You need to know these values to correctly iterate through a stack of switches.
                                int dellSwitch = 1 + int.Parse(v.Value.ToString()) / 52;
                                int port = int.Parse(v.Value.ToString()) - (52 * (dellSwitch - 1));
                                KeyValuePair<string, string> Port = new KeyValuePair<string, string>(mac, switchNum + "/" + dellSwitch.ToString() + "/" + port.ToString());
                                portList.Add(Port);
 
                                //Exit Loop
                                lastOid = v.Oid;
                            }
                            else
                            {
                                //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();
        }
 
        private string GetHost(string ipAddress)
        {
            try
            {
                IPHostEntry entry = Dns.GetHostEntry(ipAddress);
                return entry.HostName;
            }
            catch
            {
                return "";
            }
        }
    }
}

任何人都可以帮助我找到代码,或者给我一种方法,让我如何将此代码转换为适用于思科。它可能是什么?


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何列出连接交换机的端口和 Mac 地址 (Cisco) C# 的相关文章

  • 如何将动态数据写入 MVC 3 Razor 中的页面布局?

    我有带有 Razor 引擎的 MVC 3 C 项目 将动态数据写入 Layout cshtml 的方法和最佳实践是什么 例如 也许我想在网站的右上角显示用户名 该名称来自会话 数据库或基于用户登录的任何内容 更新 我也在寻找将某些数据渲染到
  • 如何准备sql语句并绑定参数?

    不幸的是 文档 http www sqlite org完全缺乏示例 这真的很奇怪 就好像它假设所有读者都是优秀的程序员一样 然而 我对C 并且无法真正从文档中弄清楚如何真正准备和执行语句 我喜欢它的实施方式PDO for PHP 通常 我只
  • Python 相当于 Bit Twiddling Hacks 中的 C 代码?

    我有一个位计数方法 我正在尝试尽可能快地实现 我想尝试下面的算法位摆弄黑客 http graphics stanford edu seander bithacks html CountBitsSetParallel 但我不知道 C 什么是
  • 为基于架构的 XML 文件创建 WPF 编辑器

    这是场景 我们的服务器产品之一使用大型 XML 配置文件 该文件的布局相当好 并且针对 XSD 文件进行了验证 现在是时候构建一个配置 GUI 来维护这个文件了 我想深入研究 WPF 来完成它 我可以为每个配置部分布置一个单独的表单 每次向
  • 如何进行Visual Studio格式字典初始化?

    所有 Visual Studio 也包括 2012 不格式化以下内容 messageProcessor new Dictionary
  • 如何使用 libclang 判断成员函数是 const 还是 volatile?

    我有一个实例CXCursor同类CXCursor CXXMethod 我想知道这个函数是否是const or volatile 例如 class Foo public void bar const void baz volatile voi
  • 使用正则表达式解析日志文件

    我目前正在为我们的内部日志文件 由 log4php log4net 和 log4j 生成 开发一个解析器 到目前为止 我有一个很好的正则表达式来解析日志 除了一个烦人的一点 一些日志消息跨越多行 我无法正确匹配 我现在的正则表达式是这样的
  • 我们什么时候应该在.NET中使用NativeMemory.Alloc()? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 NET6 C 引入NativeMemory类 但我不知道什么时候应该使用NativeMemory Alloc 而不是普通的数组实例化
  • 如何在控制器中使用多个 DBContext

    如何在控制器中使用多个 DBContext 我尝试以不同的方式重载构造函数 一些控制器 public C1 DBContext1 a DBContext2 b DBContext3 c public C1 DBContext1 a publ
  • 我如何模拟 UserManager 和 RoleManager 进行单元测试

    我模拟了抽象类来测试类的具体方法 如下所示 var mock new Mock
  • 指向 VLA 的指针

    你可能知道 VLA 的优点和缺点 https stackoverflow com a 3082302 1606345在 C11 中它们是可选的 我认为使 VLA 成为可选的主要原因是 堆栈可能会爆炸 int arr n where n 10
  • Bazel:将编译标志添加到默认 C++ 工具链

    我想向默认的 C 工具链添加一些编译器和链接器标志 以便我构建的所有目标 本地或导入 共享它们 我知道可以定义我自己的工具链 但我不想这样做 因为它非常复杂且容易出错 理想情况下我想要这样的东西 cc toolchain cc defaul
  • PowerShell 与 MongoDB C# 驱动程序方法不兼容?

    由 C 泛型引起的最新 MongoDB 驱动程序的问题 Cannot find an overload for GetCollection and the argument count 1 我可能可以使用其他没有泛型的 GetCollect
  • C# 从今天起 30 天

    我需要我的应用程序从今天起 30 天后过期 我会将当前日期存储在应用程序配置中 如何检查应用程序是否已过期 我不介意用户是否将时钟调回来并且应用程序可以正常工作 用户太愚蠢而不会这样做 if appmode Trial string dat
  • 在 boost 元组、zip_iterator 等上使用 std::get 和 std::tie

    我有哪些使用选择std get lt gt and std tie lt gt 与增强结构一起 例子 我想使用基于范围的 for 循环在多个容器上进行迭代 我可以实施zip函数 它使用boost zip iterator include
  • 如何在RcppParallel中调用用户定义的函数?

    受到文章的启发http gallery rcpp org articles parallel distance matrix http gallery rcpp org articles parallel distance matrix 我
  • 在 C++ 中什么时候首选传递指针而不是引用传递?

    我可以想象一种情况 其中输入参数可以为 NULL 以便首选传递指针而不是传递引用 有人可以添加更多案例吗 在传递的对象实际上将被修改的情况下 有些人更喜欢传递指针 当对象通过引用传递时 它们使用 pass by const referenc
  • OpenCV 仅围绕大轮廓绘制矩形?

    第一次发帖 希望我以正确的方式放置代码 我正在尝试检测和计算视频中的车辆 因此 如果您查看下面的代码 我会在阈值处理和膨胀后找到图像的轮廓 然后我使用 drawContours 和矩形在检测到的轮廓周围绘制一个框 我试图在 drawCont
  • 使用 List.Contains 方法为 LINQ 构建表达式树

    Problem 我正在重构一些LINQ查询我们的 Web 应用程序中的多个报告 并且我尝试将一些重复的查询谓词移至它们自己的中IQueryable扩展方法 以便我们可以将它们重新用于这些报告以及将来的报告 正如您可能推断的那样 我已经重构了
  • 在地图上使用 find

    如何使用 find 和 aconst iterator如果你有一个地图定义为 typedef std pair

随机推荐