0xtv

Simple port scanner

Dec 8th, 2013
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from socket import *
  5. from threading import Thread
  6. from Queue import Queue
  7.  
  8. def scan(ip,port):
  9.     s=socket(AF_INET,SOCK_STREAM)
  10.     result=s.connect_ex((ip,port))
  11.     if(result==0):
  12.         print 'Port %d: OPEN' % port
  13.     s.close()
  14.  
  15. class Worker(Thread):
  16.     def __init__(self,taskQueue):
  17.         Thread.__init__(self)
  18.         self.setDaemon(True)
  19.         self.taskQueue=taskQueue
  20.         self.start()
  21.  
  22.     def run(self):
  23.         while True:
  24.             try:
  25.                 callable,args,kwds=self.taskQueue.get(block=False)
  26.                 callable(*args,**kwds)
  27.             except:
  28.                 break
  29.  
  30. class ThreadPool:
  31.     def __init__(self,ip):
  32.         self.threads=[]
  33.         self.taskQueue=Queue()
  34.         self.threadNum=10
  35.         self.__create_taskqueue(ip)
  36.         self.__create_threadpool(self.threadNum)
  37.  
  38.     def __create_taskqueue(self,ip):
  39.         for i in range(20,10000):
  40.             self.add_task(scan,ip,i)
  41.  
  42.     def __create_threadpool(self,threadNum):
  43.         for i in range(threadNum):
  44.             thread=Worker(self.taskQueue)
  45.             self.threads.append(thread)
  46.  
  47.     def add_task(self,callable,*args,**kwds):
  48.         self.taskQueue.put((callable,args,kwds))
  49.  
  50.     def waitfor_complete(self):
  51.         while len(self.threads):
  52.             thread=self.threads.pop()
  53.             thread.join()
  54.             if thread.isAlive() and not self.taskQueue.empty():
  55.                 self.threads.append(thread)
  56.         print 'scaning is over!'
  57.  
  58. if __name__=='__main__':
  59.     target=raw_input('Enter host to scan:')
  60.     targetIP=gethostbyname(target)
  61.     print 'Starting scan on host',targetIP
  62.     tp=ThreadPool(targetIP)
  63.     tp.waitfor_complete()
Advertisement
Add Comment
Please, Sign In to add comment