我在使用线程编辑端口扫描器时遇到问题。 这是原始代码的基础:
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 分钟才能完成。所以我想我应该给它线程,让它运行得更快一些。这是我的第一个线程项目,所以它不是太极端,但我已经运行了以下代码大约一个小时并且没有出现异常但也没有输出。我只是做错了线程还是什么?
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
现在您可以轻松调整要扫描的线程数和端口数。
关于python - 线程 Python 端口扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4640527/