龙空技术网

Python使用asyncio库实现的简单的端口扫描器

wlvgfe1314 87

前言:

现时兄弟们对“python udp端口扫描”都比较着重,同学们都需要学习一些“python udp端口扫描”的相关知识。那么小编同时在网上收集了一些关于“python udp端口扫描””的相关内容,希望同学们能喜欢,看官们快快来学习一下吧!

Python的asyncio库是Python进行异步IO开发的内置库,这个库也是Python最难理解的库之一了。因为Python的异步IO理解起来本来就比较困难,其中涉及到了生成器、yield from、协程、异步IO系统函数等相应的一系列概念。

Python的asyncio本身实现了对TCP、UDP、SSL、子进程等内容的实现,下面就是使用asyncio库提供的功能,实现的简单的端口扫描工具,可以对asyncio的理解有所帮助

# -*- encoding:utf8 -*-import asynciofrom collections import namedtupleEndpoint = namedtuple("Endpoint", "host port")async def telnet(ip, port):    """检查端口是否打开"""    endpoint = Endpoint(ip, port)    try:        await asyncio.open_connection(            ip, port)    except Exception:        return endpoint, False    return endpoint, Trueasync def scan_ip(ip):    """创建扫描任务"""    tasks = []    for port in range(65536):        tasks.append(asyncio.ensure_future(            telnet(ip, port)))    for task in asyncio.as_completed(tasks):        endpoint, flag = await task        if not flag:            continue        print(f"{endpoint.host} -> "              f"{endpoint.port} is open")if __name__ == '__main__':    loop = asyncio.get_event_loop()    host = "127.0.0.1"    fut = scan_ip(host)    loop.run_until_complete(fut)

标签: #python udp端口扫描 #udp端口扫描工具