Nikki bee Nikki bee - 4 months ago 12x
Linux Question

Using console commands in python

I am using console commands in python, however, it is not outputting the value I want.

The path is:

#ifconfig -a | grep "HWaddr"

From this command I get:

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

I need to use console commands to retrieve that value, so this is what I have so far for code:

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

I basically only want to retrieve the hardware address which is 30:0E:D5:C7:1A:F0. My code above doesn't retrieve that. My question is how do I use console commands to get the value I want.

Thanks in advance.

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())

Note: Using shell=True isn't recommended as per Python docs

You could have also returned


However, in the above case, you might get an OSError or a CalledProcessError(retcode, cmd, output=output) depending on whether you passed your commands as a list, which can be solved if you explicitly mention your python path as per this