port_scanner.py源码
#!/usr/bin/env python3
import socket
import time
from concurrent.futures import ThreadPoolExecutor
class PortScanner:
def __init__(self, host, start_port=1, end_port=65535, threads=400, timeout=0.6):
self.host = host
self.start_port = start_port
self.end_port = end_port
self.threads = threads
self.timeout = timeout
self.open_ports = []
def scan_port(self, port):
"""Scan a single port"""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(self.timeout)
result = sock.connect_ex((self.host, port))
if result == 0:
return port
except socket.error:
pass
return None
def scan(self):
"""Perform the port scan"""
print(f"Scanning {self.host} for open ports...\n")
try:
self.remote_ip = socket.gethostbyname(self.host)
except socket.gaierror:
print(f"Hostname {self.host} could not be resolved.")
return
start_time = time.time()
with ThreadPoolExecutor(max_workers=self.threads) as executor:
futures = [executor.submit(self.scan_port, port) for port in range(self.start_port, self.end_port + 1)]
for future in futures:
port = future.result()
if port:
self.open_ports.append(port)
end_time = time.time()
self.duration = end_time - start_time
def print_results(self):
"""Print the scan results"""
if self.open_ports:
print("Open ports:")
for port in sorted(self.open_ports):
print(f"Port {port} is open")
else:
print("No open ports found.")
print(f"\nScan complete. Found {len(self.open_ports)} open port(s).")
print(f"Scan duration: {self.duration:.2f} seconds")
def main():
import argparse
parser = argparse.ArgumentParser(description='Remote Port Scanner')
parser.add_argument('--host', action="store", dest="host", default='localhost')
parser.add_argument('--start-port', action="store", dest="start_port", default=1, type=int)
parser.add_argument('--end-port', action="store", dest="end_port", default=100, type=int)
args = parser.parse_args()
scanner = PortScanner(args.host, args.start_port, args.end_port)
scanner.scan()
scanner.print_results()
if __name__ == '__main__':
main()
运行结果如下
Scanning localhost for open ports...
No open ports found.
Scan complete. Found 0 open port(s).
Scan duration: 0.01 seconds