使用nmap扫描SSH端口时遇builtins.KeyError问题求助
Let's dig into why you're hitting that builtins.KeyError: [generated IP] when accessing the nmap scan results—especially since manual IP entry works, and even pasting the generated IP in debug mode runs fine. This almost always boils down to a mismatch between the IP string your ipPick() function generates and the exact IP key stored in the nmap results object.
Most Likely Causes & Fixes
1. Hidden Whitespace in the Generated IP
Your ipPick() function might be returning an IP string with invisible characters (like newlines \n, spaces, or tabs) that you can't spot at a glance. Nmap's scan() method is lenient enough to ignore these, but dictionary indexing requires an exact match—even a single hidden space will break it.
Debug & Fix Steps:
- Right after generating the IP, print its raw representation to reveal hidden characters:
ip = ipPick() print(f"Generated IP (raw): {repr(ip)}") # Will show things like '\n192.168.1.100' or '192.168.1.100 ' - If you see extra characters, clean the IP string with
strip()to remove leading/trailing whitespace:ip = ipPick().strip()
2. Subtle Format Mismatch
It's possible the IP from ipPick() has a minor format difference (like a trailing dot, or being a byte string instead of a regular string) that doesn't match what nmap stores in the nm object.
Debug Steps:
- After scanning, check exactly what IPs nmap recognized:
nm.scan(ip, '22') print("Hosts found in scan:", list(nm.all_hosts())) - Compare this list to your generated IP. If they don't match exactly, adjust your
ipPick()function to output the correct format, or clean the IP string as needed.
3. Missing Port Data (Less Likely)
While nm.scan(ip, '22') doesn't throw an error, it's possible the host didn't respond, or port 22 is filtered/closed, so nmap didn't add the tcp[22] entry to the results. Since manual entry works with the same IP, this is a long shot—but worth checking to avoid future errors.
Safe Access Code:
Add checks before accessing the dictionary to prevent KeyErrors entirely:
nm.scan(ip, '22') if ip in nm: host_data = nm[ip] if 'tcp' in host_data and 22 in host_data['tcp']: port22_state = host_data['tcp'][22]['state'] print(f"Port 22 state: {port22_state}") else: print(f"Port 22 data not found for {ip}") else: print(f"Host {ip} not detected in scan")
Quick Confirmation Test
Try hardcoding the exact IP that ipPick() generates (copy it from your debug print) and run the script. If it works without error, the problem is definitely in how ipPick() returns the IP string—not in your scanning logic.
内容的提问来源于stack exchange,提问作者cr0n_dist0rti0n

