Python - 不能用键盘中断杀死主线程



我正在制作一个简单的多线程端口扫描程序。它扫描主机上的所有端口并返回打开的端口。故障在于中断扫描。扫描要花很多时间才能完成,有时我想在扫描过程中用C-C杀死程序。问题是扫描无法停止。主线程被锁定在queue.join()上,并忽略KeyboardInterrupt,直到队列中的所有数据都得到处理,从而解除主线程的锁定并正常退出程序。我所有的线程都被守护了,所以当主线程死的时候,它们应该和他一起死。

我试着使用信号库,但没有成功。重写线程。线程类和用于优雅终止的添加方法不起作用。。。主线程在执行queue.join()时不会收到KeyboardInterrupt

import threading, sys, Queue, socket
queue = Queue.Queue()
def scan(host):
    while True:
        port = queue.get()
        if port > 999 and port % 1000 == 0:
            print port
        try:
            #sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #sock.settimeout(2) #you need timeout or else it will try to connect forever! 
            #sock.connect((host, port))
            #----OR----
            sock = socket.create_connection((host, port), timeout = 2)
            sock.send('aaa')
            data = sock.recv(100)
            print "Port {} open, message: {}".format(port, data)
            sock.shutdown()
            sock.close()
            queue.task_done()
        except:
            queue.task_done()

def main(host):
    #populate queue
    for i in range(1, 65536):
        queue.put(i)
    #spawn worker threads
    for port in range(100):
        t = threading.Thread(target = scan, args = (host,))
        t.daemon = True
        t.start()
if __name__ == '__main__':
    host = ""
    #does input exist?
    try:
        host = sys.argv[1]
    except:
        print "No argument was recivied!"
        exit(1)
    #is input sane?
    try:
        host = socket.gethostbyname(host)
    except:
        print "Adress does not exist"
        exit(2)
    #execute main program and wait for scan to complete
    main(host)
    print "Post main() call!"
    try:
        queue.join()
    except KeyboardInterrupt:
        print "C-C"
        exit(3)

编辑:

我通过使用时间模块找到了一个解决方案。

#execute main program and wait for scan to complete
main(host)
#a little trick. queue.join() makes main thread immune to keyboardinterrupt. So use queue.empty() with time.sleep()
#queue.empty() is "unreliable" so it may return True a bit earlier then intented.
#when queue is true, queue.join() is executed, to confirm that all data was processed.
#not a true solution, you can't interrupt main thread near the end of scan (when queue.empty() returns True)
try:
    while True:
        if queue.empty() == False:
            time.sleep(1)
        else:
            break
except KeyboardInterrupt:
    print "Alas poor port scanner..."
    exit(1)
queue.join()

您已经使线程成为守护进程,但您需要在守护进程线程存在的情况下保持主线程的活动状态,方法如下:无法使用Ctrl-C 杀死Python脚本

创建线程时,将它们添加到正在运行的线程列表中,处理ctrl-C时,向列表中的每个线程发送终止信号。这样,你就可以主动清理,而不是依赖于别人为你清理。

相关内容

  • 没有找到相关文章

最新更新