nmap_port_scan
Scan specific ports on target hosts to identify open services and assess network security using the Nmap MCP Server.
Instructions
Scan specific ports on target hosts
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| targets | Yes | ||
| ports | Yes | ||
| scan_method | No | syn |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- server.py:248-266 (handler)The handler function for the nmap_port_scan tool. It constructs Nmap arguments based on the scan_method (syn, connect, or udp) and executes the scan using the shared run_nmap_command helper.
async def nmap_port_scan( targets: str, ports: str, scan_method: str = "syn" ) -> str: """Scan specific ports on target hosts.""" if scan_method == "syn": args = ["-sS", "-p", ports, targets] elif scan_method == "connect": args = ["-sT", "-p", ports, targets] else: # udp args = ["-sU", "-p", ports, targets] result = run_nmap_command(args) if result["success"]: return f"Port scan completed:\n\n{result['stdout']}" else: return f"Port scan failed:\n\n{result['stderr']}" - server.py:244-247 (registration)Registration of the nmap_port_scan tool using the FastMCP @app.tool decorator.
@app.tool( name="nmap_port_scan", description="Scan specific ports on target hosts" ) - server.py:38-92 (helper)Shared helper function used by all Nmap tools, including nmap_port_scan, to execute Nmap commands via subprocess and handle output, errors, and timeouts.
def run_nmap_command(args: List[str], timeout: int = 300) -> Dict[str, Any]: """ Execute an nmap command and return the results. Args: args: List of nmap command arguments timeout: Command timeout in seconds Returns: Dictionary containing command output, error, and exit code """ try: # Construct the full nmap command cmd = ["nmap"] + args logger.info(f"Executing nmap command: {' '.join(cmd)}") # Run the command with timeout result = subprocess.run( cmd, capture_output=True, text=True, timeout=timeout, check=False ) return { "stdout": result.stdout, "stderr": result.stderr, "exit_code": result.returncode, "success": result.returncode == 0 } except subprocess.TimeoutExpired: return { "stdout": "", "stderr": f"Command timed out after {timeout} seconds", "exit_code": -1, "success": False } except FileNotFoundError: return { "stdout": "", "stderr": "nmap command not found. Please ensure nmap is installed and in PATH", "exit_code": -1, "success": False } except Exception as e: return { "stdout": "", "stderr": f"Error executing nmap command: {str(e)}", "exit_code": -1, "success": False }