Scapy是一种用于Python编写的交互式数据包操作工具和库。该工具可以用输入IP范围或单个IP/域名的方式进行端口扫描。以下是使用Scapy进行端口扫描的代码示例:
from scapy.all import *
# 输入CIDR/IP范围作为输入
ip_range = input("Enter IP range (CIDR notation): ")
# 将目标IP范围转换为IP列表
ip_list = [str(ip) for ip in IP(ip_range).hosts()]
# 输入单个IP地址或域名作为输入
ip = input("Enter single IP address or domain name: ")
# 将输入的IP地址或域名转换为IP地址
dest_ip = socket.gethostbyname(ip)
# 循环遍历IP地址列表,进行端口扫描
for ip in ip_list:
# 创建IP包
ip_packet = IP(dst=ip)
# 创建TCP连接
tcp_connection = TCP(sport=RandShort(), dport=[80, 443, 8080], flags='S')
# 发送IP和TCP包
response = sr1(ip_packet/tcp_connection, timeout=1, verbose=0)
if response is not None:
# 如果收到回复,则表明端口开放
print(ip + ": " + str(response.sprintf('%TCP.sport% : TCP open')))
以上代码允许用户输入CIDR/IP范围或单个IP地址/域名,并对给定的IP地址进行端口扫描。代码使用IP()
函数将IP范围转换为IP地址列表,并使用socket.gethostbyname()
函数将单个IP地址或域名转换为IP地址。端口扫描使用TCP连接进行,扫描常用的端口,如80、443和8080,并使用sr1()
函数和超时参数在1秒内等待回复。如果收到回复,则表明端口开放。