【问题标题】:Python mac adress matching and processingPython mac地址匹配与处理
【发布时间】:2013-05-30 17:23:02
【问题描述】:

python 版本 2.7.3

这是目前为止的“代码”:

import subprocess

p = subprocess.Popen(["pppoe-discovery", "-I", "eth0"], stdout=subprocess.PIPE)
output, err = p.communicate()

print output

这将给出一个包含所有发现的 pppoe 服务器的字符串

我的问题是提取所有 mac 地址并将每个地址与预定义的列表或字符串进行比较。

即使我可以找到并打印所有这些,作为一个初学者,我仍然不清楚找到一个解决方案来比较它们是否在列表中。 之后,我将编写一些 if “条件”并发送一封包含不匹配 mac-address 的电子邮件。

输出:

访问集中器:xxxx 服务名称:xxxx

得到一个 cookie:de 58 08 d0 66 c8 58 15 a0 66 9b b1 02 3f 7c 95 1f 42 00 00

AC-以太网地址:00:22:33:6b:4b:ee

这只是其中一台服务器,不胜枚举。

【问题讨论】:

  • 你得到什么输出?
  • 编辑后回答

标签: python mac-address pppoe


【解决方案1】:

你可以像这样用正则表达式过滤掉mac地址:

>>> import re
>>> input_string = "Access-Concentrator: xxxx Service-Name: xxxx Got a cookie: de 58 08 d0 66 c8 58 15 a0 66 9b b1 02 3f 7c 95 1f 42 00 00 -------------------------------------------------- AC-Ethernet-Address: 00:14:5e:6b:4b:ee –"
>>> mac = re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', input_string, re.I).group()
>>> mac
'00:14:5e:6b:4b:ee'

您可以像这样查看新找到的 MAC 地址是否已经在列表中:

>>> my_macs = ['00:14:5e:6b:4b:ee','00:14:5e:6b:4b:eb','00:14:5e:6b:4b:ec']
>>> mac in my_macs
True

添加:每行查找单个匹配项:

import re

my_macs = ['00:14:5e:6b:4b:ea','00:14:5e:6b:4b:eb','00:14:5e:6b:4b:ec']
mac = ''

strToFind = re.compile(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', re.I)

for line in output.split('\n'):
    results = re.search(strToFind, line)
    if results:
        mac = results.group()
    if mac not in my_macs:
        print mac

【讨论】:

  • 这可行,但仅适用于第一次出现,在我的情况下,mac 地址的数量在 1 到 30 之间是可变的,并且每个都必须与现有的 mac 列表进行比较。跨度>
  • 对于多次出现,您必须执行 re.findall()。但是,每行只有一个 mac。因此,您可以逐行遍历文件并以这种方式搜索 MAC 地址。我会尽快更新我的答案。
  • thx 的答案,我非常感谢帮助,但在您的示例中,您从文件中读取行,我需要通过运行命令从作为输出的字符串中获取“匹配”外壳 - “输出”。
  • 你可以做 output.split('\n') 得到相同的结果:)
  • 我无法让它工作给出一个错误:mac = re.search(strToFind , line).group() AttributeError: 'NoneType' object has no attribute 'group'
【解决方案2】:

上面给定的正则表达式["strToFind = re.compile(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', re.I)"] 将匹配最后一个八位字节中的无效值,例如'00:14:5e:6b:4b:eah'

所以对正则表达式稍作改动,只需用“$”结束最后一个八位字节。像这样:

strToFind = re.compile(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2}$)', re.I)

【讨论】:

    猜你喜欢
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2019-09-08
    • 2011-05-12
    • 2012-05-22
    • 1970-01-01
    • 2011-02-11
    相关资源
    最近更新 更多