Automated network reconnaissance tool using Nmap and Python for ethical penetration testing.
READ THIS BEFORE USING THIS TOOL
Unauthorized network scanning is ILLEGAL in most jurisdictions and may result in:
United States: Computer Fraud and Abuse Act (CFAA) violations — up to 10 years imprisonment
European Union: Computer Misuse Act violations, GDPR breaches — criminal prosecution
Germany: StGB §202a/b (unauthorized data access) — up to 3 years imprisonment
UK: Computer Misuse Act 1990 — up to 2 years imprisonment
- Written authorization from the network owner
- Defined scope (IP ranges, ports, timeframe)
- Signed liability waiver
- Compliance with local laws and regulations
✅ Your own networks and devices
✅ Authorized penetration testing engagements
✅ Bug bounty programs with explicit permission
✅ Educational lab environments (isolated VMs)
✅ Capture The Flag (CTF) competitions
- You have explicit written permission to scan target networks
- You understand the legal consequences of unauthorized scanning
- You will not hold the author liable for any misuse
- You accept full responsibility for your actions
If you cannot provide written authorization, DO NOT USE THIS TOOL.
NMAP-Black-Python automates network reconnaissance by:
- Reading target domains/IPs from a text file
- Executing optimized Nmap scans with configurable options
- Parsing XML output for open ports and service detection
- Generating structured CSV reports for analysis
- Providing secure, injection-proof command execution
Built for: Security researchers, penetration testers, red teams, and students learning network security in controlled environments.
- Secure execution — no shell injection vulnerabilities
- Configurable scans — adjust ports, timing, and detection methods
- Batch processing — scan multiple targets from a file
- Structured output — CSV reports for easy analysis
- Error handling — graceful failures with detailed logging
- Timeout protection — prevents hanging scans
- Rate limiting — avoid overwhelming targets
# Debian/Ubuntu
sudo apt update && sudo apt install nmap python3 python3-pip
# RHEL/CentOS/Rocky
sudo yum install nmap python3 python3-pip
# macOS (Homebrew)
brew install nmap python3
# Arch Linux
sudo pacman -S nmap python- Python 3.8 or higher
None required — uses standard library only (subprocess, csv, xml.etree.ElementTree, shlex)
# Clone repository
git clone https://github.com/VolkanSah/NMAP-Black-Python.git
cd NMAP-Black-Python
# Verify Nmap installation
nmap --version
# Test Python
python3 --versionCreate targets.txt with one target per line:
192.168.1.1
example.com
10.0.0.0/24
testphp.vulnweb.com
python3 nmap_scanner.pyOutput files will be created:
target_name.xml— Full Nmap XML outputtarget_name.csv— Structured CSV report
Edit the script to customize scan behavior:
# Port ranges (default: common ports only)
PORTS = '21-23,25,53,80,110,143,443,445,993,995,3306,3389,5432,8080,8443'
# Scan timing (0=paranoid, 5=insane)
TIMING = 'T4' # Aggressive but reasonable
# Service detection
SERVICE_DETECTION = True # Enable -sV flag
# OS detection (requires root)
OS_DETECTION = False # Enable -O flag
# Timeout per target (seconds)
TIMEOUT = 600 # 10 minutesQuick scan (Top 100 ports):
PORTS = '--top-ports 100'
TIMING = 'T5'Comprehensive scan (All ports):
PORTS = '1-65535'
TIMING = 'T3'
TIMEOUT = 3600 # 1 hourStealth scan (IDS evasion):
TIMING = 'T1'
EXTRA_FLAGS = ['-f', '-D', 'RND:10'] # Fragmentation + decoysSecure implementation with injection prevention:
#!/usr/bin/env python3
import subprocess
import csv
import xml.etree.ElementTree as ET
import shlex
import sys
from pathlib import Path
# Configuration
TARGETS_FILE = 'targets.txt'
PORTS = '21-23,25,53,80,110,143,443,445,993,995,3306,3389,5432,8080,8443'
TIMING = 'T4'
TIMEOUT = 600
def read_targets(filename):
"""Read and validate target list"""
try:
with open(filename, 'r') as f:
targets = [line.strip() for line in f if line.strip() and not line.startswith('#')]
if not targets:
print(f"[!] No targets found in {filename}")
sys.exit(1)
return targets
except FileNotFoundError:
print(f"[!] File not found: {filename}")
sys.exit(1)
def scan_target(target):
"""Execute Nmap scan with security measures"""
# Sanitize target name for filename
safe_name = "".join(c for c in target if c.isalnum() or c in ".-_")
xml_file = f"{safe_name}.xml"
# Build command securely (no shell injection possible)
cmd = [
'nmap',
'-p', PORTS,
f'-{TIMING}',
'-sV', # Service detection
'--open', # Only show open ports
'-oX', xml_file,
target
]
print(f"[*] Scanning {target}...")
try:
result = subprocess.run(
cmd,
check=True,
timeout=TIMEOUT,
capture_output=True,
text=True
)
print(f"[+] Scan completed: {target}")
return xml_file
except subprocess.TimeoutExpired:
print(f"[!] Timeout exceeded for {target}")
return None
except subprocess.CalledProcessError as e:
print(f"[!] Scan failed for {target}: {e}")
return None
except FileNotFoundError:
print("[!] Nmap not found. Install with: sudo apt install nmap")
sys.exit(1)
def parse_results(xml_file):
"""Extract open ports and services from XML"""
try:
tree = ET.parse(xml_file)
root = tree.getroot()
results = {
'target': '',
'open_ports': [],
'services': []
}
# Extract target info
host = root.find('host')
if host is None:
return results
addr = host.find('address')
if addr is not None:
results['target'] = addr.get('addr', 'Unknown')
# Extract open ports and services
for port in host.findall('.//port'):
port_id = port.get('portid')
protocol = port.get('protocol')
state = port.find('state')
if state is not None and state.get('state') == 'open':
results['open_ports'].append(f"{port_id}/{protocol}")
service = port.find('service')
if service is not None:
svc_name = service.get('name', 'unknown')
svc_version = service.get('version', '')
service_str = f"{port_id}: {svc_name} {svc_version}".strip()
results['services'].append(service_str)
return results
except ET.ParseError as e:
print(f"[!] XML parsing error: {e}")
return None
except Exception as e:
print(f"[!] Unexpected error: {e}")
return None
def write_csv(target, results):
"""Write results to CSV file"""
safe_name = "".join(c for c in target if c.isalnum() or c in ".-_")
csv_file = f"{safe_name}.csv"
try:
with open(csv_file, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Target', 'Open Ports', 'Services'])
writer.writerow([
results['target'],
', '.join(results['open_ports']) if results['open_ports'] else 'None',
' | '.join(results['services']) if results['services'] else 'None'
])
print(f"[+] Results saved: {csv_file}")
except Exception as e:
print(f"[!] CSV write error: {e}")
def main():
print("""
╔═══════════════════════════════════════════════════════╗
║ NMAP-Black-Python Scanner ║
║ ⚠️ Only scan networks you have permission to access ║
╚═══════════════════════════════════════════════════════╝
""")
# Read targets
targets = read_targets(TARGETS_FILE)
print(f"[*] Loaded {len(targets)} target(s)")
# Scan each target
for target in targets:
xml_file = scan_target(target)
if xml_file and Path(xml_file).exists():
results = parse_results(xml_file)
if results:
write_csv(target, results)
print("\n[+] All scans completed")
if __name__ == '__main__':
main()Target,Open Ports,Services
192.168.1.1,"22/tcp, 80/tcp, 443/tcp","22: ssh OpenSSH 8.2 | 80: http Apache 2.4.41 | 443: https Apache 2.4.41"
Complete Nmap XML output preserved for advanced analysis with tools like:
xsltproc(convert to HTML)- Metasploit Framework (
db_import) - NmaptoCSV converters
- Custom parsing scripts
# Validate IP addresses
import ipaddress
try:
ipaddress.ip_address(target)
except ValueError:
print(f"[!] Invalid IP: {target}")import time
time.sleep(5) # 5 second delay between scansimport logging
logging.basicConfig(filename='scan.log', level=logging.INFO)
logging.info(f"Scanned {target} at {time.ctime()}")# Some scans require root privileges
sudo python3 nmap_scanner.py# Adjust timing template
TIMING = 'T5' # Faster but more detectable# Add firewall evasion flags
EXTRA_FLAGS = ['-Pn', '--source-port', '53']# Verify Nmap output manually
nmap -p 80 target.com -oX test.xml
cat test.xml# Download from https://www.virtualbox.org/- Metasploitable2 — Classic vulnerable Linux
- DVWA — Damn Vulnerable Web Application
- VulnHub images — https://www.vulnhub.com/
- Set VMs to "Host-Only" network
- Scan only
192.168.56.0/24range - Never expose VMs to internet
# Create safe target list
echo "192.168.56.101" > targets.txt
python3 nmap_scanner.pyFound bugs? Want to add features?
- Fork the repository
- Create feature branch (
git checkout -b feature/improvement) - Commit changes (
git commit -am 'Add new feature') - Push to branch (
git push origin feature/improvement) - Open Pull Request
Please include:
- Description of changes
- Test results
- Security considerations
If this tool helped you in your security research or studies:
- ⭐ Star this repository
- 🐛 Report bugs via Issues
- 💡 Suggest features via Discussions
- 💖 Become a Sponsor
Volkan Sah
- GitHub: @volkansah
- Website: volkansah.github.io
This project is licensed under the MIT License — see LICENSE file.
✅ Commercial use
✅ Modification
✅ Distribution
✅ Private use
┌─────────────────────────────────────────────────────────┐
│ 🚨 UNAUTHORIZED SCANNING IS A CRIME 🚨 │
│ │
│ Before running ANY scan, ask yourself: │
│ 1. Do I have WRITTEN permission? │
│ 2. Am I within the authorized scope? │
│ 3. Am I complying with local laws? │
│ │
│ If you answered NO to any question: │
│ ❌ STOP IMMEDIATELY │
│ │
│ Ignorance of the law is not a defense. │
│ You WILL be held accountable. │
└─────────────────────────────────────────────────────────┘
Use responsibly. Stay legal. Stay ethical.
Last updated: 2025/12
Version: 2.0
Status: Production-ready
