python多线程方式扫描开放端口

使用python多线程方式扫描某台机器开放端口

import socket
import time
import threading
from queue import Queue

socket.setdefaulttimeout(0.25)
print_lock = threading.Lock()

target = '127.0.0.1'

def portscan(port):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        con = s.connect_ex((target,port))
        if con == 0:
            with print_lock:
             print('port', port, 'is open')
        con.close()
    except:
        pass

def threader():
    while True:
        worker = q.get()
        portscan(worker)
        q.task_done()

q = Queue()
startTime = time.time()

for x in range(1000):
    t = threading.Thread(target=threader)
    t.daemon = True
    t.start()

for worker in range(1,65536):
    q.put(worker)

q.join()

print('Time taken:', time.time()-startTime)

参考:

python-port-scanner-using-multithreading

Be First to Comment

发表评论

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