标签:
从单线程到多线程版,一次迭代
# coding:utf-8 # author:jwong import sys from socket import * def main(start_port, end_port, host): target_ip = gethostbyname(host) opened_ports = [] for port in range(start_port, end_port): print "port scanning is %s " % port sock = socket(AF_INET, SOCK_STREAM) sock.settimeout(1) result = sock.connect_ex((target_ip, port)) if result == 0: opened_ports.append(port) print_port() def print_port(): print("Opened ports:") for i in opened_ports: print "%s \n" % i if __name__ == ‘__main__‘: if len(sys.argv) < 3: print ‘useage python 192.168.1.1 1-65535‘ exit(0) host = sys.argv[1] portstrs = sys.argv[2].split(‘-‘) start_port = int(portstrs[0]) end_port = int(portstrs[1]) main(start_port, end_port, host)
多线程版本1:
# coding:utf-8 # author:jwong import threading import Queue from socket import * queue = Queue.Queue() thread_num = 20 def scan(target): opened_ports = [] while not queue.empty(): port = queue.get() sock = socket(AF_INET, SOCK_STREAM) sock.settimeout(2) result = sock.connect_ex((host, port)) if result == 0: opened_ports.append(port) for i in opened_ports: print "%s \n" % i host = ‘192.168.31.232‘ lists = [22, 25, 80, 8080, 81, 1433, 3306] # 放入队列中 for list in lists: queue.put(list) for i in range(thread_num): s = threading.Thread(target=scan, args=(host,)) s.start()
增加了线程锁,防止阻塞
# coding:utf-8 # author:jwong import socket import time import thread def connect(ip, port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((ip, host)) if result == 0: lock.acquire() print ip ‘:‘,port,‘open‘ lock.release() sock.close() except: print ‘port scan error!‘ def scan(ip): try: print ‘start scan now!‘ start_time = time.time() for i range(0,65534): thread.start_new_thread(connect, (ip,int(i))) print ‘total time in scan %.2f‘ % (time.time()-start_time) raw_input(‘press anykey to exit!‘) except : print ‘ip scan error!!‘ if __name__ == ‘__main__‘: url=raw_input(‘Input the ip you want to scan:\n‘) lock = thread.allocate_lock() scan(url)
标签:
原文地址:http://www.cnblogs.com/jwong/p/5444110.html