[英]How do I parse the output of getmac command?
在做了一些研究之后,我发现获取 windows 下的 Ethe.net MAC 地址的最佳方法是“getmac”命令。 (python 的 getmac 模块不产生相同的..):现在我想从 python 代码中使用这个命令来获取 MAC 地址。 我发现我的代码应该像这样开始:
import os
if sys.platform == 'win32':
os.system("getmac")
do something here to get the first mac address that appears in the results
这是一个例子 output
Physical Address Transport Name
=================== ==========================================================
1C-69-7A-3A-E3-40 Media disconnected
54-8D-5A-CE-21-1A \Device\Tcpip_{82B01094-C274-418F-AB0A-BC4F3660D6B4}
我终于想要 1C-69-7A-3A-E3-40 最好没有破折号。 提前致谢。
两件事情。 首先,我建议您找到更优雅地获取 mac 地址的方法。 This question's answer seems to use the uuid module ,这也许是一个很好的跨平台解决方案。
话虽如此,如果你想继续解析系统调用的 output,我推荐使用 Python 的subprocess 模块。 例如:
import subprocess
output_of_command = subprocess.check_output("getmac")
这将运行getmac
,该命令的 output 将 go 转换为一个变量。 从那里,您可以解析字符串。
以下是从该字符串中提取 mac 地址的方法:
# I'm setting this directly to provide a clear example of the parsing, separate
# from the first part of this answer.
my_string = """Physical Address Transport Name
=================== ==========================================================
1C-69-7A-3A-E3-40 Media disconnected
54-8D-5A-CE-21-1A \Device\Tcpip_{82B01094-C274-418F-AB0A-BC4F3660D6B4}"""
my_mac_address = my_string.rsplit('=', 1)[-1].split(None, 1)[0]
第一次分裂是右分裂。 它从字符串的末尾开始一次按“=”字符拆分字符串。 然后,我将其中的 output 按空格拆分,限制为一次拆分,并获取第一个字符串值。
但是,我再次反对这种获取 mac 地址的方法。 很少建议解析人类可读的命令行脚本 output,因为 output 可能会意外地与您的脚本所期望的不同。 您肯定可以以更可靠的方式获取 mac 地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.