Skip to content

Instantly share code, notes, and snippets.

@icedraco
Last active November 13, 2015 22:05
Show Gist options
  • Select an option

  • Save icedraco/3ae2c42e6f18d2d6d279 to your computer and use it in GitHub Desktop.

Select an option

Save icedraco/3ae2c42e6f18d2d6d279 to your computer and use it in GitHub Desktop.
Hostname, IP and MAC probing script. Used to obtain information from a distributed system by remotely activating it on each node.
#!/usr/bin/python
import os
import uuid
# Data gathered from a single host will be stored here (on that same host)
DATA_PATH = "/home/icedragon/probe-result"
#--- INTERFACE PROBING ---------------------------------------------------------
import fcntl
import array
import struct
import socket
import platform
SIOCGIFCONF = 0x8912
MAXBYTES = 8096
# Returns a list of (interface, ipaddr) pairs discovered
# Example:
# [('lo', '127.0.0.1'), ('eth0', '192.168.119.129')]
def localifs():
global SIOCGIFCONF
global MAXBYTES
arch = platform.architecture()[0]
if arch == '32bit':
var1 = 32
var2 = 32
elif arch == '64bit':
var1 = 16
var2 = 40
else:
raise OSError("Unknown architecture: %s" % arch)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * MAXBYTES)
outbytes = struct.unpack('iL', fcntl.ioctl(
sock.fileno(),
SIOCGIFCONF,
struct.pack('iL', MAXBYTES, names.buffer_info()[0])
))[0]
namestr = names.tostring()
return [(namestr[i:i+var1].split('\0', 1)[0], socket.inet_ntoa(namestr[i+20:i+24])) \
for i in xrange(0, outbytes, var2)]
#--- Other ---------------------------------------------------------------------
def filter_localhost(iface):
return iface[0] != 'lo'
def add_dns(iface):
hostname = iface[1]
try:
hostname = socket.gethostbyaddr(iface[1])[0]
except:
pass
return (iface[0], iface[1], hostname)
def format_mac(mac):
# Convert to a hex string, ditch the "0x" and the "L", and zero-pad to 12 digits
return hex(mac)[2:-1].zfill(12)
def store(mac, iface):
global DATA_PATH
(name, ip, hostname) = iface
open(os.path.join(DATA_PATH, "%s-%s" % (hostname, name)), 'w').write(
"\t".join([mac, name, ip, hostname]) + "\n")
def probe():
socket.setdefaulttimeout(3)
mac = format_mac(uuid.getnode())
ifaces = map(add_dns, filter(filter_localhost, localifs()))
for iface in ifaces:
store(mac, iface)
if __name__ == "__main__":
probe()
raise SystemExit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment