Python端口扫描CLI参数解析问题:如何正确指定端口范围?
Hey there! I see you're diving into Python by building a port scanner—great way to learn through practice! Let's break down why your CLI port range isn't working and fix it step by step.
First, let's spot the key issues in your current code snippet:
1. Mismatched Variable Names
You defined first_port but tried to print start_port—that would throw a NameError right off the bat. Small typo, but easy to miss!
2. String vs. Integer Type Mismatch
The biggest problem: sys.argv returns strings for all command-line arguments, but range() requires integers. If you pass something like python scanner.py 127.0.0.1 1 100, first_port and ending_port are the strings "1" and "100"—feeding those into range() will cause a TypeError, which might be why you're seeing no output (if error messages are suppressed, or your code crashes silently).
3. Missing Parameter Validation
You aren't checking if the user provided all required arguments (host, start port, end port), or if the port values are valid numbers. This leads to unexpected behavior instead of helpful error messages.
Fixed Code Example
Here's a revised version that addresses all these issues, plus a basic port scanning logic:
import sys import socket def scan_ports(host, start_port, end_port): print(f"Checking ports on {host} from {start_port} to {end_port}...") for port in range(start_port, end_port + 1): # +1 because range is exclusive of the end value try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(0.5) # Short timeout to speed up scanning result = sock.connect_ex((host, port)) if result == 0: print(f"Port {port} is open") sock.close() except Exception as e: print(f"Error scanning port {port}: {e}") if __name__ == "__main__": # Check if user provided enough arguments if len(sys.argv) != 4: print("Usage: python port_scanner.py <host> <start_port> <end_port>") print("Example: python port_scanner.py 127.0.0.1 1 100") sys.exit(1) # Parse and validate arguments host = sys.argv[1] try: start_port = int(sys.argv[2]) end_port = int(sys.argv[3]) except ValueError: print("Error: Port numbers must be integers!") sys.exit(1) # Validate port range is reasonable if start_port < 1 or end_port > 65535 or start_port > end_port: print("Error: Invalid port range. Ports must be between 1-65535, and start port <= end port.") sys.exit(1) # Run the scanner scan_ports(host, start_port, end_port)
Key Fixes Explained:
- Type Conversion: We use
int()to convert the port arguments from strings to integers, sorange()works as expected. - Parameter Checks: We verify the user provided exactly 3 arguments, that ports are valid integers, and that the range makes sense (ports can't be outside 1-65535, and start can't be higher than end).
- Range Adjustment:
range(start, end)stops atend-1, so we userange(start_port, end_port + 1)to include the ending port in the scan. - Basic Scanning Logic: Added a simple TCP port check using
socket.connect_ex()which returns 0 if the port is open.
Give this a try—when you run it like python port_scanner.py 127.0.0.1 1 100, you should see output showing which ports are open (if any) on your local machine.
内容的提问来源于stack exchange,提问作者user3311890

