The Problem Every Developer Faces
Want to integrate Nmap into your web application? You'll quickly discover three brutal realities: subprocess management is messy, shell injection vulnerabilities are everywhere, and cross-platform compatibility is a constant headache.
Traditional approaches leave you wrestling with dangerous string concatenation, endless boilerplate code for process handling, and the nightmare of integrating Python subprocess logic into JavaScript frontends or mobile apps.
The Solution: nmap-exec-api
nmap-exec-api transforms Nmap into a modern REST API. Instead of managing subprocesses and shell commands, you send simple JSON requests. No shell injection risks, no subprocess headaches, and it works with any programming language.
The Core Innovation: ID-Based Options
Every Nmap option gets a numeric ID. Instead of concatenating dangerous command strings, you send structured data:
fetch('http://localhost:8000/scan', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
target: "192.168.1.1",
options: [
{ id: 30 }, // TCP SYN scan
{ id: 50, value: "1-1000" } // Port range
]
})
})
This design eliminates shell injection by construction—there's no user-controlled string interpolation in the execution path.
Two Implementations for Different Needs
The project provides two distinct implementations, each serving a specific purpose.
nmap-testing.py: Developer Foundation
Clean, minimal boilerplate designed for integration into existing systems. Perfect when you need custom authentication flows, specialized validation logic, or integration with existing microservices. Minimal dependencies: just FastAPI and uvicorn.
Use this when building your own API service, integrating into existing applications, or when you need full control over the implementation.
main.py: Ready-to-Run Testing Tool
Not production-grade, but includes essential features for localhost/loopback usage and testing on your own devices. This implementation demonstrates what a complete setup looks like with automatic file management, path sanitization, and built-in XML parsing.
Key features include safe file handling with automatic path sanitization, automatic directory management in the nmap_scans/ folder, auto-generated XML output for all scans, built-in XML parser with structured JSON output, path traversal protection, UUID-based unique filenames to prevent conflicts, and Windows compatibility using Hypercorn.
Use this when testing locally with Postman or curl on 127.0.0.1, quick prototyping and experimentation on your own device, or when you need immediate functionality without modifications. It's particularly useful for Windows users where uvicorn's SelectorEventLoop causes problems.
Desktop Application Demo
An experimental desktop UI demonstration is available via GitHub Releases. This release includes two executable files: server.exe running the FastAPI backend and ui.exe providing a React + Vite desktop interface.
The setup demonstrates how this API can power real desktop applications, not just web or CLI tools. Both components run strictly on localhost with no outbound network connections—the server runs on 127.0.0.1:8000 and the UI on 127.0.0.1:4565.
This isn't an advanced security product or a Zenmap replacement. Instead, it focuses on clean, modern UI design, clear scan workflows, better usability for everyday Nmap users, and treating Nmap as a first-class tool rather than a hidden backend.
For Nmap users who want a cleaner interface and easier scan composition, this UI may genuinely improve your workflow. For developers, it demonstrates how this API can be turned into a desktop application and how a React + Vite UI sits cleanly on top of the backend.
The provided binaries are Windows executables, but the architecture is cross-platform. You can compile and package this project for Linux or macOS environments. The desktop UI was created with the help of Lovable AI.
Download at: GitHub Releases
Understanding Output Modes
The API tracks output formats and makes retrieval intelligent. When you run a scan, the response tells you exactly how to get the results: Mode 1 for normal text output, Mode 2 for XML with structured parsing, and Mode 3 for all-format scans.
Even if you only request text output, the API automatically generates an XML file in the background. This means you can always get structured, parseable data regardless of what output format was originally requested. The response includes an auto_xml path that you can use to retrieve parsed JSON results.
Windows Compatibility
The main.py implementation uses Hypercorn instead of uvicorn for Windows compatibility. uvicorn uses SelectorEventLoop on Windows, which breaks subprocess execution, while Hypercorn uses ProactorEventLoop for reliable scanning across all platforms.
While the API runs perfectly on Windows, Nmap itself has platform limitations. Features like SYN scans and OS detection may require administrator privileges or behave differently than on Linux. For maximum accuracy and capability, Linux or WSL is recommended.
Comprehensive Option Catalog
The API supports over 50 Nmap options organized into logical categories: scan techniques (TCP SYN, Connect, ACK, UDP, and specialized scans), service detection with configurable intensity, OS detection with various scanning modes, and multiple output formats.
Each option is identified by a simple numeric ID, making integration straightforward regardless of your programming language. For the complete option table, API endpoints documentation, usage examples, and implementation details, please read the repository README, which explains everything in full detail.
Critical Security Requirements
This API is a foundation, not a complete solution. Before deploying to production, you must add essential security layers.
Implement authentication using OAuth2, JWT tokens, or API key validation. Every request should verify the user's identity and permissions before executing scans. Create an allowlist of networks or IP ranges that can be scanned, rejecting any target outside your authorized scope.
Set up rate limiting per user and per IP to prevent a single user from overwhelming your scanning infrastructure. Track every scan request with timestamps, user identities, targets, and results for security monitoring and compliance.
The main.py implementation includes built-in path sanitization that strips directory traversal attempts and forces all files into a safe directory with UUID-based names, preventing unauthorized file access and naming conflicts.
Production Deployment Considerations
The project is a lightweight boilerplate designed to minimize dependencies and infrastructure requirements. It provides a clean, auditable foundation rather than a fully production-hardened service.
Before deploying, implement authentication (OAuth2, JWT, or API keys), authorization with role-based access control, target validation through CIDR whitelisting, rate limiting per user and IP, comprehensive logging with audit trails, and health monitoring with metrics and alerting.
Advanced production features are intentionally excluded to reduce dependencies and allow you to add only what your environment requires. The default implementation provides no security features—adding them based on your requirements is your responsibility.
Real-World Use Cases
Security Monitoring Dashboards
Build React, Vue, or Angular interfaces for real-time network visibility. Your frontend sends JSON requests, the API handles all the Nmap complexity, and you get back structured data ready for visualization.
CI/CD Integration
Integrate automated vulnerability scanning into deployment pipelines. Every production deployment triggers a scan, and results feed directly into your security reporting systems.
Mobile Applications
Create iOS or Android network diagnostic tools. The JSON interface means your mobile app doesn't need to bundle Nmap or manage complex native integrations.
Compliance Reporting
Schedule regular scans with automated report generation. The structured output makes it easy to track changes over time and demonstrate compliance.
Incident Response
Enable rapid network assessment during security incidents. Security teams can trigger comprehensive scans through a clean interface without SSH access to scanning infrastructure.
Getting Started
Installation is straightforward. Clone the repository, install FastAPI and uvicorn for the basic version, or add python-libnmap and hypercorn for the full-featured implementation.
git clone https://github.com/hejhdiss/nmap-exec-api.git
cd nmap-exec-api
pip install fastapi uvicorn
# Run the API
uvicorn nmap-testing:app --host 0.0.0.0 --port 8000 --reload
Test it immediately with a simple curl request or Postman. The API documentation is available at http://localhost:8000/docs.
Why This Approach Wins
Time savings: Go from 50+ lines of subprocess management and error handling to 5 lines of clean JSON requests.
Cross-platform: Works anywhere that speaks HTTP. Your backend can be Python, your frontend JavaScript, your mobile app Swift or Kotlin—it doesn't matter.
Security: Structured input eliminates entire classes of injection vulnerabilities that plague traditional command-line integrations.
Future-proof: Adding new Nmap options requires zero changes to your client code. Just update the option catalog and clients automatically get new capabilities.
Maintainability: Clear separation between Nmap execution and application logic makes debugging and updates vastly simpler.
Legal and Ethical Notice
This tool is for authorized security testing only.
You must have explicit written permission before scanning any network or system. Unauthorized network scanning may violate computer fraud laws in your jurisdiction. This tool is designed for legitimate security research, compliance testing, and authorized vulnerability assessment.
The author assumes no responsibility for misuse. Use responsibly and legally.
Project Information
Repository: https://github.com/hejhdiss/nmap-exec-api
License: Apache 2.0 (free for commercial use)
Author: Muhammed Shafin P (@hejhdiss)
The Apache 2.0 license means you can freely use, modify, and distribute this project in both open source and proprietary commercial software. Attribution is appreciated but not required.
Contributing and Community
Contributions are welcome and encouraged. Whether you've found a bug, have a feature request, or want to submit a pull request, head over to the GitHub repository. The project benefits from community input and real-world usage feedback.
If this project helps you build something cool, consider starring the repository on GitHub. It helps others discover the project and shows appreciation for the work.
Building web-based security tools just got significantly easier. No more subprocess nightmares, no more shell injection fears, no more cross-language integration headaches. Just clean JSON requests and structured responses, ready to power your next security application.
Top comments (0)