Python只是让主线程休眠
我在主线程中使用time.sleep(),只想让这个线程睡眠。问题是,我在main中创建的所有其他线程也在休眠。一个问题可能是他们必须访问一个全局变量。 这样做的目的就是不要一次创建太多的线程——因此我计算运行的线程,如果它们>200,我希望让主线程休眠,以便给其他线程更多的时间Python只是让主线程休眠,python,python-3.x,multithreading,python-multithreading,Python,Python 3.x,Multithreading,Python Multithreading,我在主线程中使用time.sleep(),只想让这个线程睡眠。问题是,我在main中创建的所有其他线程也在休眠。一个问题可能是他们必须访问一个全局变量。 这样做的目的就是不要一次创建太多的线程——因此我计算运行的线程,如果它们>200,我希望让主线程休眠,以便给其他线程更多的时间 import requests import ipaddress import sys import threading import time loginIndicators = ["username",
import requests
import ipaddress
import sys
import threading
import time
loginIndicators = ["username", "user name", "password", "passwort", "log in", "sign in", "anmelden", "signin", "login", "submit", "account", "user", "pass", "id", "authentification", "authentication", "auth", "authorization", "access", "passphrase", "key"]
scancounter = 0
def scan(ip, port, protocol):
global scancounter
global file
try:
res = requests.get(protocol + "://" + ip.exploded + ":" + port + "/", timeout=1)
except:
return
finally:
scancounter += 1
if res.status_code == 401 or any(indicator in res.text.lower() for indicator in loginIndicators):
print("Found: " + ip.exploded + ":" + port + " --> " + protocol)
file.write(protocol + "://" + ip.exploded + ":" + port + "\n")
def output_status(end):
global scancounter
if(end):
time.sleep(3)
print("Scanned: " + str(int(scancounter / len(ports) / 2)))
try:
if __name__ == "__main__":
try:
nw = ipaddress.ip_network(input("Enter the starting IP address: "))
except:
print("Invalid format - expected: IP/prefix")
sys.exit()
ports = input("Enter the ports that should be tested: ")
if ports == "":
ports = ["80","8080","443"]
else:
ports = ports.replace(" ", "")
ports = ports.split(",")
file = input("Output file path: ")
if file != "":
file = open(file, "a")
iprange = nw.hosts()
try:
skip = input("How many addresses do you want to skip: ")
if skip == "":
skip = 0
for i in range(0, int(skip)):
next(iprange)
except:
print("You can't skip more addresses than the IP range contains!")
for ip in iprange:
for port in ports:
threading.Thread(target=scan, args=(ip, port, "http",)).start()
threading.Thread(target=scan, args=(ip, port, "https",)).start()
threading.Thread(target=output_status, args=(True,)).start()
except KeyboardInterrupt:
threading.Thread(target=output_status, args=(True,)).start()
为什么不在主线程中调用
output\u status
,而不是为它启动一个线程
threading.Thread(target=output_status, args=(True,)).start()
如果这样做,睡眠将发生在主线程上
output_status(True)
@新增9769953it@9769953你还需要什么吗?这个方法不是问题,而是扫描方法。我在一个for循环中创建了很多这个方法的线程,但在某些情况下它太多了。有多少线程是多线程?通常,线程受到内核的限制,如果您创建100个线程,并且有4个内核,那么一次只能运行4个线程(在最佳情况下)。在Python中,线程被限制为1,基本上是因为GIL,如果您必须创建“多个”线程,那么您应该再次阅读线程是什么以及它们的用途,因为即使Python没有GIL,您仍然很可能没有服务器来原谅大量创建线程。我打算建议您应该使用工作线程池和作业队列,例如
多处理.pool
。但这并不能解决主线程没有睡眠这一问题中的主要问题。相反,它的子线程是。即使使用池
,it作业队列也不受限制。这会将多余的线程转换为工作队列中的多余作业。因此,无论如何,您都必须使用信号量限制作业或线程的数量。