在 python 中使用控制台命令

Using console commands in python

我在 python 中使用控制台命令,但是,它没有输出我想要的值。

路径为:

#ifconfig -a | grep "HWaddr"

从这个命令我得到:

eth0     Link encap:Ethernet HWaddr 30:9E:D5:C7:1z:EF
eth1     Link encap:Ethernet HWaddr 30:0E:95:97:0A:F0

我需要使用控制台命令来检索该值,所以这是我目前的代码:

def getmac():
    mac=subprocess.check_output('ifconfig -a | grep "HWaddr"')
print "%s" %(mac)

我基本上只想检索 30:0E:D5:C7:1A:F0 的硬件地址。我上面的代码没有检索到它。我的问题是如何使用控制台命令来获取我想要的值。

提前致谢。

在 Linux 中获取 MAC 地址的最可靠和最简单的方法是从 sysfs 获取它,安装在 /sys.

对于接口 etho,位置将是 /sys/class/net/eth0/address;同样,对于 eth1,它将是 /sys/class/net/eth1/address

% cat /sys/class/net/eth0/address 
74:d4:35:XX:XX:XX

因此,您也可以阅读 python 中的文件:

with open('/sys/class/net/eth0/address') as f:
    mac_eth0 = f.read().rstrip()

引用自here

Python 2.5 包含一个 uuid 实现(至少在一个版本中)需要 mac 地址。您可以轻松地将 mac 查找功能导入到您自己的代码中:

from uuid import getnode as get_mac
mac = get_mac()

return 值是作为 48 位整数的 mac 地址。

import subprocess

def getmac(command):
    return subprocess.check_output(command, shell=True)

command = "ifconfig -a | grep HWaddr" 
print "%s" %(getmac(command).split()[9])
# or print out the entire list to see which index your HWAddr corresponds to
# print "%s" %(getmac(command).split())

或根据用户 heemayl,

command = "cat /sys/class/net/eth1/address"
print "%s" %(getmac(command))

注:
1. 根据 Python docs
不推荐使用 shell=True 2. 与 Python.

中读取文件的常规方式相比,这效率不高

你也可以回来

subprocess.check_output(command)

但是,在上述情况下,您可能会得到 OSErrorCalledProcessError(retcode, cmd, output=output),具体取决于您是否将命令作为列表传递,如果您明确提及 python 路径根据 this