TCP扫描程序Python MultiThreaded

时间:2012-12-14 05:00:33

标签: python multithreading tcp

我正在尝试为网络掩码构建一个小型tcp扫描程序。

代码如下:

import socket,sys,re,struct
from socket import *


host = sys.argv[1]

def RunScanner(host):
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((host,80))
    s.settimeout(0.1)  
    String = "GET / HTTP/1.0"
    s.send(String)
    data = s.recv(1024)
    if data:
       print "host: %s have port 80 open"%(host)

Slash = re.search("/", str(host))

if Slash :
   netR,_,Wholemask = host.partition('/')
   Wholemask = int(Wholemask)
   netR = struct.unpack("!L",inet_aton(netR))[0]
   for host in (inet_ntoa(struct.pack("!L", netR+n)) for n in range(0, 1<<32-Wholemask)):
      try:
         print "Doing host",host
         RunScanner(host)
      except:
         pass
else:
   RunScanner(host)

启动:python script.py 10.50.23.0/24

我遇到的问题是,即使设置了一个荒谬的低settimeout值,也需要很长时间才能覆盖255个ip地址,因为大多数地址都没有分配给一台机器。

如果端口关闭,我怎样才能使速度更快的扫描仪不会卡住。多线程?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试使用线程来做我过去所做的事情。用您的输入更改它应该超级容易:

import socket
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool 

def scan(d):
    s = socket.socket()
    s.settimeout(0.1)
    port = 80  # port number is a number, not string
    try:
        address = '192.168.0.' + str(d)
        s.connect((address, port)) 
    except Exception as e: 
        print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
    finally:
        s.close()

pool = ThreadPool() 

d = range(1, 255)
pool.map(scan, d)

pool.close()
pool.join()