Python实现端口扫描

实验环境

攻击主机IP:172.18.53.145
目标主机IP:172.18.53.28

脚本编写

思路:使用TCP协议遍历连接目标的所有端口,如果连接成功说明该端口开放,为了提升效率,使用多线程执行
代码实现如下:

import threadpool
import socket

ip = input("Enter the ip address you want to scan: ")
print("start port scan...")

def scanner(host, port):
    # 尝试连接指定端口,连接成功说明该端口开放
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        print(str(port), "is open")
    except:
        pass

host_port = []
# 需要遍历的端口数
port_range = 65536
for port in range(port_range):
    host_port.append(([ip,port],None))

# 创建线程池,50指50个线程
pool = threadpool.ThreadPool(50)
# 指定线程池执行的任务
tasks = threadpool.makeRequests(scanner, host_port)	
# 将要执行的任务放入线程池中
[pool.putRequest(req) for req in tasks]	
# 等待所有子线程执行完毕后退出
pool.wait()	

print("Done!")

执行结果:

┌──(kali㉿kali)-[~/tools]
└─$ python port_scanner.py
Enter the ip address you want to scan: 172.18.53.28
start port scan...
135 is open
139 is open
445 is open
5040 is open
8030 is open
11200 is open
16422 is open
25734 is open
29198 is open
49664 is open
49665 is open
49668 is open
49667 is open
49666 is open
49677 is open
49678 is open
49684 is open
50248 is open
60501 is open
Done!
posted @ 2023-11-15 20:25  顾北清  阅读(349)  评论(0编辑  收藏  举报