Amn*_*ite 3 python windows multithreading port-scanning
我正在编辑端口扫描程序,我正在编辑使用线程.这是原始代码的基础知识:
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()
Run Code Online (Sandbox Code Playgroud)
这大约需要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()
Run Code Online (Sandbox Code Playgroud)
这是您的代码失败的地方.
threading.Thread(target = ScanLow).start()
threading.Thread(target = ScanHigh).start()
e = a + b
while e < 2000:
f = raw_input()
Run Code Online (Sandbox Code Playgroud)
启动线程后,立即将值设置为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
Run Code Online (Sandbox Code Playgroud)
编辑: 与您的问题无关,但是有用的评论.两个扫描功能都完全相同.您可以使用一个将扫描范围作为参数的函数替换它们,并使用一个函数启动两个线程.
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
Run Code Online (Sandbox Code Playgroud)
现在,您可以轻松调整要扫描的线程和端口数.