Created
July 23, 2013 19:23
-
-
Save xavierskip/6065360 to your computer and use it in GitHub Desktop.
ip and mac
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#-*- coding:utf-8 -*- | |
import socket | |
def get_ipaddress(): | |
try: | |
return socket.gethostbyname(socket.gethostname()) | |
except Exception, e: | |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
s.connect(("baidu.com",80)) | |
ip = s.getsockname()[0] | |
s.close() | |
return ip | |
def get_macaddress(host): | |
import sys,re | |
re = re.compile('linux') | |
math = re.search(sys.platform) | |
if math: | |
import uuid | |
return uuid.UUID(int = uuid.getnode()).hex[-12:] | |
else: | |
return win_mac(host) | |
def win_mac(host): | |
""" Returns the MAC address of a network host, requires >= WIN2K. | |
""" | |
import ctypes | |
import struct | |
# Check for api availability | |
try: | |
SendARP = ctypes.windll.Iphlpapi.SendARP | |
except: | |
raise NotImplementedError('Usage only on Windows 2000 and above') | |
# Doesn't work with loopbacks, but let's try and help. | |
if host == '127.0.0.1' or host.lower() == 'localhost': | |
host = socket.gethostname() | |
# gethostbyname blocks, so use it wisely. | |
try: | |
inetaddr = ctypes.windll.wsock32.inet_addr(host) | |
if inetaddr in (0, -1): | |
raise Exception | |
except: | |
hostip = socket.gethostbyname(host) | |
inetaddr = ctypes.windll.wsock32.inet_addr(hostip) | |
buffer = ctypes.c_buffer(6) | |
addlen = ctypes.c_ulong(ctypes.sizeof(buffer)) | |
if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen)) != 0: | |
raise WindowsError('Retreival of mac address(%s) - failed' % host) | |
# Convert binary data into a string. | |
macaddr = [] | |
for intval in struct.unpack('BBBBBB', buffer): | |
if intval > 15: | |
replacestr = '0x' | |
else: | |
replacestr = 'x' | |
macaddr.append(hex(intval).replace(replacestr, '')) | |
return ':'.join([i.upper() for i in macaddr ]) | |
if __name__ == '__main__': | |
import sys | |
deparment = sys.argv[1] | |
name = sys.argv[2] | |
ip = get_ipaddress() | |
mac = get_macaddress(ip) | |
line = '%s\t%s\t%s\t%s' %(ip,mac,deparment,name) | |
note = sys.argv[3:] | |
if note: | |
line += '\t#%s' %','.join([i for i in note]) | |
print line | |
raw_input() | |
f = open('register.txt','a+') | |
f.write(line) | |
f.write('\n') | |
f.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment