如何列出连接交换机的端口和 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# 的相关文章

  • 在一个数据访问层中处理多个连接字符串

    我有一个有趣的困境 我目前有一个数据访问层 它必须与多个域一起使用 并且每个域都有多个数据库存储库 具体取决于所调用的存储过程 目前 我只需使用 SWITCH 语句来确定应用程序正在运行的计算机 并从 Web config 返回适当的连接字
  • 从经典 ASP 调用 .Net C# DLL 方法

    我正在开发一个经典的 asp 项目 该项目需要将字符串发送到 DLL DLL 会将其序列化并发送到 Zebra 热敏打印机 我已经构建了我的 DLL 并使用它注册了regasm其次是 代码库这使得 IIS 能够识别它 虽然我可以设置我的对象
  • 如何在 C++ 中标记字符串?

    Java有一个方便的分割方法 String str The quick brown fox String results str split 在 C 中是否有一种简单的方法可以做到这一点 The 增强分词器 http www boost o
  • 枚举扩展方法

    在vs2008中 是否可以编写适用于任何枚举的扩展方法 我知道您可以针对特定枚举编写扩展方法 但我希望能够使用单个扩展方法对每个枚举进行处理 这可能吗 是的 只需针对基础进行编码Enum类型 例如 public static void So
  • 需要帮助优化算法 - 两百万以下所有素数的总和

    我正在尝试做一个欧拉计划 http projecteuler net问题 我正在寻找 2 000 000 以下所有素数的总和 这就是我所拥有的 int main int argc char argv unsigned long int su
  • WPF 数据绑定到复合类模式?

    我是第一次尝试 WPF 并且正在努力解决如何将控件绑定到使用其他对象的组合构建的类 例如 如果我有一个由两个单独的类组成的类 Comp 为了清楚起见 请注意省略的各种元素 class One int first int second cla
  • C# 列表通用扩展方法与非通用扩展方法

    这是一个简单的问题 我希望 集合类中有通用和非通用方法 例如List
  • 如何定义一个可结构化绑定的对象的概念?

    我想定义一个concept可以检测类型是否T can be 结构化绑定 or not template
  • 实例化类时重写虚拟方法

    我有一个带有一些虚函数的类 让我们假设这是其中之一 public class AClassWhatever protected virtual string DoAThingToAString string inputString retu
  • C 编程:带有数组的函数

    我正在尝试编写一个函数 该函数查找行为 4 列为 4 的二维数组中的最大值 其中二维数组填充有用户输入 我知道我的主要错误是函数中的数组 但我不确定它是什么 如果有人能够找到我出错的地方而不是编写新代码 我将不胜感激 除非我刚去南方 我的尝
  • 如何在当前 Visual Studio 主机内的 Visual Studio 扩展中调试使用 Roslyn 编译的代码?

    我有一个 Visual Studio 扩展 它使用 Roslyn 获取当前打开的解决方案中的项目 编译它并从中运行方法 程序员可以修改该项目 我已从当前 VisualStudioWorkspace 成功编译了 Visual Studio 扩
  • C 函数 time() 如何处理秒的小数部分?

    The time 函数将返回自 1970 年以来的秒数 我想知道它如何对返回的秒数进行舍入 例如 对于100 4s 它会返回100还是101 有明确的定义吗 ISO C标准没有说太多 它只说time 回报 该实现对当前日历时间的最佳近似 结
  • C++ 继承的内存布局

    如果我有两个类 一个类继承另一个类 并且子类仅包含函数 那么这两个类的内存布局是否相同 e g class Base int a b c class Derived public Base only functions 我读过编译器无法对数
  • 使用特定参数从 SQL 数据库填充组合框

    我在使用参数从 sql server 获取特定值时遇到问题 任何人都可以解释一下为什么它在 winfom 上工作但在 wpf 上不起作用以及我如何修复它 我的代码 private void UpdateItems COMBOBOX1 Ite
  • 对于某些 PDF 文件,LoadIFilter() 返回 -2147467259

    我正在尝试使用 Adob e IFilter 搜索 PDF 文件 我的代码是用 C 编写的 我使用 p invoke 来获取 IFilter 的实例 DllImport query dll SetLastError true CharSet
  • 为什么C++代码执行速度比java慢?

    我最近用 Java 编写了一个计算密集型算法 然后将其翻译为 C 令我惊讶的是 C 的执行速度要慢得多 我现在已经编写了一个更短的 Java 测试程序和一个相应的 C 程序 见下文 我的原始代码具有大量数组访问功能 测试代码也是如此 C 的
  • C# 中最小化字符串长度

    我想减少字符串的长度 喜欢 这串 string foo Lorem ipsum dolor sit amet consectetur adipiscing elit Aenean in vehicula nulla Phasellus li
  • 在OpenGL中,我可以在坐标(5, 5)处精确地绘制一个像素吗?

    我所说的 5 5 正是指第五行第五列 我发现使用屏幕坐标来绘制东西非常困难 OpenGL 中的所有坐标都是相对的 通常范围从 1 0 到 1 0 为什么阻止程序员使用屏幕坐标 窗口坐标如此严重 最简单的方法可能是通过以下方式设置投影以匹配渲
  • 类型或命名空间“MyNamespace”不存在等

    我有通常的类型或命名空间名称不存在错误 除了我引用了程序集 using 语句没有显示为不正确 并且我引用的类是公共的 事实上 我在不同的解决方案中引用并使用相同的程序集来执行相同的操作 并且效果很好 顺便说一句 这是VS2010 有人有什么
  • 如何确定 CultureInfo 实例是否支持拉丁字符

    是否可以确定是否CultureInfo http msdn microsoft com en us library system globalization cultureinfo aspx我正在使用的实例是否基于拉丁字符集 我相信你可以使

随机推荐