import commands, re, json, urllib2, binascii
PREFIX = "192.168.1" #Network prefix
MIN = "0" #Starting network address, eg 192.168.1.0
MAX = "12" #Closing network address, e.g. 192.168.1.55
results = []
def escapeMe(message): #Escape characters (using ASCII value) not allowed in JSON
new = ""
for num in range(len(message)):
char_code = ord(message[num])
if char_code < 32 or char_code == 39 or char_code == 34 or char_code == 92:
new = new + "%" + binascii.hexlify(message[num])
else:
new = new + message[num]
return new
def sendDevice(gotcha): #Send the device report to the server as a POST
try:
url = "http://127.0.0.1:3707/new/" #Server address
gotcha = escapeMe(gotcha)
values = json.dumps({'device' : str(gotcha)})
req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
rsp = urllib2.urlopen(req, values)
code = rsp.getcode()
except Exception, e:
print e
def removeDevice(ip): #Send request to remove device
try:
ip = ip.replace('.','-')
url = "http://127.0.0.1:3707/remove/"+ip+"/"
rsp = urllib2.urlopen(url)
code = rsp.getcode()
except Exception, e:
print e
def main():
global results
while 1:
new = commands.getoutput('for i in {'+MIN+'..'+MAX+'}; do ping -c 1 -t 1 '+PREFIX+'.$i | grep "from"; done') #Ping sweep the network to find connected devices
tmp = re.findall(PREFIX+".(d+)", str(new)) #Pull out IP addresses from the ping results
if tmp != results:
for ip in tmp:
if ip not in results:
gotcha = commands.getoutput('nmap -v -A -Pn '+PREFIX+'.'+ip) #nmap new devices found on the network
sendDevice(gotcha) #send device record to server
for r in results:
if r not in tmp:
removeDevice(PREFIX+'.'+r) #remove device if it wasn't found in the latest ping
results = tmp
if __name__ == "__main__":
main()