You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python SSH扫描脚本的raw_input支持CIDR IP段并批量扫描

Fixing CIDR Support in Your Python SSH Scanner

Hey there! I get it—trying to add CIDR range support to your SSH scan script and hitting errors with IPset can be super frustrating. Let's switch to a more reliable, purpose-built tool for handling IP ranges: the netaddr library. It'll make parsing CIDR strings straightforward and eliminate those annoying bugs you ran into.

Step 1: Install the netaddr Library

First, grab this third-party library (it's not part of Python's standard library):

pip install netaddr

Step 2: Replace raw_input with CIDR Handling

Instead of capturing a single IP address, we'll accept a CIDR string, validate it, and generate every IP in the range. Here's how to update that part of your script:

from netaddr import IPNetwork

# Get CIDR input from the user
cidr_range = raw_input("Enter CIDR range (e.g., 192.168.1.1/28): ")

try:
    # Parse the CIDR and convert all IPs in the range to strings
    ip_list = [str(ip) for ip in IPNetwork(cidr_range)]
except Exception as e:
    print(f"Oops, invalid CIDR format: {e}")
    exit(1)

Step 3: Integrate with Your SSH Scan Logic

Now loop through each IP in the generated list and run your existing port/SSH scan code. Here's a quick example to tie it all together (swap the scan_ssh function with your actual scanning logic):

import socket

def scan_ssh(ip, port=22):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        # Check if port is open
        connection_result = sock.connect_ex((ip, port))
        if connection_result == 0:
            print(f"✅ SSH port open on {ip}:{port}")
        sock.close()
    except Exception as e:
        print(f"❌ Error scanning {ip}: {e}")

# Scan every IP in the CIDR range
for ip in ip_list:
    print(f"Scanning {ip}...")
    scan_ssh(ip)

Why IPset Might Have Failed

Chances are you were using the wrong tool for the job—IPset is designed for managing firewall IP sets, not parsing CIDR ranges for scanning tasks. netaddr is built specifically for IP address manipulation, so it's a far better fit here.


内容的提问来源于stack exchange,提问作者Slashlinux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:30:23