""" Example usage script for the network scanner API. This script demonstrates how to use the network scanner programmatically. """ import asyncio import time from typing import Optional import httpx class NetworkScannerClient: """Client for interacting with the network scanner API.""" def __init__(self, base_url: str = "http://localhost:8000"): """Initialize client with API base URL.""" self.base_url = base_url self.api_url = f"{base_url}/api" async def start_scan( self, network_range: str, scan_type: str = "quick", use_nmap: bool = False ) -> int: """ Start a new network scan. Args: network_range: Network in CIDR notation (e.g., '192.168.1.0/24') scan_type: Type of scan ('quick', 'standard', 'deep') use_nmap: Whether to use nmap Returns: Scan ID """ async with httpx.AsyncClient() as client: response = await client.post( f"{self.api_url}/scans/start", json={ "network_range": network_range, "scan_type": scan_type, "include_service_detection": True, "use_nmap": use_nmap } ) response.raise_for_status() data = response.json() return data['scan_id'] async def get_scan_status(self, scan_id: int) -> dict: """Get status of a scan.""" async with httpx.AsyncClient() as client: response = await client.get(f"{self.api_url}/scans/{scan_id}/status") response.raise_for_status() return response.json() async def wait_for_scan(self, scan_id: int, timeout: int = 600) -> dict: """ Wait for a scan to complete. Args: scan_id: Scan ID timeout: Maximum time to wait in seconds Returns: Final scan status """ start_time = time.time() while time.time() - start_time < timeout: status = await self.get_scan_status(scan_id) print(f"Scan {scan_id} status: {status['status']} - " f"Found {status['hosts_found']} hosts") if status['status'] in ['completed', 'failed', 'cancelled']: return status await asyncio.sleep(5) raise TimeoutError(f"Scan {scan_id} did not complete within {timeout} seconds") async def get_hosts(self, status: Optional[str] = None) -> list: """Get list of discovered hosts.""" async with httpx.AsyncClient() as client: params = {} if status: params['status'] = status response = await client.get(f"{self.api_url}/hosts", params=params) response.raise_for_status() return response.json() async def get_topology(self, include_offline: bool = False) -> dict: """Get network topology.""" async with httpx.AsyncClient() as client: response = await client.get( f"{self.api_url}/topology", params={"include_offline": include_offline} ) response.raise_for_status() return response.json() async def get_statistics(self) -> dict: """Get network statistics.""" async with httpx.AsyncClient() as client: response = await client.get(f"{self.api_url}/hosts/statistics") response.raise_for_status() return response.json() async def main(): """Main example function.""" # Initialize client client = NetworkScannerClient() # Example 1: Start a quick scan print("=" * 60) print("Example 1: Starting a quick scan of local network") print("=" * 60) network_range = "192.168.1.0/24" # Change to your network scan_id = await client.start_scan(network_range, scan_type="quick") print(f"Started scan {scan_id} for {network_range}") # Wait for scan to complete print("\nWaiting for scan to complete...") final_status = await client.wait_for_scan(scan_id) print(f"\nScan completed!") print(f"Status: {final_status['status']}") print(f"Hosts found: {final_status['hosts_found']}") print(f"Ports scanned: {final_status['ports_scanned']}") # Example 2: Get discovered hosts print("\n" + "=" * 60) print("Example 2: Getting discovered hosts") print("=" * 60) hosts = await client.get_hosts(status="online") print(f"\nFound {len(hosts)} online hosts:") for host in hosts[:10]: # Show first 10 services = host.get('services', []) print(f"\n IP: {host['ip_address']}") print(f" Hostname: {host.get('hostname', 'N/A')}") print(f" Status: {host['status']}") print(f" Services: {len(services)}") if services: print(" Open Ports:") for svc in services[:5]: # Show first 5 services print(f" - {svc['port']}/{svc['protocol']} " f"({svc.get('service_name', 'unknown')})") # Example 3: Get network topology print("\n" + "=" * 60) print("Example 3: Getting network topology") print("=" * 60) topology = await client.get_topology() print(f"\nTopology:") print(f" Nodes: {len(topology['nodes'])}") print(f" Edges: {len(topology['edges'])}") # Show node types node_types = {} for node in topology['nodes']: node_type = node['type'] node_types[node_type] = node_types.get(node_type, 0) + 1 print(f"\n Node types:") for node_type, count in node_types.items(): print(f" - {node_type}: {count}") # Example 4: Get statistics print("\n" + "=" * 60) print("Example 4: Getting network statistics") print("=" * 60) stats = await client.get_statistics() print(f"\nNetwork Statistics:") print(f" Total hosts: {stats['total_hosts']}") print(f" Online hosts: {stats['online_hosts']}") print(f" Offline hosts: {stats['offline_hosts']}") print(f" Total services: {stats['total_services']}") print(f" Total scans: {stats['total_scans']}") if stats.get('most_common_services'): print(f"\n Most common services:") for svc in stats['most_common_services'][:5]: print(f" - {svc['service_name']}: {svc['count']}") print("\n" + "=" * 60) print("Examples completed!") print("=" * 60) if __name__ == "__main__": asyncio.run(main())