I recently wanted to write some python since I've been relegated to the worlds of Java and sometimes C being a college student again. As a fun and paranoid project, I put together a little script that generates a random mac address and optionally assigns that MAC address to an interface and restarts your network connection.
I initially haven't made it all that complicated or general purpose (for instance, it assumes you're using network-manager, as I guess most of us are now). The relevant functions are below, but I'd be happy to post the whole script or make it more versatile / general if anyone is interested... post a comment or send me an email.
def mac():
"""
Returns a randomly generated Unicast MAC Address.
Returns:
String - A mac address.
"""
mac = '';
i = 0
count = 6
while i < count:
# If the least significant bit of the first bite is onw,
# ifconfig will fail because those addrs are reserved for multicast
odd_hex = ['1', '3', '5', '7', '9', 'b', 'd', 'f']
octet = hex(random.randint(0, 255))
octet = octet.replace('0x', '')
if len (octet) == 1:
octet = '0' + octet
if (i != 0) or (octet[len(octet)-1] not in odd_hex):
mac += octet
if i != 5:
mac += ':'
i=i+1
return mac
def restartNetwork(iface):
"""
Assign a random mac address to the given interface and
restarts network-manager to pick up the changes.
TODO: error checking for a valid iface.
Args:
iface: String representing an assumed valid network interface.
"""
new_mac = mac()
subprocess.call(['/etc/init.d/network-manager', 'stop'])
ifconfig = ['/sbin/ifconfig', iface, 'down']
subprocess.call(ifconfig)
#print subprocess.call('/sbin/ifconfig')
ifconfig = ['/sbin/ifconfig', iface, 'hw','ether', new_mac]
subprocess.call(ifconfig)
subprocess.call(['/etc/init.d/network-manager', 'start'])
print "If everything went as planned, %s should now have " \
"mac address:" % iface
print new_mac
Tuesday, September 11, 2012
Subscribe to:
Posts (Atom)