python多线程扫描端口

常用的端口扫描工具:netcat

nc -z -v -n IP 10-65535

如果简单的一台机器,几个端口没问题,很多台机器就麻烦了。

下面是一个多线程扫描的python小程序:使用telnet,默认扫TCP端口

#!/usr/bin/env python

import telnetlib
import threading
import queue
import logging

loggers = {}

server = telnetlib.Telnet()


def get_ip_status(a_ip, a_port):
    try:
        server.open(a_ip, a_port)
        loggers[a_ip + '_open'].warning('{0} port {1} is open'.format(a_ip, a_port))
    except Exception as err:
        # print('{0} port {1} is not open'.format(a_ip, a_port))
        loggers[a_ip + '_close'].error('{0} port {1} is not open'.format(a_ip, a_port))
    finally:
        server.close()


def check_open(a_q):
    try:
        while True:
            the_ip, the_port = a_q.get_nowait()
            get_ip_status(the_ip, the_port)
    except queue.Empty as e:
        print(e)


def init_logger(host_arr):
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    for h in host_arr:
        loggers[h + '_open'] = get_logger(h + '_open.log')
        loggers[h + '_close'] = get_logger(h + '_close.log')


def get_logger(name):
    handler = logging.FileHandler(filename=name)
    logger = logging.getLogger('port_scan_' + name)
    logger.addHandler(handler)
    return logger


if __name__ == '__main__':
    host = ['10.10.10.1', '10.10.10.2', '10.10.10.3', '10.10.10.4']
    init_logger(host)
    q = queue.Queue()
	[q.put((ip, port)) for ip in host for port in range(1, 65535)]
    
    threads = []
    n_thread = 100
    for i in range(n_thread):
        t = threading.Thread(target=check_open, args=(q,))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

线程数开100个,还是很快的,视端口数量而定,本机测试5个IP*6万多个端口,大概需要1个小时才能跑完。

你可能感兴趣的:(网络)