Python:
import socket
import argparse
from datetime import datetime
# Function to perform the port scan
def port_scanner(target, start_port, end_port):
print(f"[*] Starting scan on target: {target}")
# Start time of the scan
start_time = datetime.now()
# Try to resolve the target hostname to an IP address
try:
target_ip = socket.gethostbyname(target)
except socket.gaierror:
print(f"[-] Could not resolve hostname: {target}")
return
print(f"[*] IP Address of Target: {target_ip}")
print(f"[*] Scanning ports from {start_port} to {end_port}...")
# Scanning ports within the specified range
for port in range(start_port, end_port + 1):
# Create a new socket for each connection attempt
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1) # 1 second timeout for connections
result = sock.connect_ex((target_ip, port)) # Try to connect
if result == 0:
print(f"[+] Port {port} is open")
sock.close()
# Calculate total scan time
end_time = datetime.now()
total_time = end_time - start_time
print(f"[*] Scan completed in {total_time}")
# Main function to handle command-line arguments
if __name__ == "__main__":
# Create the parser for command-line arguments
parser = argparse.ArgumentParser(description="Simple Python Port Scanner")
parser.add_argument("target", help="Target IP or hostname to scan")
parser.add_argument("--start_port", type=int, default=1, help="Start port for scanning (default: 1)")
parser.add_argument("--end_port", type=int, default=65535, help="End port for scanning (default: 65535)")
# Parse the arguments from the command line
args = parser.parse_args()
# Call the port scanner function with the parsed arguments
port_scanner(args.target, args.start_port, args.end_port)
Running the Script:
Save the script as port_scanner.py and run it from the command line:
Код:
python3 port_scanner.py <target> --start_port <start_port> --end_port <end_port>
For example, to scan a host 192.168.1.1 for open ports between 1 and 1000, use:
Код:
python3 port_scanner.py 192.168.1.1 --start_port 1 --end_port 1000
Key Points:
Target: The IP or hostname of the machine you are scanning.
Ports: You can define a port range, e.g., from port 1 to 65535 (default if no range is specified).
Dependencies:
This script uses only the built-in Python libraries (socket, argparse, and datetime), so there are no external dependencies.