Okay, this is a complex request involving multiple tools, database interaction, report generation, and notifications. Here's a Python script structure that outlines how you could achieve this.
Limitations & Considerations:
- Tool Installation: This script assumes
nmap, subfinder, httpx, and nuclei are installed and accessible in your system's PATH.
- External Dependencies: You'll need to install Python libraries:
pymongo, python-telegram-bot, xhtml2pdf, Jinja2. Install them using pip:
pip install pymongo python-telegram-bot xhtml2pdf Jinja2
- PDF Styling: Achieving a specific "enterprise font," "colorized," "pretty" look with icons requires careful CSS work within the HTML template used for PDF generation. The example uses basic styling and Font Awesome for icons. Ensure the chosen font is available or handled correctly by
xhtml2pdf.
- Error Handling: Robust error handling (network issues, tool failures, DB connection errors, invalid data) is crucial for a production script. This example includes basic error handling.
- Configuration: Sensitive information (DB connection strings, Telegram Bot Token) should ideally be loaded from environment variables or a secure configuration management system, not hardcoded.
- Nmap Output: Nmap output can be complex. This script uses Grepable output (
-oG) for simplicity in parsing open ports and services. For more detail, consider XML (-oX) and libraries like xmltodict.
- Nuclei
-as flag: This flag isn't standard. Nuclei uses templates for scanning. -as might be a custom flag or typo. Common usage involves specifying template directories or tags (-t). The script assumes you want to run default or specified nuclei templates. Let's use -silent and capture JSON output for easier parsing.
- Concurrency: For scanning many domains, running these tasks sequentially can be slow. Consider using
asyncio or multiprocessing for parallel execution. This script runs sequentially for clarity.
- Logo Path: Ensure the
company_logo.png path is correct relative to where the script is run or provide an absolute path.
Project Structure:
security_scanner/
├── scanner.py # Main script
├── config.json # Configuration file
├── templates/
│ ├── report_template.html # HTML template for the PDF
│ └── company_logo.png # Your company logo
└── requirements.txt # Lists Python dependencies
1. config.json:
{
"mongodb_uri": "mongodb://localhost:27017/",
"database_name": "security_scans",
"domains_collection": "domains",
"scans_collection": "scan_history",
"company_name": "Your Awesome Corp",
"logo_path": "templates/company_logo.png",
"report_output_dir": "reports/",
"telegram_bot_token": "YOUR_TELEGRAM_BOT_TOKEN",
"nmap_path": "nmap",
"subfinder_path": "subfinder",
"httpx_path": "httpx",
"nuclei_path": "nuclei",
"nuclei_templates": "templates/default-templates.txt"
}
2. templates/report_template.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Security Scan Report - {{ domain }}</title>
<style>
body {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
margin: 40px;
color: #333;
font-size: 11pt;
}
h1, h2, h3 {
color: #0056b3; /* Enterprise blue */
}
.page-header {
text-align: center;
margin-bottom: 30px;
border-bottom: 2px solid #0056b3;
padding-bottom: 10px;
position: running(header); /* For reportlab/xhtml2pdf page numbering */
}
.page-header img {
max-width: 150px;
margin-bottom: 10px;
}
.page-header h1 {
margin: 0;
font-size: 24pt;
}
.report-meta {
font-size: 9pt;
color: #777;
text-align: right;
margin-bottom: 30px;
}
h2 {
border-bottom: 1px solid #ccc;
padding-bottom: 5px;
margin-top: 25px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 15px;
margin-bottom: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
color: #555;
}
.new {
background-color: #e6ffed; /* Light green */
color: #006400; /* Dark green */
}
.changed {
background-color: #fff0e6; /* Light orange */
color: #cc5500; /* Dark orange */
}
.removed {
background-color: #ffe6e6; /* Light red */
color: #cc0000; /* Dark red */
}
.icon {
font-family: "FontAwesome"; /* Use Font Awesome */
font-size: 1.1em;
margin-right: 5px;
}
.summary-item {
margin-bottom: 10px;
}
footer {
position: running(footer);
font-size: 8pt;
color: #777;
text-align: center;
width: 100%;
}
/* Ensure header/footer repeat on pages */
@page {
@top-center {
content: element(header);
}
@bottom-center {
content: element(footer) " - Page " counter(page);
}
}
</style>
<!-- Include Font Awesome (ensure accessibility or download) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="page-header">
<img src="{{ logo_path }}" alt="{{ company_name }} Logo">
<h1>Security Scan Report</h1>
<h2>{{ domain }}</h2>
</div>
<div class="report-meta">
<strong>Scan Date:</strong> {{ scan_timestamp}}<br>
<strong>Report Generated:</strong> {{ generation_timestamp }}
</div>
<h3>Scan Summary</h3>
<div class="summary">
<div class="summary-item"><strong>Discovered Subdomains:</strong> {{ summary.subdomains_count }}</div>
<div class="summary-item"><strong>Live HTTP(S) Services:</strong> {{ summary.live_http_count }}</div>
<div class="summary-item"><strong>Nmap Open Ports Found:</strong> {{ summary.open_ports_count }}</div>
<div class="summary-item"><strong>Vulnerabilities Found:</strong> {{ summary.vulnerabilities_count }}</div>
</div>
{% if differences %}
<h3>Changes Detected (vs Previous Scan)</h3>
<div class="differences">
{% if differences.new_ports %}
<h4>New Open Ports <span class="icon"></span></h4>
<table>
<thead>
<tr><th>Port</th><th>Service</th><th>Status</th></tr>
</thead>
<tbody>
{% for port, data in differences.new_ports.items() %}
<tr class="new">
<td>{{ port }}</td>
<td>{{ data.service }}</td>
<td>New</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% if differences.new_vulnerabilities %}
<h4>New Vulnerabilities <span class="icon"></span></h4>
<table>
<thead>
<tr><th>Vulnerability</th><th>Severity</th><th>URL/Target</th><th>Info</th></tr>
</thead>
<tbody>
{% for vuln in differences.new_vulnerabilities %}
<tr class="new">
<td>{{ vuln.template_id | default('N/A') }}</td>
<td>{{ vuln.info.severity | default('N/A') }}</td>
<td>{{ vuln.matched_at }}</td>
<td>{{ vuln.info.name | default('N/A') }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% if differences.closed_ports %}
<h4>Closed Ports <span class="icon"></span></h4>
<table>
<thead>
<tr><th>Port</th><th>Service</th><th>Status</th></tr>
</thead>
<tbody>
{% for port, data in differences.closed_ports.items() %}
<tr class="removed">
<td>{{ port }}</td>
<td>{{ data.service }}</td>
<td>Previously Open</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
<!-- Add sections for changed services if needed -->
</div>
{% else %}
{% if previous_scan %}
<h3>No significant changes detected since the last scan.</h3>
{% else %}
<h3>No previous scan data found for comparison. This is the baseline.</h3>
{% endif %}
{% endif %}
<h2>Detailed Scan Results</h2>
<h3>Nmap Scan Results</h3>
{% if results.nmap %}
<table>
<thead>
<tr><th>Port</th><th>State</th><th>Service</th><th>Info</th></tr>
</thead>
<tbody>
{% for port, data in results.nmap.items() %}
<tr>
<td>{{ port }}</td>
<td>{{ data.state }}</td>
<td>{{ data.service }}</td>
<td>{{ data.extra_info }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>Nmap scan did not return results or was not performed.</p>
{% endif %}
<h3>Subdomain Scan Results</h3>
{% if results.subdomains %}
<p>Found {{ results.subdomains | length }} subdomains:</p>
<ul>
{% for sub in results.subdomains %}
<li>{{ sub }}</li>
{% endfor %}
</ul>
{% else %}
<p>No subdomains found.</p>
{% endif %}
<h3>HTTP(S) Scan Results (httpx)</h3>
{% if results.httpx %}
<table>
<thead>
<tr><th>URL</th><th>Status</th><th>Title</th><th>CDN</th></tr>
</thead>
<tbody>
{% for item in results.httpx %}
<tr>
<td><a href="{{ item.url }}" target="_blank">{{ item.url }}</a></td>
<td>{{ item.status }}</td>
<td>{{ item.title | default('N/A') }}</td>
<td>{{ item.cdn | default('N/A') }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No live HTTP(S) services found.</p>
{% endif %}
<h3>Nuclei Scan Results (Vulnerabilities)</h3>
{% if results.nuclei %}
<table>
<thead>
<tr><th>Vulnerability ID</th><th>Severity</th><th>URL/Target</th><th>Info</th></tr>
</thead>
<tbody>
{% for vuln in results.nuclei %}
<tr>
<td>{{ vuln.template_id }}</td>
<td>{{ vuln.info.severity | default('N/A') }}</td>
<td>{{ vuln.matched_at }}</td>
<td>{{ vuln.info.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No vulnerabilities found by Nuclei.</p>
{% endif %}
<footer>{{ company_name }} | Automated Security Scan</footer>
</body>
</html>
3. scanner.py:
import subprocess
import json
import logging
import os
import datetime
import pymongo
from telegram import Bot
from telegram.error import TelegramError
from xhtml2pdf import pisa
from jinja2 import Environment, FileSystemLoader
# --- Configuration Loading ---
CONFIG_FILE = 'config.json'
def load_config():
"""Loads configuration from JSON file."""
try:
with open(CONFIG_FILE, 'r') as f:
config = json.load(f)
# Basic validation
required_keys = ["mongodb_uri", "database_name", "domains_collection",
"scans_collection", "company_name", "logo_path",
"report_output_dir", "telegram_bot_token"]
if not all(key in config for key in required_keys):
raise ValueError("Missing required keys in config file.")
# Ensure output directory exists
os.makedirs(config.get("report_output_dir", "reports/"), exist_ok=True)
return config
except FileNotFoundError:
logging.error(f"Configuration file '{CONFIG_FILE}' not found.")
exit(1)
except (json.JSONDecodeError, ValueError) as e:
logging.error(f"Error reading configuration file: {e}")
exit(1)
# --- Logging Setup ---
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# --- Global Config & DB Connection ---
config = load_config()
try:
client = pymongo.MongoClient(config['mongodb_uri'])
db = client[config['database_name']]
domains_collection = db[config['domains_collection']]
scans_collection = db[config['scans_collection']]
logging.info("Successfully connected to MongoDB.")
except pymongo.errors.ConnectionFailure as e:
logging.error(f"Could not connect to MongoDB: {e}")
exit(1)
except Exception as e:
logging.error(f"An error occurred during MongoDB setup: {e}")
exit(1)
# --- Telegram Bot ---
try:
bot = Bot(token=config['telegram_bot_token'])
except Exception as e:
logging.error(f"Failed to initialize Telegram bot. Is the token correct? Error: {e}")
bot = None # Continue without Telegram if initialization fails
# --- Helper Functions ---
def run_command(command, input_data=None, capture_output=True, text=True, shell=False):
"""Executes a command using subprocess."""
logging.info(f"Running command: {' '.join(command)}")
try:
process = subprocess.run(
command,
input=input_data,
capture_output=capture_output,
text=text,
check=True, # Raise exception on non-zero exit
shell=shell, # Use shell=True carefully
encoding='utf-8',
errors='ignore' # Ignore decoding errors
)
return process.stdout.strip()
except FileNotFoundError:
logging.error(f"Command not found: {command[0]}. Is it installed and in PATH?")
return None
except subprocess.CalledProcessError as e:
logging.error(f"Command failed: {' '.join(command)}\nError: {e}\nStderr: {e.stderr}")
return None
except Exception as e:
logging.error(f"An unexpected error occurred running command {' '.join(command)}: {e}")
return None
def parse_nmap_grepable(output):
"""Parses Nmap -oG output into a dictionary."""
results = {}
if not output:
return results
for line in output.split('\n'):
if "Host: " in line and "Status: Up" in line:
parts = line.split()
ip_index = parts.index("Host:") + 1
ip_address = parts[ip_index].rstrip('/') # Remove trailing slash if present
port_index = parts.index("Ports:")
ports_str = parts[port_index+1:]
current_ports = {}
for port_info in ports_str:
try:
port, state = port_info.split('/')[:2]
if state == 'open':
# Try to get service info if available later in the line
service = "unknown"
extra_info = ""
try:
# Find service info which follows the port state
port_detail_parts = port_info.split()
if len(port_detail_parts) > 2:
service = port_detail_parts[2]
if len(port_detail_parts) > 3:
extra_info = " ".join(port_detail_parts[3:])
except Exception:
pass # Ignore errors getting service details
current_ports[port] = {"state": state, "service": service, "extra_info": extra_info}
except ValueError:
continue # Ignore malformed port strings
results[ip_address] = current_ports
# Return ports for the first IP found, assuming scan is for a single host/domain
if results:
return list(results.values())[0] # Return ports dict for the first host
return {}
def parse_json_output(output):
"""Parses JSON output, handling potential multiple JSON objects."""
results = []
if not output:
return results
# Handle cases where output might contain multiple JSON objects separated by newlines
potential_json = f"[{output.strip()}]" if not output.strip().startswith('[') else output.strip()
try:
# Attempt to load if it's a single JSON object or list
data = json.loads(potential_json)
if isinstance(data, list):
# Filter out nulls/empty dicts that might occur from multiple objects
return [item for item in data if item and isinstance(item, dict)]
elif isinstance(data, dict):
return [data] # Return as a list containing the single dict
else:
logging.warning("JSON output was neither a list nor a dict.")
return []
except json.JSONDecodeError:
# Try splitting by lines if it looks like multiple JSON objects
logging.warning("Failed to parse output as single JSON. Attempting line-by-line parse.")
lines = output.strip().split('\n')
for line in lines:
try:
if line.strip():
results.append(json.loads(line.strip()))
except json.JSONDecodeError:
logging.error(f"Failed to parse line as JSON: {line[:100]}...") # Log snippet
return [item for item in results if item] # Filter out empties
except Exception as e:
logging.error(f"Unexpected error parsing JSON output: {e}")
return []
def scan_subdomains(domain):
"""Scans for subdomains using subfinder."""
command = [config.get('subfinder_path', 'subfinder'), '-d', domain, '-silent']
output = run_command(command)
return output.split('\n') if output else []
def scan_http_services(subdomains):
"""Checks live HTTP/S services using httpx."""
if not subdomains:
return []
# Prepare input for httpx
subdomains_input = "\n".join(subdomains)
command = [config.get('httpx_path', 'httpx'), '-silent', '-title', '-web-status-code', '-cl', '-cdn', '-json']
output = run_command(command, input_data=subdomains_input)
return parse_json_output(output)
def scan_vulnerabilities(urls):
"""Scans for vulnerabilities using nuclei."""
if not urls:
return []
nuclei_templates = config.get('nuclei_templates', None)
if not nuclei_templates or not os.path.exists(nuclei_templates):
logging.warning(f"Nuclei templates '{nuclei_templates}' not found or specified. Running without specific templates.")
template_arg = []
else:
template_arg = ['-t', nuclei_templates]
# Process URLs in batches if the list is very large to avoid command line length limits
all_vulns = []
batch_size = 50 # Adjust as needed
for i in range(0, len(urls), batch_size):
batch_urls = urls[i:i+batch_size]
# Use file input for potentially long lists
url_file = f"temp_urls_{i}.txt"
with open(url_file, "w") as f:
for url in batch_urls:
f.write(url + "\n")
# Run nuclei, requesting JSON output
command = [config.get('nuclei_path', 'nuclei'), '-silent', '-json'] + template_arg + ['-l', url_file]
output = run_command(command)
# Nuclei might output multiple JSON objects, one per line
parsed_output = parse_json_output(output)
all_vulns.extend(parsed_output)
# Clean up temp file
try:
os.remove(url_file)
except OSError as e:
logging.warning(f"Could not remove temporary file {url_file}: {e}")
# Filter for actual vulnerabilities (sometimes nuclei outputs status info)
return [vuln for vuln in all_vulns if 'template-id' in vuln and 'matched-at' in vuln]
def scan_nmap(target_domain):
"""Performs Nmap scan on the target domain."""
command = [
config.get('nmap_path', 'nmap'),
'-sC', # Default script scanning
'-T4', # Faster scan timing
'-oG', '-', # Grepable output to stdout
target_domain
]
output = run_command(command)
return parse_nmap_grepable(output)
def store_scan_results(domain_name, nmap_res, sub_res, http_res, nucl_res):
"""Stores the results of the current scan in MongoDB."""
timestamp = datetime.datetime.utcnow()
scan_data = {
"domain": domain_name,
"timestamp": timestamp,
"nmap": nmap_res,
"subdomains": sub_res,
"httpx": http_res,
"nuclei": nucl_res
}
try:
scans_collection.insert_one(scan_data)
logging.info(f"Stored scan results for {domain_name} with timestamp {timestamp}")
return True
except Exception as e:
logging.error(f"Failed to store scan results for {domain_name}: {e}")
return False
def get_previous_scan(domain_name):
"""Retrieves the most recent scan results for a domain."""
try:
latest_scan = scans_collection.find_one(
{"domain": domain_name},
sort=[("timestamp", pymongo.DESCENDING)]
)
return latest_scan
except Exception as e:
logging.error(f"Failed to retrieve previous scan for {domain_name}: {e}")
return None
def compare_results(current_scan, previous_scan):
"""Compares current scan results with previous ones."""
differences = {
"new_ports": {},
"closed_ports": {},
"new_vulnerabilities": [],
"resolved_vulnerabilities": [],
"changed_services": {} # Placeholder for future enhancement
}
if not previous_scan:
return differences # Nothing to compare against
# Compare Nmap Ports
current_ports = current_scan.get('nmap', {})
prev_ports = previous_scan.get('nmap', {})
current_port_keys = set(current_ports.keys())
prev_port_keys = set(prev_ports.keys())
differences["new_ports"] = {p: d for p, d in current_ports.items() if p not in prev_port_keys and d['state']=='open'}
differences["closed_ports"] = {p: d for p, d in prev_ports.items() if p not in current_port_keys and d['state']=='open'}
# Compare Nuclei Vulnerabilities (simplified check: just list new ones)
current_vulns = current_scan.get('nuclei', [])
prev_vulns = previous_scan.get('nuclei', [])
# Create sets for easier comparison (using template_id and matched_at)
current_vuln_set = {(v.get('template_id'), v.get('matched_at')) for v in current_vulns}
prev_vuln_set = {(v.get('template_id'), v.get('matched_at')) for v in prev_vulns}
new_vulns_found = current_vuln_set - prev_vuln_set
resolved_vulns_found = prev_vuln_set - current_vuln_set
# Map back to full details for new vulns
current_vulns_map = {(v.get('template_id'), v.get('matched_at')): v for v in current_vulns}
differences["new_vulnerabilities"] = [current_vulns_map[key] for key in new_vulns_found]
# Optionally, find resolved vulns (requires mapping back from prev_vulns)
# prev_vulns_map = {(v.get('template_id'), v.get('matched_at')): v for v in prev_vulns}
# differences["resolved_vulnerabilities"] = [prev_vulns_map[key] for key in resolved_vulns_found]
# Future: Compare httpx results, subdomain changes etc.
# Filter out empty differences
differences = {k: v for k, v in differences.items() if v}
return differences
def generate_pdf_report(domain_name, current_scan_data, differences):
"""Generates a PDF report using HTML template."""
template_dir = os.path.dirname(os.path.abspath(__file__)) + '/templates'
env = Environment(loader=FileSystemLoader(template_dir))
template = env.get_template('report_template.html')
# Prepare summary data
summary = {
"subdomains_count": len(current_scan_data.get('subdomains', [])),
"live_http_count": len(current_scan_data.get('httpx', [])),
"open_ports_count": sum(1 for p,d in current_scan_data.get('nmap', {}).items() if d['state'] == 'open'),
"vulnerabilities_count": len(current_scan_data.get('nuclei', []))
}
# Add logo path and company name to context
context = {
"domain": domain_name,
"scan_timestamp": current_scan_data['timestamp'].strftime('%Y-%m-%d %H:%M:%S UTC'),
"generation_timestamp": datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC'),
"results": current_scan_data,
"differences": differences,
"previous_scan": differences is not None and differences != {}, # Flag if comparison was done
"summary": summary,
"company_name": config.get("company_name", "Company"),
"logo_path": os.path.abspath(config.get("logo_path", "company_logo.png")) # Absolute path needed for pisa
}
html_out = template.render(context)
pdf_filename = os.path.join(config.get("report_output_dir", "reports/"), f"{domain_name}_scan_report_{current_scan_data['timestamp'].strftime('%Y%m%d_%H%M%S')}.pdf")
try:
with open(pdf_filename, "w+b") as result_file:
pisa_status = pisa.CreatePDF(
html_out.encode('utf-8'), # Ensure content is bytes
dest=result_file,
encoding='utf-8'
)
if pisa_status.err:
logging.error(f"PDF generation failed for {domain_name}: {pisa_status.err}")
return None
else:
logging.info(f"Successfully generated PDF report: {pdf_filename}")
return pdf_filename
except Exception as e:
logging.error(f"Error during PDF creation for {domain_name}: {e}")
return None
def send_telegram_report(chat_id, pdf_path):
"""Sends the generated PDF report via Telegram."""
if not bot:
logging.warning("Telegram bot not initialized. Cannot send report.")
return False
if not chat_id:
logging.warning(f"No chat_id provided for sending report to {pdf_path}.")
return False
if not pdf_path or not os.path.exists(pdf_path):
logging.error(f"PDF report path is invalid or file does not exist: {pdf_path}")
return False
try:
with open(pdf_path, 'rb') as f:
logging.info(f"Sending report {pdf_path} to Telegram chat ID {chat_id}...")
sent_message = bot.send_document(chat_id=chat_id, document=f, caption=f"Security scan report for {os.path.basename(pdf_path)}")
if sent_message:
logging.info(f"Report successfully sent to chat ID {chat_id}.")
return True
else:
logging.error(f"Failed to send report to chat ID {chat_id}. Unknown reason.")
return False
except TelegramError as e:
logging.error(f"Telegram API error sending report to {chat_id}: {e}")
return False
except FileNotFoundError:
logging.error(f"File not found when trying to send via Telegram: {pdf_path}")
return False
except Exception as e:
logging.error(f"An unexpected error occurred sending report via Telegram: {e}")
return False
# --- Main Execution Logic ---
def process_domain(domain_entry):
"""Processes a single domain entry from MongoDB."""
domain_name = domain_entry['name']
telegram_id = domain_entry.get('telegram_id')
logging.info(f"--- Processing domain: {domain_name} ---")
# 1. Subdomain Scan
subdomains = scan_subdomains(domain_name)
logging.info(f"Found {len(subdomains)} subdomains.")
# 2. HTTP/S Scan
live_http_services = []
if subdomains:
# Add the main domain itself in case subfinder misses it or for direct scanning
targets_for_http = list(set([f"http://{domain_name}", f"https://{domain_name}"] + [f"http://{s}" for s in subdomains if s] + [f"https://{s}" for s in subdomains if s]))
logging.info(f"Scanning {len(targets_for_http)} potential HTTP/S targets...")
live_http_services = scan_http_services(targets_for_http)
logging.info(f"Found {len(live_http_services)} live HTTP(S) services.")
# Extract just the URLs for nuclei
live_urls_for_nuclei = [s.get('url') for s in live_http_services if s.get('url')]
else:
live_urls_for_nuclei = [f"http://{domain_name}", f"https://{domain_name}"]
logging.info("No subdomains found, scanning main domain for HTTP/S.")
live_http_services = scan_http_services(live_urls_for_nuclei)
logging.info(f"Found {len(live_http_services)} live HTTP(S) services for main domain.")
live_urls_for_nuclei = [s.get('url') for s in live_http_services if s.get('url')]
# 3. Vulnerability Scan (Nuclei)
vulnerabilities = []
if live_urls_for_nuclei:
logging.info(f"Scanning {len(live_urls_for_nuclei)} URLs for vulnerabilities...")
vulnerabilities = scan_vulnerabilities(live_urls_for_nuclei)
logging.info(f"Found {len(vulnerabilities)} potential vulnerabilities.")
else:
logging.warning("No live URLs to scan with Nuclei.")
# 4. Nmap Scan (on the main domain)
logging.info(f"Performing Nmap scan on {domain_name}...")
nmap_results = scan_nmap(domain_name)
logging.info(f"Nmap found {len(nmap_results)} open ports.")
# Prepare current scan data structure
current_scan = {
"domain": domain_name,
"timestamp": datetime.datetime.utcnow(),
"nmap": nmap_results,
"subdomains": subdomains,
"httpx": live_http_services,
"nuclei": vulnerabilities
}
# 5. Store results
stored = store_scan_results(domain_name, nmap_results, subdomains, live_http_services, vulnerabilities)
if not stored:
logging.error(f"Stopping processing for {domain_name} due to storage failure.")
return
# 6. Compare with previous scan
previous_scan = get_previous_scan(domain_name)
differences = compare_results(current_scan, previous_scan)
# 7. Generate Report
pdf_report_path = generate_pdf_report(domain_name, current_scan, differences)
# 8. Send Report via Telegram
if pdf_report_path and telegram_id:
send_telegram_report(telegram_id, pdf_report_path)
elif not telegram_id:
logging.warning(f"No Telegram ID found for {domain_name} in DB. Cannot send report.")
elif not pdf_report_path:
logging.error(f"Failed to generate report for {domain_name}, cannot send.")
logging.info(f"--- Finished processing domain: {domain_name} ---")
if __name__ == "__main__":
logging.info("Starting automated security scan process...")
# Fetch domains to scan from MongoDB
try:
domains_to_scan = list(domains_collection.find({"enabled": True})) # Assuming a field to enable/disable scans
if not domains_to_scan:
logging.warning("No enabled domains found in MongoDB.")
else:
logging.info(f"Found {len(domains_to_scan)} domains to scan.")
for domain_entry in domains_to_scan:
process_domain(domain_entry)
except Exception as e:
logging.error(f"An error occurred during the main loop: {e}")
finally:
# Close MongoDB connection
if 'client' in locals() and client:
client.close()
logging.info("MongoDB connection closed.")
logging.info("Security scan process finished.")
How to Use:
- Save: Save the Python code as
scanner.py and the JSON as config.json in the same directory. Create a templates subdirectory and place report_template.html and your company_logo.png inside it.
- Configure: Edit
config.json with your MongoDB details, Telegram Bot Token, and correct paths to tools and the logo. Make sure your MongoDB is running. Get a Telegram Bot Token from BotFather on Telegram.
- Populate MongoDB:
- Run: Execute the script from your terminal:
python scanner.py
- Check Reports: Generated PDF reports will appear in the directory specified by
report_output_dir in config.json. Check the script's output and logs for progress and errors. Reports will be sent to the specified Telegram IDs.
This comprehensive script provides a solid foundation for automating your security scanning workflow. Remember to adapt the tool paths, template styling, and error handling to your specific environment and needs.