scripts

random scripts
git clone git://parazyd.org/scripts.git
Log | Files | Refs

portscan.py (2244B)


      1 #!/usr/bin/env python
      2 
      3 import socket
      4 import sys
      5 import threading
      6 import time
      7 
      8 class counter():
      9     def __init__(self):
     10         self.lock = threading.Lock()
     11         self.port = 0
     12 
     13     def nextport(self):
     14         self.lock.acquire()
     15         if self.port >= 0:
     16             self.port += 1
     17             if self.port >= 65536:
     18                 self.port = -1
     19         port = self.port
     20         self.lock.release()
     21         return port
     22 
     23 class scanner(threading.Thread):
     24     tlist = []
     25     pc = counter()
     26 
     27     def __init__(self):
     28         threading.Thread.__init__(self)
     29         self.port = scanner.pc.nextport()
     30 
     31     def run(self):
     32         while (self.port > 0):
     33             s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     34             s.setblocking(0)
     35             try:
     36                 print("(*) opening conn to %s:%s\r" % (host, self.port))
     37                 s.connect((host, self.port))
     38             except socket.error, e:
     39                 if e[0] != 155:
     40                     raise
     41 
     42             try:
     43                 time.sleep(timo)
     44                 s.send("")
     45                 s.shutdown(socket.SHUT_RDWR)
     46                 print("- port %s is open" % (self.port))
     47             except socket.error:
     48                 #print("- port %s is probably closed" % (self.port))
     49                 pass
     50             finally:
     51                 s.close()
     52             self.port = scanner.pc.nextport()
     53 
     54     def main():
     55         global host, timo
     56 
     57         if len(sys.argv) < 2:
     58             print("usage: portscan.py [host] [maxthreads] [timeout]")
     59             print("scans a host's TCP ports with conn attempts with a given")
     60             print("response timeout (default 1s).")
     61             sys.exit(1)
     62 
     63         host = sys.argv[1]
     64         maxt = int(sys.argv[2]) if len(sys.argv) > 2 else 666
     65         timo = int(sys.argv[3]) if len(sys.argv) > 3 else 1
     66         start = time.time()
     67 
     68         print("(*) port scanning %s, %s ports at a time, timeout %s seconds" % (host, maxt, timo))
     69 
     70         for i in range(0, maxt):
     71             sc = scanner()
     72             scanner.tlist.append(sc)
     73             sc.start()
     74         for sc in scanner.tlist:
     75             sc.join()
     76 
     77         print("(*) scan completed in %s seconds!" % (time.time() - start))
     78 
     79     if __name__=="__main__":
     80         main()
     81