Reputation: 27
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:9E:D5:C7:1z:EF
eth1 Link encap:Ethernet HWaddr 30:0E:95:97:0A: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.
Upvotes: 0
Views: 979
Reputation: 388
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())
Or as per user heemayl,
command = "cat /sys/class/net/eth1/address"
print "%s" %(getmac(command))
Note:
1. Using shell=True
isn't recommended as per Python docs
2. This isn't as efficient compared to the normal ways of reading a file in Python.
You could have also returned
subprocess.check_output(command)
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
Upvotes: 0
Reputation: 512
Quoting from here.
Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:
from uuid import getnode as get_mac
mac = get_mac()
The return value is the mac address as 48 bit integer.
Upvotes: 1
Reputation: 42037
The most robust and easy way in Linux to get the MAC address is to get it from sysfs
, mounted on /sys
.
For interface etho
, the location would be /sys/class/net/eth0/address
; Similarly for eth1
, it would be /sys/class/net/eth1/address
.
% cat /sys/class/net/eth0/address
74:d4:35:XX:XX:XX
So, you could just read the file in python
too:
with open('/sys/class/net/eth0/address') as f:
mac_eth0 = f.read().rstrip()
Upvotes: 1