我正在编写一个 Python 脚本,用于连接到 Cisco IOS 设备并从特定命令收集特定信息。
我正在尝试为未经身份验证的设备添加“show log”命令中列出的 MAC 地址。我尝试过直接在 IOS 命令行中执行将命令管道输出到 Regex,因为我看到多个消息来源说它应该可以工作......但我无法让它工作(不担心这一点)
当我尝试使用 Python 匹配正则表达式时,它会匹配所有内容,但会截掉 mac 地址的最后一个字符。
代码:
macpattern = re.compile(r"([A-Za-z0-9]{1,4}\.[A-Za-z0-9]{1,4}\.[A-Za-z0-9]{1,4})\w+")
for line in f:
macTest = macpattern.findall(line)
print(line)
MAC 地址示例为:“0024.c40c.4f45”
正则表达式给出的输出是“0024.c40c.4f4”,切断最后一个字符。我不明白为什么它要切断它。有人可以帮忙吗?
使用
macpattern = re.compile(r"\b[A-Za-z0-9]{1,4}\.[A-Za-z0-9]{1,4}\.[A-Za-z0-9]{1,4}\b")
macResults = macpattern.findall(f.read())
print(macResults)
参见正则表达式证明。
使用
f.read()
将整个文件读入字符串变量,当您想要收集匹配项时使用起来更方便。
表达式解释
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
[A-Za-z0-9]{1,4} any character of: 'A' to 'Z', 'a' to 'z',
'0' to '9' (between 1 and 4 times
(matching the most amount possible))
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
[A-Za-z0-9]{1,4} any character of: 'A' to 'Z', 'a' to 'z',
'0' to '9' (between 1 and 4 times
(matching the most amount possible))
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
[A-Za-z0-9]{1,4} any character of: 'A' to 'Z', 'a' to 'z',
'0' to '9' (between 1 and 4 times
(matching the most amount possible))
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char