Python просто позволяет основному потоку спать - PullRequest
0 голосов
/ 12 ноября 2018

Я использую 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 голосов
/ 12 ноября 2018

Почему вы не вызываете output_status в основном потоке, а не запускаете для него поток?

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

Если вы это сделаете, то сон будет происходить в главном потоке.

output_status(True)
...