ping_sweep.py•2.81 kB
"""
Ping Sweep Tool
Network host discovery using ping
"""
from typing import Dict, Any, List
from .base_tool import BaseTool
import subprocess
class PingSweepTool(BaseTool):
"""Network host discovery tool"""
def __init__(self):
super().__init__()
self.name = "ping_sweep"
self.description = "Network host discovery using ping sweep. Identifies live hosts on a network by sending ICMP echo requests."
def get_tool_definition(self) -> Dict[str, Any]:
"""Return MCP-compatible tool definition"""
return {
"name": self.name,
"description": self.description,
"inputSchema": {
"type": "object",
"properties": {
"network": {
"type": "string",
"description": "Target network in CIDR notation (e.g., 192.168.1.0/24)"
}
},
"required": ["network"]
}
}
async def execute(self, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Execute ping sweep"""
try:
network = arguments.get("network", "")
if not network:
return self.format_error("Network in CIDR notation is required")
# Build nmap ping sweep command
cmd = f"nmap -sn {network}"
try:
result = subprocess.run(
["wsl", "bash", "-c", cmd],
capture_output=True,
text=True,
timeout=300 # 5 minutes
)
except FileNotFoundError:
result = subprocess.run(
["bash", "-c", cmd],
capture_output=True,
text=True,
timeout=300
)
if result.returncode == 0:
output = result.stdout if result.stdout else "Scan completed"
# Count live hosts
live_hosts = output.count("Host is up")
formatted = f"✅ Ping Sweep Results for {network}\n{'='*60}\n"
formatted += f"Live Hosts Found: {live_hosts}\n\n{output}\n{'='*60}"
return self.format_success(formatted)
else:
error = result.stderr or "Scan failed"
return self.format_error(f"Ping sweep failed: {error}")
except subprocess.TimeoutExpired:
return self.format_error("Scan timeout (exceeded 5 minutes)")
except Exception as e:
return self.format_error(f"Execution failed: {str(e)}")
tool_instance = PingSweepTool()