具有 CIDR/IP 范围或单个 IP/Domain 输入的 Scapy 端口扫描器

Scapy Port Scanner with CIDR/IP Range or Single IP/Domain input

我有以下代码来扫描给定端口范围内的单个主机。我想修改它,以便输入也接受 CIDR 斜杠符号(例如 google.com/34 或 8.8.8.8/34)(即除了单个域名或 IP地址)。

我该怎么做?

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import sys
from scapy.all import *

# Define end host and TCP port range
hostInput    = input("Enter a remote host to scan: ")
host  = socket.gethostbyname(hostInput)
port_range = [21,22,23,25,53,80,110,135,137,138,139,443,1433,1434,8080]

# Send SYN with random Src Port for each Dst port
for dst_port in port_range:
    src_port = random.randint(1025,65534)
    resp = sr1(
        IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=1,
        verbose=0,
    )

    if resp is None:
        print(f"{host}:{dst_port} is filtered (silently dropped).")

    elif(resp.haslayer(TCP)):
        if(resp.getlayer(TCP).flags == 0x12):
            # Send a gratuitous RST to close the connection
            send_rst = sr(
                IP(dst=host)/TCP(sport=src_port,dport=dst_port,flags='R'),
                timeout=1,
                verbose=0,
            )
            print(f"{host}:{dst_port} is open.")

        elif (resp.getlayer(TCP).flags == 0x14):
            print(f"{host}:{dst_port} is closed.")

    elif(resp.haslayer(ICMP)):
        if(
            int(resp.getlayer(ICMP).type) == 3 and
            int(resp.getlayer(ICMP).code) in [1,2,3,9,10,13]
        ):
            print(f"{host}:{dst_port} is filtered (silently dropped).")

您可以尝试使用

host = Net(hostInput)

Net 是 class Scapy 用来处理 IPv4 地址格式的工具。如果将它传递给一个数据包,sr( 将向每个主机发送一个数据包。

但是我不确定这将如何实现即插即用:sr1 的使用将输出限制为单个数据包,因此您可能必须将其更改为 sr(它给你一个所有答案的列表)