如何过滤mac地址

2024-06-01 00:59:06 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我吗,我是编程新手,我的问题是输出我只想过滤mac地址。我该怎么做呢

from netmiko import ConnectHandler

cisco = {
        'device_type' : 'cisco_ios',
        'host' : '192.168.X.Y',
        'username' : 'foo',
        'password' : '123',
}

net_connect = ConnectHandler(**cisco)
net_connect.find_prompt()
show_mac = net_connect.send_command("show mac address-table vlan 100")
print(show_mac)

输出:

Vlan    Mac Address       Type        Ports
----    -----------       --------    -----
 100    264b.edf4.eba2    DYNAMIC     Gi0/3
 100    2680.f1ee.c0b1    DYNAMIC     Gi0/2
 100    3a60.2954.1ee2    DYNAMIC     Gi1/3
 100    4a60.05bd.27fc    DYNAMIC     Gi1/2
 100    7e02.eee8.0291    DYNAMIC     Gi0/1
 100    b689.d44e.afd1    DYNAMIC     Gi1/0
 100    d207.6258.5966    DYNAMIC     Gi1/1
Total Mac Addresses for this criterion: 7

Tags: fromnetmac地址编程showconnectdynamic
1条回答
网友
1楼 · 发布于 2024-06-01 00:59:06

您可以在这里使用regex。正则表达式允许您匹配特定的文本结构。 例如:

类似“hello\d{1,3}”的正则表达式可以匹配类似“hello12”或“hello432”的字符串

您可以为任何数字值(包括重复)匹配文字字符和占位符,如\d{1,3}=一次到三次复发之间。 在本例中,您需要字母数字值,它可以与python中的\w匹配

^=以下字符必须位于行的开头

$=前面的字符必须位于行的末尾

=每个字符都匹配

+=至少一次或多次匹配上一个字符/组。这是一个贪婪的操作符,所以在玩游戏时check your regex

因为您只需要匹配行的一部分,所以可以使用捕获组。 捕获组使匹配中的子字符串可以单独访问。只需将所需部分用括号()括起来

Python为此提供了一个正则表达式模块,下面是一些示例代码:

import re

def your_func():
    mac_addresses = []
    for line in show_mac.split('\n'):  # split the above string in lines
        line = line.strip()  # remove leading and trailing spaces
        pattern = re.compile(r'^\d+\s+(\w{1,4}\.\w{1,4}\.\w{1,4})\s+\w+\s+.+$')
        # match a regex to a string from the beginning
        match = re.match(pattern, line)
        # python match object contains our capture group. first group is at index 1, index 0 is the whole match
        if match and match[1]:
            mac_addresses.append(match[1])

    print(mac_addresses)

相关问题 更多 >