To handle multiple domains for a single company, we’ll restructure the script and template to:
- Store companies in MongoDB, each with:
- A list of associated domains
- A Telegram ID (for report delivery)
- Run scans across all domains under one company
- Generate a single PDF report per company, summarizing results from all its domains
- Compare current scan data against previous scans on a domain-by-domain basis
✅ Updated Features
- MongoDB Structure: Company → Domains
- Single Report: One consolidated report per company
- Domain-level comparison: Track changes individually per domain
- PDF Template: Unified view with all domains' findings and differences
🗂️ Project Structure
company_scanner/
├── scanner.py
├── config.json
├── templates/
│ ├── report_template.html
│ └── company_logo.png
└── requirements.txt
🔧 config.json
{
"mongodb_uri": "mongodb://localhost:27017/",
"database_name": "security_scans",
"companies_collection": "companies",
"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"
}
📄 templates/report_template.html (Updated)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Security Scan Report - {{ company }}</title>
<style>
body {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
margin: 40px;
color: #333;
font-size: 11pt;
}
h1, h2, h3 {
color: #0056b3;
}
.page-header {
text-align: center;
margin-bottom: 30px;
border-bottom: 2px solid #0056b3;
padding-bottom: 10px;
}
.page-header img {
max-width: 150px;
margin-bottom: 10px;
}
.domain-section {
page-break-before: always;
margin-top: 40px;
}
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; color: #006400; }
.removed { background-color: #ffe6e6; color: #cc0000; }
.changed { background-color: #fff0e6; color: #cc5500; }
.icon {
font-family: "FontAwesome";
font-size: 1.1em;
margin-right: 5px;
}
</style>
</head>
<body>
<div class="page-header">
<img src="{{ logo }}" alt="{{ company }} Logo">
<h1>Security Scan Report</h1>
<h2>{{ company }}</h2>
<p><strong>Scan Date:</strong> {{ scan_time }}</p>
</div>
{% for domain_data in all_domains %}
<div class="domain-section">
<h2>Domain: {{ domain_data.domain }}</h2>
{% if domain_data.differences %}
<h3>Changes Detected (vs Previous Scan)</h3>
{% if domain_data.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, info in domain_data.differences.new_ports.items() %}
<tr class="new"><td>{{ port }}</td><td>{{ info.service }}</td><td>New</td></tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% if domain_data.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, info in domain_data.differences.closed_ports.items() %}
<tr class="removed"><td>{{ port }}</td><td>{{ info.service }}</td><td>Closed</td></tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% if domain_data.differences.new_vulnerabilities %}
<h4>New Vulnerabilities <span class="icon"></span></h4>
<table>
<thead><tr><th>Vulnerability</th><th>Severity</th><th>Target</th><th>Description</th></tr></thead>
<tbody>
{% for vuln in domain_data.differences.new_vulnerabilities %}
<tr class="new">
<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>
{% endif %}
{% else %}
<h3>No significant changes detected since last scan.</h3>
{% endif %}
<h3>Nmap Results</h3>
{% if domain_data.scan.nmap %}
<table>
<thead><tr><th>Port</th><th>State</th><th>Service</th><th>Info</th></tr></thead>
<tbody>
{% for port, info in domain_data.scan.nmap.items() %}
<tr><td>{{ port }}</td><td>{{ info.state }}</td><td>{{ info.service }}</td><td>{{ info.extra_info }}</td></tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No open ports found via Nmap.</p>
{% endif %}
<h3>Subdomains</h3>
{% if domain_data.scan.subdomains %}
<ul>
{% for sub in domain_data.scan.subdomains %}
<li>{{ sub }}</li>
{% endfor %}
</ul>
{% else %}
<p>No subdomains discovered.</p>
{% endif %}
<h3>HTTP(S) Services</h3>
{% if domain_data.scan.httpx %}
<table>
<thead><tr><th>URL</th><th>Status</th><th>Title</th><th>CDN</th></tr></thead>
<tbody>
{% for item in domain_data.scan.httpx %}
<tr>
<td><a href="{{ item.url }}" target="_blank">{{ item.url }}</a></td>
<td>{{ item.status }}</td>
<td>{{ item.title }}</td>
<td>{{ item.cdn }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No live HTTP(S) services found.</p>
{% endif %}
<h3>Vulnerabilities Found</h3>
{% if domain_data.scan.nuclei %}
<table>
<thead><tr><th>ID</th><th>Severity</th><th>Target</th><th>Name</th></tr></thead>
<tbody>
{% for vuln in domain_data.scan.nuclei %}
<tr>
<td>{{ vuln.template_id }}</td>
<td>{{ vuln.info.severity }}</td>
<td>{{ vuln.matched_at }}</td>
<td>{{ vuln.info.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No vulnerabilities found by Nuclei.</p>
{% endif %}
</div>
{% endfor %}
</body>
</html>
🐍 scanner.py (Updated Version)
import subprocess
import json
import os
import datetime
import pymongo
from telegram import Bot
from xhtml2pdf import pisa
from jinja2 import Environment, FileSystemLoader
# --- Configuration ---
def load_config():
try:
with open("config.json") as f:
return json.load(f)
except Exception as e:
print(f"[!] Error loading config: {e}")
exit(1)
config = load_config()
# --- Logging ---
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# --- MongoDB Setup ---
client = pymongo.MongoClient(config["mongodb_uri"])
db = client[config["database_name"]]
companies_col = db[config["companies_collection"]]
scans_col = db[config["scans_collection"]]
# --- Telegram Setup ---
bot = Bot(token=config["telegram_bot_token"])
# --- Helper Functions ---
def run_cmd(cmd):
try:
return subprocess.check_output(cmd, shell=True, stderr=subprocess.DEVNULL).decode()
except:
return ""
def parse_nmap(output):
result = {}
for line in output.splitlines():
if "Ports:" in line:
parts = line.split("Ports:")[1].split(",")
for p in parts:
if "/open/" in p:
port = p.split("/")[0].strip()
service = p.split("/")[-1].strip()
result[port] = {"state": "open", "service": service, "extra_info": ""}
return result
def store_scan(domain, data):
data["domain"] = domain
scans_col.insert_one(data)
def get_previous(domain):
return scans_col.find_one({"domain": domain}, sort=[("timestamp", -1)])
def compare(current, previous):
diff = {"new_ports": {}, "closed_ports": {}, "new_vulnerabilities": []}
curr_ports = set(current.get("nmap", {}).keys())
prev_ports = set(previous.get("nmap", {}).keys()) if previous else set()
new_p = curr_ports - prev_ports
closed_p = prev_ports - curr_ports
diff["new_ports"] = {p: current["nmap"][p] for p in new_p}
diff["closed_ports"] = {p: previous["nmap"][p] for p in closed_p if previous}
# Vulnerabilities
curr_vulns = {(v["template_id"], v["matched_at"]) for v in current.get("nuclei", [])}
prev_vulns = {(v["template_id"], v["matched_at"]) for v in previous.get("nuclei", [])} if previous else set()
new_vulns = curr_vulns - prev_vulns
diff["new_vulnerabilities"] = [v for v in current.get("nuclei", []) if (v["template_id"], v["matched_at"]) in new_vulns]
return diff if any(diff.values()) else None
# --- Scanning Logic ---
def scan_domain(domain):
logging.info(f"Scanning domain: {domain}")
# Subfinder
subs = run_cmd(f"subfinder -d {domain} -silent").splitlines()
# Nmap
nmap_out = run_cmd(f"nmap -sC -T4 -oG - {domain}")
nmap_res = parse_nmap(nmap_out)
# Httpx
http_input = "\n".join([f"http://{s}" for s in subs] + [f"https://{s}" for s in subs])
http_res = []
if http_input.strip():
http_json = run_cmd(f"echo '{http_input}' | httpx -silent -title -web-status-code -cl -cdn -json")
http_res = [json.loads(line) for line in http_json.strip().splitlines()]
# Nuclei
urls = [item["url"] for item in http_res]
nucl_res = []
if urls:
url_file = "urls.txt"
with open(url_file, "w") as f:
f.write("\n".join(urls))
nucl_json = run_cmd(f"cat {url_file} | nuclei -silent -json")
nucl_res = [json.loads(line) for line in nucl_json.strip().splitlines()]
os.remove(url_file)
# Build Result
scan_data = {
"timestamp": datetime.datetime.utcnow(),
"nmap": nmap_res,
"subdomains": subs,
"httpx": http_res,
"nuclei": nucl_res
}
store_scan(domain, scan_data)
return scan_data
# --- PDF Generation ---
def generate_report(company_name, domains_data):
env = Environment(loader=FileSystemLoader("templates"))
template = env.get_template("report_template.html")
context = {
"company": company_name,
"scan_time": datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"),
"logo": os.path.abspath(config["logo_path"]),
"all_domains": []
}
for domain, scan_data in domains_data.items():
previous = get_previous(domain)
diff = compare(scan_data, previous) if previous else None
context["all_domains"].append({
"domain": domain,
"scan": scan_data,
"differences": diff
})
html = template.render(context)
filename = f"{company_name}_full_report_{datetime.datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.pdf"
path = os.path.join(config["report_output_dir"], filename)
with open(path, "wb") as f:
pisa.CreatePDF(html.encode(), dest=f, encoding='utf-8')
logging.info(f"Report generated: {path}")
return path
# --- Telegram Sender ---
def send_telegram(chat_id, pdf_path):
try:
bot.send_document(chat_id=chat_id, document=open(pdf_path, "rb"), caption="Company Security Report")
logging.info(f"Sent report to Telegram chat {chat_id}")
except Exception as e:
logging.error(f"Failed to send Telegram message: {e}")
# --- Main Loop ---
def main():
for company in companies_col.find():
name = company["name"]
domains = company["domains"]
chat_id = company.get("telegram_id")
logging.info(f"Processing company: {name}")
all_scans = {}
for domain in domains:
scan_data = scan_domain(domain)
all_scans[domain] = scan_data
pdf = generate_report(name, all_scans)
if chat_id:
send_telegram(chat_id, pdf)
if __name__ == "__main__":
main()
📦 Sample MongoDB Entry (companies collection)
{
"name": "Acme Corp",
"domains": ["acme.com", "app.acme.com", "api.acme.com"],
"telegram_id": 123456789
}
📌 Summary
This updated version:
- Handles one company with multiple domains
- Generates a unified PDF report per company
- Uses Telegram to deliver reports
- Compares each domain’s scan with its own history
- Uses Jinja2 + xhtml2pdf for styled, professional-looking reports
Let me know if you'd like to add support for email sending, scheduled scans, or Slack notifications!