我遇到了编辑使用线程的端口扫描程序的问题。 这是原始代码的基础知识:
for i in range(0, 2000): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : c = "Port %d: OPEN\n" % (i,) s.close()
这大概需要33分钟才能完成。 所以我想我会把它加快一点。 这是我的第一个线程项目,所以没有太大的意义,但是我已经运行了下面的代码大约一个小时,没有任何exception但没有输出。 我只是在做线程错误还是什么?
import threading from socket import * import time a = 0 b = 0 c = "" d = "" def ScanLow(): global a global c for i in range(0, 1000): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : c = "Port %d: OPEN\n" % (i,) s.close() a += 1 def ScanHigh(): global b global d for i in range(1001, 2000): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : d = "Port %d: OPEN\n" % (i,) s.close() b += 1 Target = raw_input("Enter Host To Scan:") TargetIP = gethostbyname(Target) print "Start Scan On Host ", TargetIP Start = time.time() threading.Thread(target = ScanLow).start() threading.Thread(target = ScanHigh).start() e = a + b while e < 2000: f = raw_input() End = time.time() - Start print c print d print End g = raw_input()
这是你的代码失败的地方。
threading.Thread(target = ScanLow).start() threading.Thread(target = ScanHigh).start() e = a + b while e < 2000: f = raw_input()
在开始线程之后,立即将值设置为e
。 但是,在此之后,您从不更新e
,因此循环不会退出。
这也好像你正在这样做,等到两个线程完成。 join()
方法是一个更好的方法来做到这一点。
from threading import Thread threads = [] threads.append(Thread(target = ScanLow)) threads.append(Thread(target = ScanHigh)) for thread in threads: thread.start() //both threads are running for thread in threads: thread.join() //both threads have stopped
编辑:不涉及到你的问题,但一个有用的评论。 两个扫描功能都在做同样的事情。 您可以将它们替换为一个函数,将扫描范围作为参数,并使用一个函数启动两个线程。
from threading import Thread def Scan(start, stop): global a global c for i in range(start, stop): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : c = "Port %d: OPEN\n" % (i,) s.close() a += 1 threadCount = 2 totalPorts = 2000 threads = [] for start in xrange(0, totalPorts, totalPorts/threadCount): threads.append(Thread(target = Scan, args = (start, totalPorts/threadCount))) for thread in threads: thread.start() //both threads are running for thread in threads: thread.join() //both threads have stopped
现在您可以轻松调整要扫描的线程和端口的数量。
你有一个尴尬的方法来监视线程。 使用join
将指示线程何时完成。 没有理由不分散更多的线程来获得更快的结果:
import threading import socket import time ports = [] def check_port(ip,port): s = socket.socket() if s.connect_ex((ip,port)) == 0: ports.append(port) s.close() target = raw_input('Target? ') s = time.time() threads = [] for port in range(2000): t = threading.Thread(target=check_port,args=(target,port)) t.start() threads.append(t) for t in threads: t.join() print ports print time.time() - s
[80, 135, 445, 1028] 6.92199993134