16 October 2008

Handy Python Snippets

Obtaining the local IP address (getip.py)
#!/usr/bin/env python

def getip():
from socket import gethostbyaddr, gethostname
theip = gethostbyaddr(gethostname())[2][0]
return theip


Obtaining the local MAC address (getmac.py)
#!/usr/bin/env python

def getmac():
import sys, os
if sys.platform == 'win32':
for line in os.popen("ipconfig /all"):
if line.lstrip().startswith('Physical Address'):
mac = line.split(':')[1].strip().replace('-',':')
break
else:
for line in os.popen("/sbin/ifconfig"):
if line.find('Ether') > -1:
mac = line.split()[4]
break
return mac


Putting these together (test.py)
#!/usr/bin/env python
import getmac, getip

myip = getip.getip()
mymac = getmac.getmac()

print mymac + " has address: " + myip

No comments:

Post a Comment