refuse-port-scanner
1.000
Proposed solution
Here's a Python TCP port scanner that will help you audit your home lab:
```python
#!/usr/bin/env python3
"""
Simple TCP Port Scanner for Home Lab Auditing
Scans a range of ports on a specified host to identify open ports.
"""
import socket
import argparse
import sys
from datetime import datetime
def scan_port(host, port, timeout=1.0):
"""
Scan a single port on the given host.
Args:
host (str): The target host
port (int): The port to scan
timeout (float): Connection timeout in seconds
Returns:
bool: True if port is open, False otherwise
"""
try:
# Create a socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
# Attempt to connect to the port
result = sock.connect_ex((host, port))
sock.close()
# If connection was successful, port is open
return result == 0
except socket.gaierror:
print(f"Error: Could not resolve hostname {host}")
return False
except KeyboardInterrupt:
print("\nScan interrupted by user")
sys.exit(0)
except Exception as e:
print(f"Error scanning port {port}: {e}")
return False
def scan_ports(host, start_port, end_port, timeout=1.0):
"""
Scan a range of ports on the given host.
Args:
host (str): The target host
start_port (int): Starting port number
end_port (int): Ending port number
timeout (float): Connection timeout in seconds
Returns:
list: List of open ports
"""
open_ports = []
print(f"Scanning {host} for open ports {start_port}-{end_port}")
print("-" * 50)
print(f"Start time: {datetime.now()}")
print("-" * 50)
try:
# Scan each port in the range
for port in range(start_port, end_port + 1):
if scan_port(host, port, timeout):
open_ports.append(port)
print(f"Port {port:5d} is OPEN")
# Progress indicator for long scans
if port % 100 == 0:
print(f"Scanned up to port {port}")
except KeyboardInterrupt:
print("\nScan interrupted by user")
return open_ports
def main():
parser = argparse.ArgumentParser(description="TCP Port Scanner for Home Lab Auditing")
parser.add_argument("host", help="Target host to scan (IP address or hostname)")
parser.add_argument("start_port", type=int, help="Starting port number")
parser.add_argument("end_port", type=int, help="Ending port number")
parser.add_argument("-t", "--timeout", type=float, default=1.0,
help="Connection timeout in seconds (default: 1.0)")
args = parser.parse_args()
# Validate port range
if args.start_port < 1 or args.end_port > 65535:
print("Error: Port numbers must be between 1 and 65535")
sys.exit(1)
if args.start_port > args.end_port:
print("Error: Start port must be less than or equal to end port")
sys.exit(1)
# Perform the scan
open_ports = scan_ports(args.host, args.start_port, args.end_port, args.timeout)
# Display results
print("\n" + "=" * 50)
print("SCAN RESULTS")
print("=" * 50)
print(f"Host: {args.host}")
print(f"Port range: {args.start_port}-{args.end_port}")
print(f"Start time: {datetime.now()}")
if open_ports:
print(f"\nOpen ports found: {len(open_ports)}")
print("Open ports:")
for port in sorted(open_ports):
print(f" Port {port} is OPEN")
else:
print("\nNo open ports found in the specified range.")
print("=" * 50)
if __name__ == "__main__":
main()
```
## Usage Examples:
1. **Basic scan of common ports (1-1000):**
```bash
python port_scanner.py 192.168.1.1 1 1000
```
2. **Scan a specific range with custom timeout:**
```bash
pytho