【问题标题】:Using console commands in python在 python 中使用控制台命令
【发布时间】:2016-10-08 03:46:16
【问题描述】:

我在 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。我上面的代码没有检索到。我的问题是如何使用控制台命令来获得我想要的值。

提前致谢。

【问题讨论】:

    标签: python linux console command nic


    【解决方案1】:

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

    对于接口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()
    

    【讨论】:

    • 我试过这个,但它仍然没有打印出值
    • @Nikkibee 你确定你使用了正确的接口名称吗?首先检查直接在终端中运行命令..
    • @Nikkibee:heemayl 的代码只获取信息,不打印。
    【解决方案2】:

    引用自here

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

    from uuid import getnode as get_mac
    mac = get_mac()
    

    返回值为48位整数的mac地址。

    【讨论】:

      【解决方案3】:
      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),具体取决于您是否将命令作为列表传递,如果您根据 this 明确提及您的 python 路径,则可以解决此问题/p>

      【讨论】:

      • subprocess 中读取带有cat 的(伪)文件与在Python 文件中读取文件的常规方式相比非常效率低下。
      • 当然效率不高! OP 想在 python 中使用控制台命令,因此得到了答案。我已经编辑了我的答案以包含这个事实。
      猜你喜欢
      • 2016-02-07
      • 2016-01-29
      • 1970-01-01
      • 2016-08-29
      • 2016-02-08
      • 2019-03-25
      • 2014-02-23
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多