Python:多线程端口扫描

#!/usr/bin/python3
# -*- coding: utf-8 -*-
from socket import *
import threading
from time import sleep, ctime

lock = threading.Lock()
openNum = 0
ports = []
threads = []

def portScanner(host,port):
    global openNum
    global ports
    try:
        s = socket(AF_INET,SOCK_STREAM)
        res = s.connect((host,port))
        lock.acquire()
        openNum+=1
        print('[+] %d open' % port)
        ports.append(port)
        lock.release()
        s.close()
    except:
        pass

def main():
    setdefaulttimeout(1)
    print('starting at:', ctime())
    for p in range(1,65536):
        t = threading.Thread(target=portScanner,args=('10.20.0.205',p))
        threads.append(t)
        t.start()     

    for t in threads:
        t.join()

    print('[*] The scan is complete!')
    print('[*] A total of %d open port ' % (openNum))
    print('all DONE at:', ctime())
    print(ports)

if __name__ == '__main__':
    main()

测试结果,65535个端口耗时17秒

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注