|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Network scanner script for DialogChain. |
| 4 | +Provides basic network scanning capabilities without requiring root privileges. |
| 5 | +""" |
| 6 | + |
| 7 | +import asyncio |
| 8 | +import socket |
| 9 | +import argparse |
| 10 | +from typing import List, Optional |
| 11 | +from dataclasses import dataclass |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class NetworkService: |
| 15 | + """Represents a discovered network service.""" |
| 16 | + ip: str |
| 17 | + port: int |
| 18 | + service: str = "unknown" |
| 19 | + protocol: str = "tcp" |
| 20 | + banner: str = "" |
| 21 | + is_secure: bool = False |
| 22 | + is_up: bool = True |
| 23 | + |
| 24 | +class SimpleNetworkScanner: |
| 25 | + """Simple network scanner that doesn't require root privileges.""" |
| 26 | + |
| 27 | + COMMON_PORTS = { |
| 28 | + 'rtsp': [554, 8554], |
| 29 | + 'http': [80, 8080, 8000, 8888], |
| 30 | + 'https': [443, 8443], |
| 31 | + 'ssh': [22], |
| 32 | + 'vnc': [5900, 5901], |
| 33 | + 'rdp': [3389], |
| 34 | + 'mqtt': [1883], |
| 35 | + 'mqtts': [8883] |
| 36 | + } |
| 37 | + |
| 38 | + def __init__(self, timeout: float = 2.0): |
| 39 | + """Initialize the scanner with connection timeout.""" |
| 40 | + self.timeout = timeout |
| 41 | + |
| 42 | + async def check_port(self, ip: str, port: int) -> bool: |
| 43 | + """Check if a port is open.""" |
| 44 | + try: |
| 45 | + reader, writer = await asyncio.wait_for( |
| 46 | + asyncio.open_connection(ip, port), |
| 47 | + timeout=self.timeout |
| 48 | + ) |
| 49 | + writer.close() |
| 50 | + await writer.wait_closed() |
| 51 | + return True |
| 52 | + except (asyncio.TimeoutError, ConnectionRefusedError, OSError): |
| 53 | + return False |
| 54 | + |
| 55 | + def identify_service(self, port: int) -> str: |
| 56 | + """Identify service based on port number.""" |
| 57 | + for service, ports in self.COMMON_PORTS.items(): |
| 58 | + if port in ports: |
| 59 | + return service |
| 60 | + return "unknown" |
| 61 | + |
| 62 | + async def scan_network( |
| 63 | + self, |
| 64 | + network: str = '192.168.1.0/24', |
| 65 | + ports: Optional[List[int]] = None, |
| 66 | + service_types: Optional[List[str]] = None |
| 67 | + ) -> List[NetworkService]: |
| 68 | + """Scan a network for open ports and services.""" |
| 69 | + if ports is None and service_types is None: |
| 70 | + ports = list(set(p for ports in self.COMMON_PORTS.values() for p in ports)) |
| 71 | + elif service_types: |
| 72 | + ports = [] |
| 73 | + for svc in service_types: |
| 74 | + if svc in self.COMMON_PORTS: |
| 75 | + ports.extend(self.COMMON_PORTS[svc]) |
| 76 | + ports = list(set(ports)) |
| 77 | + |
| 78 | + # Get IPs to scan |
| 79 | + base_ip = ".".join(network.split(".")[:3]) |
| 80 | + ips = [f"{base_ip}.{i}" for i in range(1, 255)] |
| 81 | + |
| 82 | + # Scan ports for each IP |
| 83 | + tasks = [] |
| 84 | + for ip in ips: |
| 85 | + for port in ports: |
| 86 | + tasks.append(self.scan_port(ip, port)) |
| 87 | + |
| 88 | + # Run all scans concurrently |
| 89 | + results = await asyncio.gather(*tasks) |
| 90 | + return [service for service in results if service.is_up] |
| 91 | + |
| 92 | + async def scan_port(self, ip: str, port: int) -> NetworkService: |
| 93 | + """Scan a single port and return service info.""" |
| 94 | + is_open = await self.check_port(ip, port) |
| 95 | + service = self.identify_service(port) |
| 96 | + return NetworkService( |
| 97 | + ip=ip, |
| 98 | + port=port, |
| 99 | + service=service, |
| 100 | + is_up=is_open |
| 101 | + ) |
| 102 | + |
| 103 | +async def main(): |
| 104 | + """Main function for command-line usage.""" |
| 105 | + parser = argparse.ArgumentParser(description='Network scanner for DialogChain') |
| 106 | + parser.add_argument('--network', '-n', default='192.168.1.0/24', |
| 107 | + help='Network to scan in CIDR notation') |
| 108 | + parser.add_argument('--service', '-s', action='append', |
| 109 | + help='Service types to scan (rtsp, http, etc.)') |
| 110 | + parser.add_argument('--port', '-p', type=int, action='append', |
| 111 | + help='Specific ports to scan') |
| 112 | + parser.add_argument('--timeout', '-t', type=float, default=1.0, |
| 113 | + help='Connection timeout in seconds') |
| 114 | + |
| 115 | + args = parser.parse_args() |
| 116 | + |
| 117 | + scanner = SimpleNetworkScanner(timeout=args.timeout) |
| 118 | + services = await scanner.scan_network( |
| 119 | + network=args.network, |
| 120 | + ports=args.port, |
| 121 | + service_types=args.service |
| 122 | + ) |
| 123 | + |
| 124 | + # Print results |
| 125 | + print("\nScan Results:") |
| 126 | + print("-" * 60) |
| 127 | + print(f"{'IP':<15} {'Port':<6} {'Service':<10} {'Status'}") |
| 128 | + print("-" * 60) |
| 129 | + |
| 130 | + for svc in sorted(services, key=lambda x: (x.ip, x.port)): |
| 131 | + status = "UP" if svc.is_up else "DOWN" |
| 132 | + print(f"{svc.ip:<15} {svc.port:<6} {svc.service:<10} {status}") |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + asyncio.run(main()) |
0 commit comments