如何杀死无响应的线程

时间:2013-11-25 17:20:13

标签: python multithreading

我一直试图找到一种方法来杀死在该程序结束时没有响应的线程:

大多数时候代码都有效,但在某些域上,某些线程会挂起,不允许程序完成。

非常感谢任何帮助。

    #!/usr/bin/python

from socket import gethostbyaddr
import dns.resolver
import sys
import Queue
import threading
import subprocess
import time

exitFlag = 0
lines = ''

class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        process_data(self.name, self.q)

class Timer():
   def __enter__(self): self.start = time.time()
   def __exit__(self, *args):
        taken = time.time() - self.start
        print " [*] Time elapsed " + str(round(taken,1)) + " seconds at " + str(round(len(subdomains) / taken)) + " lookups per second."

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            host = data.strip() + '.' + domain.strip()
            try:
                answers = resolver.query(host)
                try:
                    output = gethostbyaddr(host)
                    if len(host) < 16:
                        print str(host) + "\t\t" +  str(output[0]) + " " + str(output[2])
                        found.append(str(host) + "\t\t" +  str(output[0]) + " " + str(output[2]))
                    else:
                        print str(host) + "\t" +  str(output[0]) + " " + str(output[2])
                        found.append(str(host) + "\t" +  str(output[0]) + " " + str(output[2]))
                except:
                    print str(host)
                    found.append(str(host))
            except:
                pass
        else:
            queueLock.release()

if len(sys.argv) < 3:
    print
    print 'Usage: dnsbrute.py <target.com> <subdomains.txt> (threads)'
    exit()

if len(sys.argv) >= 4:
    maxthreads = int(sys.argv[3])
else:
    maxthreads = int(40)

domain = sys.argv[1]
maked = "mkdir -p logs"
process = subprocess.Popen(maked.split(), stdout=subprocess.PIPE)
poutput = process.communicate()[0]
found = []
subdomains = [line.strip() for line in open(sys.argv[2], 'r')]
dnsservers = ["8.8.8.8", "8.8.4.4", "4.2.2.1", "4.2.2.2", "4.2.2.3", "4.2.2.4", "4.2.2.5", "4.2.2.6", "209.244.0.3", "209.244.0.4" ]
threadList = []
numthreads = 1
resolver = dns.resolver.Resolver()
resolver.nameservers = dnsservers
logfile = open("logs/" + domain + ".log", 'w') 

while numthreads <= maxthreads:
    threadList.append(str("Thread-") + str(numthreads))
    numthreads += 1

print " [*] Starting " + str(maxthreads) + " threads to process " + str(len(subdomains)) + " subdomains."
print

queueLock = threading.Lock()
workQueue = Queue.Queue(len(subdomains))
threads = []
threadID = 1

with Timer():
    for tName in threadList:
        thread = myThread(threadID, tName, workQueue)
        thread.start()
        threads.append(thread)
        threadID += 1

    queueLock.acquire()
    for work in subdomains:
        workQueue.put(work)
    queueLock.release()

    while not workQueue.empty():
        pass

    exitFlag = 1

    for t in threads:
        t.join()

    for item in found:
      logfile.write("%s\n" % item)

    print
    print " [*] All threads complete, " + str(len(found)) + " subdomains found."
    print " [*] Results saved to logs/" + domain + ".log"

1 个答案:

答案 0 :(得分:0)

请记住,以任何语言杀死线程都是一种糟糕的方法,因为资源可能会处于不一致的状态。如果可以,尝试重新设计程序,以便线程通过检查布尔值来关闭自己。无论如何,这是一个非常好的答案来自SO:

Is there any way to kill a Thread in Python?