我如何稀疏getmac命令的输出?

问题描述 投票:0回答:1

经过一些研究,我发现在Windows下获取以太网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

这是示例输出

物理地址传输名称================================================== ==========================1C-69-7A-3A-E3-40媒体已断开54-8D-5A-CE-21-1A \ Device \ Tcpip_ {82B01094-C274-418F-AB0A-BC4F3660D6B4}

我最终希望获得1C-69-7A-3A-E3-40,最好不要使用破折号。预先感谢。

python windows mac-address
1个回答
0
投票

两件事。首先,我建议您找到更优雅地获取mac地址的方法。 This question's answer seems to use the uuid module,这也许是一个很好的跨平台解决方案。

已经说过,如果要继续解析系统调用的输出,建议使用Python的subprocess module。例如:

import subprocess

output_of_command = subprocess.check_output("getmac")

这将运行getmac,该命令的输出将进入变量。从那里,您可以解析字符串。

这是从该字符串中提取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]

第一个分割是右分割。从字符串末尾开始,它一次用'='字符将字符串分开。然后,我将其输出用空格分割,限制为一个分割,并采用第一个字符串值。

但是,同样,我不鼓励这种方法获取Mac地址。很少建议解析人类可读的命令行脚本输出,因为该输出可能出乎意料地不同于您的脚本期望的输出。您可以肯定地以更可靠的方式获取mac地址。

© www.soinside.com 2019 - 2024. All rights reserved.