Donnerstag, 2. Juli 2009

PYTHON: simple scanner in python

this is a simple scanner in python.

work: call a system ping (with popen() ) and look for ttl count.
if count ~64 -> linux, count ~128 -> windows, count ~255 -> BSD/Router

then it connect to well known ports and look for respond.

limits: only certain ports and only TCP

trace2.py
###################################################################

#!/usr/bin/python

import sys, os, socket, re


class Scan:
def __init__(self):
#print "create socket ..."
self.scanNew=None
self.allPorts={"ftp-data":20, "ftp":21,"smtp":25, "http":80, "pop3":110, "imap3":220, "https":443,
"ldap":389 }
self.linuxPorts={"ssh":22, "dns":53, "snmp":161, "snmp-trap":162}
self.windowPorts={"netbios-ns":137, "netbios-dgm":138, "netbios-ssn":139,"microsoft-ds":445 }

def ping(self, ip):
findttl = re.compile(r"ttl=(\d{1,3}) ")
pingpipe = os.popen("ping -W 1 -c 1 "+ip,"r")
for line in pingpipe.readlines():
if "ttl" in line:
result = re.findall(findttl,line)
return int(result[0])
return -1

def connectTCP(self, ip, port, portname):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
try:
s.connect((ip, port))
print "connect to %s : %d (%s) was succesfull"%(ip, port, portname)
except:
pass
#print "failing to connect %s : %d (%s)"%(ip, port, portname)
s.close()

def scann(self, ip):
ttl=self.ping(ip)
if( ttl==-1):
print "IP %s not reachable"%ip
elif( ttl==0 ):
print "huch, ttl is zero"
elif( ttl>0 and ttl<65 ):
print " %s possible LINUX and is Alive"%ip
for port in self.allPorts.keys():
self.connectTCP(ip, self.allPorts[port], port)
for port in self.linuxPorts.keys():
self.connectTCP(ip, self.linuxPorts[port], port)
elif( ttl>64 and ttl<129 ):
print " %s possible WINDOWS and is Alive"%ip
for port in self.allPorts.keys():
self.connectTCP(ip, self.allPorts[port], port)
for port in self.windowPorts.keys():
self.connectTCP(ip, self.windowPorts[port], port)
else:
print " %s possible BSD or Router and is Alive"%ip
for port in self.allPorts.keys():
self.connectTCP(ip, self.allPorts[port], port)
for port in self.linuxPorts.keys():
self.connectTCP(ip, self.linuxPorts[port], port)

if( len(sys.argv) != 4):
print "%s ip(first triple) begin end"%sys.argv[0]
print " example:"
print " %s 123.45.67 10 20"%sys.argv[0]
sys.exit(2)

iptriple=sys.argv[1]
begin=int(sys.argv[2])
end=int(sys.argv[3])

scan=Scan()

for ip4 in range(begin, end):
ip="%s.%d"%(iptriple,ip4)
scan.scann(ip)

###################################################################

Keine Kommentare:

Kommentar veröffentlichen