Python只是让主线程进入睡眠状态

时间:2018-11-12 08:50:43

标签: python python-3.x multithreading python-multithreading

我在主线程中使用time.sleep(),并且只希望该线程进入睡眠状态。问题是,我在主目录中创建的所有其他线程也正在睡眠。一个问题可能是他们必须访问全局变量。 目的只是一次不创建太多线程-因此我计算正在运行的线程,如果它们大于200,我想让主线程休眠以给其他线程更多的时间。

    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()

1 个答案:

答案 0 :(得分:0)

为什么不在主线程中调用output_status而不是为其启动线程?

threading.Thread(target=output_status, args=(True,)).start()

如果这样做,睡眠将在主线程上发生。

output_status(True)