Please give complete HTML with head and head meta tags for this HTML: "<h1 style="text-align: left;">Automating Network Intelligence: Python Script to Generate PDF Reports in Kali Linux</h1>
<blockquote style="border-left: 5px solid #ff4444; background: #fff0f0; padding: 10px;">
<strong>Ethical Hacking Disclaimer:</strong> This tutorial and script are for educational purposes and authorized security auditing only. Never use these tools on networks or systems without explicit permission from the owner.
</blockquote>
<p>In the world of penetration testing and system administration, documentation is just as important as execution. In Kali Linux, we often interact with the <code>/etc/hosts</code> file to manage local DNS or map target IPs. Today, we’ll build a Python automation tool that audits your host configurations and generates a professional PDF report using network resolution.</p>
<h2>Why Use Python for Kali Linux Reporting?</h2>
<p>While Bash scripts are great for quick tasks, Python offers robust libraries like <b>ReportLab</b> for document generation and <b>Socket</b> for deep network interaction. This script allows you to bridge the gap between raw system data and a shareable, executive-style report.</p>
<h2>The Python Script: Network Host Auditor</h2>
<pre style="background: #282c34; color: #abb2bf; padding: 15px; border-radius: 8px; overflow-x: auto; font-family: 'Courier New', Courier, monospace; line-height: 1.5;"><code>import socket
import os
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
def get_host_info(ip):
"""Attempt to resolve an IP address to a hostname."""
try:
# gethostbyaddr returns (hostname, aliaslist, ipaddrlist)
return socket.gethostbyaddr(ip)[0]
except (socket.herror, socket.gaierror):
return "Unresolved"
def network_scan_to_pdf(output_path='network_scan_report.pdf'):
"""Reads /etc/hosts and generates a formatted PDF report."""
report_data = []
hosts_path = '/etc/hosts'
if not os.path.exists(hosts_path):
print(f"Error: {hosts_path} not found.")
return
try:
with open(hosts_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) >= 2:
ip = parts[0]
declared_name = parts[1]
resolved_name = get_host_info(ip)
report_data.append((ip, declared_name, resolved_name))
except Exception as e:
print(f"Error reading hosts file: {e}")
return
try:
c = canvas.Canvas(output_path, pagesize=letter)
width, height = letter
c.setFont("Helvetica-Bold", 16)
c.drawString(50, height - 50, "Kali Linux Network Scan Report")
c.setFont("Helvetica", 10)
c.drawString(50, height - 70, f"Source: {hosts_path}")
c.line(50, height - 80, width - 50, height - 80)
y = height - 100
c.setFont("Helvetica-Bold", 12)
c.drawString(50, y, "IP Address")
c.drawString(180, y, "Declared Hostname")
c.drawString(350, y, "Network Resolution")
y -= 20
c.setFont("Helvetica", 10)
for ip, dec_name, res_name in report_data:
if y < 50:
c.showPage()
y = height - 50
c.drawString(50, y, ip)
c.drawString(180, y, dec_name)
c.drawString(350, y, res_name)
y -= 15
c.save()
print(f"Success! Report generated at: {os.path.abspath(output_path)}")
except Exception as e:
print(f"Error generating PDF: {e}")
if __name__ == "__main__":
network_scan_to_pdf()</code></pre>
<h2>Deep Dive: How the Script Works</h2>
<h3>1. The Socket Library</h3>
<p>We use <code>socket.gethostbyaddr(ip)</code> to perform a reverse DNS lookup. This is vital because it checks if the IP actually responds with the name declared in your system files, helping you spot spoofed or outdated host entries.</p>
<h3>2. Data Parsing</h3>
<p>The script targets <b>/etc/hosts</b>, the heart of Linux networking. It uses Python's string manipulation to ignore comments (lines starting with #) and extract only the relevant IP and Hostname pairs.</p>
<h3>3. PDF Generation with ReportLab</h3>
<p>Instead of a messy text file, we use <code>canvas.Canvas</code> to draw a structured table. We even included logic to handle page breaks (<code>c.showPage()</code>) if your hosts file is exceptionally long.</p>
<h2>Execution Guide for Kali Linux</h2>
<p>To run this script effectively in your terminal, follow these steps:</p>
<h3>Step 1: Install Dependencies</h3>
<p>Kali Linux usually comes with Python 3, but you'll need the ReportLab library:</p>
<pre style="background: #282c34; color: #abb2bf; padding: 10px; border-radius: 5px;"><code>sudo apt update
pip3 install reportlab</code></pre>
<h3>Step 2: Save and Set Permissions</h3>
<p>Create the file and make it executable:</p>
<pre style="background: #282c34; color: #abb2bf; padding: 10px; border-radius: 5px;"><code>nano host_audit.py
# Paste the code, then press CTRL+O and CTRL+X
chmod +x host_audit.py</code></pre>
<h3>Step 3: Run the Audit</h3>
<p>Since the script reads system files, run it with sudo:</p>
<pre style="background: #282c34; color: #abb2bf; padding: 10px; border-radius: 5px;"><code>sudo python3 host_audit.py</code></pre>
<p>The script will output a file named <b>network_scan_report.pdf</b> in your current directory.</p>"
Gemini said
Here is the complete HTML document, including the <head>, meta tags, and the content you provided. I have also added a basic CSS reset and font styling to ensure the report looks clean and professional.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="description" content="Tutorial on automating network intelligence using Python to generate PDF reports from /etc/hosts in Kali Linux.">
<meta name="keywords" content="Kali Linux, Python, Cybersecurity, Network Auditing, ReportLab, Automation">
<title>Automating Network Intelligence: Python PDF Reporting | Kali Linux</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
line-height: 1.6;
color: #333;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f9f9f9;
}
.container {
background: #ffffff;
padding: 40px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1, h2, h3 {
color: #2c3e50;
}
code {
font-family: 'Courier New', Courier, monospace;
background-color: #f4f4f4;
padding: 2px 4px;
border-radius: 4px;
}
pre code {
background-color: transparent;
padding: 0;
}
strong {
color: #d32f2f;
}
</style>
</head>
<body>
<div class="container">
<h1 style="text-align: left;">Automating Network Intelligence: Python Script to Generate PDF Reports in Kali Linux</h1>
<blockquote style="border-left: 5px solid #ff4444; background: #fff0f0; padding: 10px;">
<strong>Ethical Hacking Disclaimer:</strong> This tutorial and script are for educational purposes and authorized security auditing only. Never use these tools on networks or systems without explicit permission from the owner.
</blockquote>
<p>In the world of penetration testing and system administration, documentation is just as important as execution. In Kali Linux, we often interact with the <code>/etc/hosts</code> file to manage local DNS or map target IPs. Today, we’ll build a Python automation tool that audits your host configurations and generates a professional PDF report using network resolution.</p>
<h2>Why Use Python for Kali Linux Reporting?</h2>
<p>While Bash scripts are great for quick tasks, Python offers robust libraries like <b>ReportLab</b> for document generation and <b>Socket</b> for deep network interaction. This script allows you to bridge the gap between raw system data and a shareable, executive-style report.</p>
<h2>The Python Script: Network Host Auditor</h2>
<pre style="background: #282c34; color: #abb2bf; padding: 15px; border-radius: 8px; overflow-x: auto; font-family: 'Courier New', Courier, monospace; line-height: 1.5;"><code>import socket
import os
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
def get_host_info(ip):
"""Attempt to resolve an IP address to a hostname."""
try:
# gethostbyaddr returns (hostname, aliaslist, ipaddrlist)
return socket.gethostbyaddr(ip)[0]
except (socket.herror, socket.gaierror):
return "Unresolved"
def network_scan_to_pdf(output_path='network_scan_report.pdf'):
"""Reads /etc/hosts and generates a formatted PDF report."""
report_data = []
hosts_path = '/etc/hosts'
if not os.path.exists(hosts_path):
print(f"Error: {hosts_path} not found.")
return
try:
with open(hosts_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) >= 2:
ip = parts[0]
declared_name = parts[1]
resolved_name = get_host_info(ip)
report_data.append((ip, declared_name, resolved_name))
except Exception as e:
print(f"Error reading hosts file: {e}")
return
try:
c = canvas.Canvas(output_path, pagesize=letter)
width, height = letter
c.setFont("Helvetica-Bold", 16)
c.drawString(50, height - 50, "Kali Linux Network Scan Report")
c.setFont("Helvetica", 10)
c.drawString(50, height - 70, f"Source: {hosts_path}")
c.line(50, height - 80, width - 50, height - 80)
y = height - 100
c.setFont("Helvetica-Bold", 12)
c.drawString(50, y, "IP Address")
c.drawString(180, y, "Declared Hostname")
c.drawString(350, y, "Network Resolution")
y -= 20
c.setFont("Helvetica", 10)
for ip, dec_name, res_name in report_data:
if y < 50:
c.showPage()
y = height - 50
c.drawString(50, y, ip)
c.drawString(180, y, dec_name)
c.drawString(350, y, res_name)
y -= 15
c.save()
print(f"Success! Report generated at: {os.path.abspath(output_path)}")
except Exception as e:
print(f"Error generating PDF: {e}")
if __name__ == "__main__":
network_scan_to_pdf()</code></pre>
<h2>Deep Dive: How the Script Works</h2>
<h3>1. The Socket Library</h3>
<p>We use <code>socket.gethostbyaddr(ip)</code> to perform a reverse DNS lookup. This is vital because it checks if the IP actually responds with the name declared in your system files, helping you spot spoofed or outdated host entries.</p>
<h3>2. Data Parsing</h3>
<p>The script targets <b>/etc/hosts</b>, the heart of Linux networking. It uses Python's string manipulation to ignore comments (lines starting with #) and extract only the relevant IP and Hostname pairs.</p>
<h3>3. PDF Generation with ReportLab</h3>
<p>Instead of a messy text file, we use <code>canvas.Canvas</code> to draw a structured table. We even included logic to handle page breaks (<code>c.showPage()</code>) if your hosts file is exceptionally long.</p>
<h2>Execution Guide for Kali Linux</h2>
<p>To run this script effectively in your terminal, follow these steps:</p>
<h3>Step 1: Install Dependencies</h3>
<p>Kali Linux usually comes with Python 3, but you'll need the ReportLab library:</p>
<pre style="background: #282c34; color: #abb2bf; padding: 10px; border-radius: 5px;"><code>sudo apt update
pip3 install reportlab</code></pre>
<h3>Step 2: Save and Set Permissions</h3>
<p>Create the file and make it executable:</p>
<pre style="background: #282c34; color: #abb2bf; padding: 10px; border-radius: 5px;"><code>nano host_audit.py
# Paste the code, then press CTRL+O and CTRL+X
chmod +x host_audit.py</code></pre>
<h3>Step 3: Run the Audit</h3>
<p>Since the script reads system files, run it with sudo:</p>
<pre style="background: #282c34; color: #abb2bf; padding: 10px; border-radius: 5px;"><code>sudo python3 host_audit.py</code></pre>
<p>The script will output a file named <b>network_scan_report.pdf</b> in your current directory.</p>
</div>
</body>
</html>
Would you like me to add a dark mode toggle to this HTML structure?
hash tags for this blogger article
Gemini said
To maximize the visibility of your Kali Linux tutorial on platforms like LinkedIn, Instagram, or X (Twitter), here are the best hashtags categorized by their focus:
🛡️ Cybersecurity & Hacking
#KaliLinux #EthicalHacking #CyberSecurity #PenetrationTesting #InfoSec #RedTeaming #BugBounty #CyberSecurityTraining
🐍 Python & Automation
#PythonProgramming #PythonScripts #Automation #DevSecOps #PythonForBeginners #CodingLife #NetworkAutomation
🐧 Linux & Systems
#Linux #SysAdmin #NetworkSecurity #OpenSource #Kali #Networking #LinuxTips
📊 Professional / Educational
#TechTutorial #CyberSecurityAudit #DataReporting #NetworkIntelligence #LearnToCode #STEM
Suggested Optimized Tag Blocks:
For Instagram/Threads (The "Power Block"):
#KaliLinux #PythonProgramming #EthicalHacking #CyberSecurity #InfoSec #Automation #Linux #PenTesting #Coding #NetworkSecurity #PythonScripts
For LinkedIn (Professional & Focused):
#CyberSecurity #NetworkIntelligence #PythonAutomation #KaliLinux #InformationSecurity #DigitalTransformation #TechTutorials
For X / Twitter (Concise):
#KaliLinux #Python #CyberSecurity #Infosec #Automation #LinuxTips
Pro-Tip for Blogger: When adding labels in your Blogger dashboard, use the most relevant ones like "Kali Linux", "Python", and "Cybersecurity". This helps Google index your article specifically within those technical niches.
Would you like me to write a meta description and SEO-friendly title to go along with these tags?
A SEO friendly title for this blogger article please.
Gemini said
To help your article rank higher on search engines and attract more clicks, I’ve broken these down by "search intent."
🚀 Top Recommendation: The "How-To" Power Title
How to Automate Network Audits in Kali Linux with Python and PDF Reports
Why it works: It uses high-value keywords like "Automate," "Kali Linux," and "Python" while clearly stating the end result (PDF reports).
🛠️ The Technical/Tutorial Approach
Python for Kali Linux: Building a Network Host Auditor & PDF Generator
Why it works: It targets users looking for specific "Python for Kali Linux" tutorials, which is a popular niche search.
💼 The Executive/Professional Approach
Automating Network Intelligence: Generate Professional Audit Reports in Kali Linux
Why it works: It sounds high-level and professional, appealing to SysAdmins and Security Consultants.
⚡ The SEO "Long-Tail" Title (Best for Google Search)
Python Script to Audit /etc/hosts and Generate PDF Reports in Kali Linux
Why it works: It includes the specific file path (
/etc/hosts) that people often search for when looking for networking solutions.
💡 Pro-Tips for your Blogger Title:
Keep it under 60 characters: This ensures the full title shows up in Google search results without being cut off.
Use the H1 tag: Ensure this title is also the main
<h1>in your post (which I included in the HTML code above).URL Permalinks: In Blogger, make sure your "Permalink" matches the title keywords (e.g.,
kali-linux-python-pdf-report.html).
Would you like me to generate a Meta Description (the short 150-character blurb that appears under the title in Google) to finish your SEO setup?
Can you modify this script to include higher network information and port scanning etc?
Gemini said
This is a great evolution of the tool. To step up from simple host auditing to a more "Pro" network scanner, we’ll integrate python-nmap for port discovery and psutil to grab system-level interface details (like MAC addresses and local gateway info).
Updated Script Requirements
You will need to install two additional libraries in your Kali terminal:
sudo apt update
pip3 install python-nmap psutil reportlab
Note: This script requires sudo because nmap needs root privileges for certain types of scans.
The Modified Python Script: Pro-Network Auditor
This version now fetches local interface data and performs a TCP port scan on the hosts it finds.
import socket
import os
import psutil
import nmap
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib import colors
def get_network_interfaces():
"""Get local network interface details using psutil."""
interfaces = []
stats = psutil.net_if_addrs()
for intf, addrs in stats.items():
for addr in addrs:
if addr.family == socket.AF_INET:
interfaces.append({"name": intf, "ip": addr.address, "mask": addr.netmask})
return interfaces
def scan_ports(ip):
"""Perform a quick scan of common ports using Nmap."""
nm = nmap.PortScanner()
try:
# Scanning common ports: 21, 22, 80, 443, 3389
nm.scan(ip, '21,22,80,443,3389', arguments="-T4")
if ip in nm.all_hosts():
open_ports = []
for proto in nm[ip].all_protocols():
lport = nm[ip][proto].keys()
for port in lport:
if nm[ip][proto][port]['state'] == 'open':
open_ports.append(f"{port}({proto})")
return ", ".join(open_ports) if open_ports else "None Found"
except Exception:
pass
return "Scan Failed"
def generate_pro_report(output_path='network_audit_pro.pdf'):
"""Generates a comprehensive network intelligence report."""
hosts_path = '/etc/hosts'
report_data = []
print("[+] Gathering Interface Info...")
interfaces = get_network_interfaces()
print("[+] Reading Hosts and Scanning Ports (This may take a moment)...")
if os.path.exists(hosts_path):
with open(hosts_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'): continue
parts = line.split()
if len(parts) >= 2:
ip = parts[0]
name = parts[1]
ports = scan_ports(ip)
report_data.append((ip, name, ports))
# PDF Creation
c = canvas.Canvas(output_path, pagesize=letter)
width, height = letter
# Title
c.setFont("Helvetica-Bold", 18)
c.drawString(50, height - 50, "Advanced Network Intelligence Report")
# Section 1: Local Interfaces
c.setFont("Helvetica-Bold", 12)
c.drawString(50, height - 80, "1. Local Network Interfaces")
c.setFont("Helvetica", 10)
y = height - 100
for i in interfaces:
c.drawString(60, y, f"Interface: {i['name']} | IP: {i['ip']} | Mask: {i['mask']}")
y -= 15
c.line(50, y - 5, width - 50, y - 5)
y -= 30
# Section 2: Host Audit & Port Scan
c.setFont("Helvetica-Bold", 12)
c.drawString(50, y, "2. Target Host Audit & Port Scanning")
y -= 25
# Table Headers
c.setFont("Helvetica-Bold", 10)
c.drawString(50, y, "IP Address")
c.drawString(160, y, "Hostname")
c.drawString(300, y, "Open Ports (Discovery)")
y -= 5
c.line(50, y, width - 50, y)
y -= 15
c.setFont("Helvetica", 9)
for ip, name, ports in report_data:
if y < 50:
c.showPage()
y = height - 50
c.drawString(50, y, ip)
c.drawString(160, y, name[:20]) # Truncate long names
c.drawString(300, y, ports)
y -= 15
c.save()
print(f"[!] Report saved to {os.path.abspath(output_path)}")
if __name__ == "__main__":
generate_pro_report()
What’s New in This Version:
System Interface Discovery: Uses
psutilto list all active network cards (eth0, wlan0, etc.) and their IP/Subnet masks. This gives context to which network you are actually auditing.Integrated Port Scanner: It doesn't just resolve names anymore. It uses
nmapto probe the target IPs for common services like SSH (22), HTTP (80), and RDP (3389).Cleaned Up PDF Layout: Added section headers and lines to make the "Executive Report" look more structured.
Updated Tags for this "Pro" Version:
#NmapAutomation #NetworkScanning #PythonForHacking #KaliLinuxTools #CybersecurityReporting #NetworkAudit
Would you like me to add a vulnerability check (like checking for outdated service versions) to the port scanning section?
sudo python3 network_scan_and_generate_pdf1Gem1.py
[sudo] password for kali:
Traceback (most recent call last):
File "/home/kali/network_scan_and_generate_pdf1Gem1.py", line 4, in <module>
import nmap
ModuleNotFoundError: No module named 'nmap'
Gemini said
It looks like you've hit a classic Python pitfall! Even if you have Nmap installed on Kali, the Python library (python-nmap) needs to be installed specifically for the environment where you are running the script.
When you run with sudo, it uses the global Python environment. Here is how to fix the ModuleNotFoundError:
1. Fix the Installation
Run this command to install the specific Nmap wrapper for Python globally:
sudo apt update
sudo apt install python3-nmap -y
Alternative (using pip):
If the apt command doesn't work, use:
sudo pip3 install python-nmap --break-system-packages
(Note: Kali recently added the --break-system-packages flag to prevent users from accidentally breaking system tools, but it is necessary for global pip installs.)
2. Complete Final Code
Per your instructions, here is the complete, refined script. I have added a "Safety Check" at the top to give you a helpful error message if the library is still missing.
import socket
import os
import psutil
import sys
# Safety check for the nmap library
try:
import nmap
except ImportError:
print("\n[!] Error: python-nmap not found.")
print("[*] Install it using: sudo apt install python3-nmap")
sys.exit(1)
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib import colors
def get_network_interfaces():
"""Get local network interface details using psutil."""
interfaces = []
stats = psutil.net_if_addrs()
for intf, addrs in stats.items():
for addr in addrs:
if addr.family == socket.AF_INET:
interfaces.append({"name": intf, "ip": addr.address, "mask": addr.netmask})
return interfaces
def scan_ports(ip):
"""Perform a quick scan of common ports using Nmap."""
nm = nmap.PortScanner()
try:
# Scanning common ports: 21 (FTP), 22 (SSH), 80 (HTTP), 443 (HTTPS), 3389 (RDP)
nm.scan(ip, '21,22,80,443,3389', arguments="-T4")
if ip in nm.all_hosts():
open_ports = []
for proto in nm[ip].all_protocols():
lport = nm[ip][proto].keys()
for port in lport:
if nm[ip][proto][port]['state'] == 'open':
open_ports.append(f"{port}/{proto}")
return ", ".join(open_ports) if open_ports else "None Found"
except Exception:
pass
return "Host Down/No Ports"
def generate_pro_report(output_path='network_audit_pro.pdf'):
"""Generates a comprehensive network intelligence report."""
hosts_path = '/etc/hosts'
report_data = []
print("[+] Gathering Local Interface Info...")
interfaces = get_network_interfaces()
print("[+] Reading /etc/hosts and Scanning Ports (This may take a minute)...")
if os.path.exists(hosts_path):
try:
with open(hosts_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'): continue
parts = line.split()
if len(parts) >= 2:
ip = parts[0]
name = parts[1]
print(f" - Scanning {ip} ({name})...")
ports = scan_ports(ip)
report_data.append((ip, name, ports))
except PermissionError:
print("[!] Error: Permission denied reading /etc/hosts. Use sudo.")
return
# PDF Creation
c = canvas.Canvas(output_path, pagesize=letter)
width, height = letter
# Header
c.setFont("Helvetica-Bold", 18)
c.setStrokeColor(colors.red)
c.drawString(50, height - 50, "Kali Linux Advanced Network Audit")
# Section 1: Local Interfaces
c.setFont("Helvetica-Bold", 12)
c.setFillColor(colors.black)
c.drawString(50, height - 85, "1. Local Network Configuration")
c.setFont("Helvetica", 10)
y = height - 105
for i in interfaces:
c.drawString(60, y, f"Interface: {i['name']} | IP: {i['ip']} | Mask: {i['mask']}")
y -= 15
c.line(50, y - 5, width - 50, y - 5)
y -= 35
# Section 2: Host Audit & Port Scan
c.setFont("Helvetica-Bold", 12)
c.drawString(50, y, "2. Targeted Host Audit & Service Discovery")
y -= 25
# Table Headers
c.setFont("Helvetica-Bold", 10)
c.setFillColor(colors.darkblue)
c.drawString(50, y, "IP Address")
c.drawString(180, y, "Hostname")
c.drawString(350, y, "Open Ports")
y -= 5
c.setStrokeColor(colors.black)
c.line(50, y, width - 50, y)
y -= 20
# Data Rows
c.setFont("Helvetica", 10)
c.setFillColor(colors.black)
for ip, name, ports in report_data:
if y < 50:
c.showPage()
y = height - 50
c.drawString(50, y, ip)
c.drawString(180, y, name)
c.drawString(350, y, ports)
y -= 18
c.save()
print(f"\n[!] Success! Pro Report generated at: {os.path.abspath(output_path)}")
if __name__ == "__main__":
# Ensure script is run as root for Nmap functionality
if os.geteuid() != 0:
print("[!] Warning: This script works best with sudo for Nmap scanning.")
generate_pro_report()
Next Step
After running the installation command above, try running the script again with sudo python3 network_scan_and_generate_pdf1Gem1.py.
Would you like me to add a "Service Banner" grabber so the report shows which versions of software (like Apache or OpenSSH) are running on those ports?
yes
Gemini said
To add service banner grabbing (version detection), we need to modify the Nmap scan arguments to include -sV (Version Intensity). This tells Nmap to probe the open ports to determine what software and version are actually running (e.g., "Apache 2.4.58" instead of just "HTTP").
🛠️ Prerequisites
This version still requires python-nmap. If you haven't already, ensure it's installed:
sudo apt install python3-nmap -y
The Final Complete Code: Advanced Auditor with Service Versioning
This script now probes ports and extracts the Vendor and Version information for a truly professional security report.
import socket
import os
import psutil
import sys
# Safety check for the nmap library
try:
import nmap
except ImportError:
print("\n[!] Error: python-nmap not found.")
print("[*] Install it using: sudo apt install python3-nmap")
sys.exit(1)
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib import colors
def get_network_interfaces():
"""Get local network interface details using psutil."""
interfaces = []
stats = psutil.net_if_addrs()
for intf, addrs in stats.items():
for addr in addrs:
if addr.family == socket.AF_INET:
interfaces.append({"name": intf, "ip": addr.address, "mask": addr.netmask})
return interfaces
def scan_ports_with_versions(ip):
"""Scan ports and grab service banners/versions using Nmap."""
nm = nmap.PortScanner()
try:
# -T4 for speed, -sV for Service/Version detection
print(f" - Probing services on {ip}...")
nm.scan(ip, '21,22,80,443,3389,8080', arguments="-T4 -sV")
if ip in nm.all_hosts():
service_details = []
for proto in nm[ip].all_protocols():
lport = nm[ip][proto].keys()
for port in lport:
state = nm[ip][proto][port]['state']
if state == 'open':
name = nm[ip][proto][port]['name']
product = nm[ip][proto][port]['product']
version = nm[ip][proto][port]['version']
# Format: 80/tcp (http: Apache 2.4.x)
info = f"{port}/{proto} ({name}: {product} {version})".strip(": ")
service_details.append(info)
return service_details if service_details else ["No open services"]
except Exception as e:
return [f"Scan Error: {str(e)}"]
return ["Host unreachable"]
def generate_pro_report(output_path='network_audit_v2.pdf'):
"""Generates a comprehensive network intelligence report with service versions."""
hosts_path = '/etc/hosts'
report_data = []
print("[+] Gathering Local Interface Info...")
interfaces = get_network_interfaces()
print("[+] Reading /etc/hosts and Identifying Services (Be patient, versioning takes time)...")
if os.path.exists(hosts_path):
try:
with open(hosts_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'): continue
parts = line.split()
if len(parts) >= 2:
ip = parts[0]
hostname = parts[1]
services = scan_ports_with_versions(ip)
report_data.append({"ip": ip, "host": hostname, "services": services})
except PermissionError:
print("[!] Error: Permission denied reading /etc/hosts. Use sudo.")
return
# PDF Creation
c = canvas.Canvas(output_path, pagesize=letter)
width, height = letter
# Header
c.setFont("Helvetica-Bold", 18)
c.setFillColor(colors.darkred)
c.drawString(50, height - 50, "Network Intelligence & Service Audit")
# Section 1: Local Interfaces
c.setFont("Helvetica-Bold", 12)
c.setFillColor(colors.black)
c.drawString(50, height - 85, "1. Source Interface Configuration")
c.setFont("Helvetica", 10)
y = height - 105
for i in interfaces:
c.drawString(60, y, f"Interface: {i['name']} | IP: {i['ip']} | Mask: {i['mask']}")
y -= 15
c.setStrokeColor(colors.lightgrey)
c.line(50, y - 5, width - 50, y - 5)
y -= 35
# Section 2: Host Audit
c.setFont("Helvetica-Bold", 12)
c.drawString(50, y, "2. Target Audit: Service Banner Discovery")
y -= 25
# Data Rows
for entry in report_data:
# Check for page overflow
if y < 100:
c.showPage()
y = height - 50
# Host Header
c.setFont("Helvetica-Bold", 11)
c.setFillColor(colors.blue)
c.drawString(50, y, f"Target: {entry['host']} ({entry['ip']})")
y -= 18
# Service List
c.setFont("Helvetica", 9)
c.setFillColor(colors.black)
for service in entry['services']:
c.drawString(70, y, f"• {service}")
y -= 14
y -= 10 # Extra spacing between hosts
c.save()
print(f"\n[!] Success! Advanced Report generated at: {os.path.abspath(output_path)}")
if __name__ == "__main__":
if os.geteuid() != 0:
print("[!] ERROR: Service versioning requires root privileges. Please run with sudo.")
sys.exit(1)
generate_pro_report()
Key Improvements:
Banner Grabbing: Instead of just showing "80/tcp", it now returns results like
80/tcp (http: Apache 2.4.58).Increased Coverage: Added port
8080to the scan, as it's common for development servers in Kali environments.Visual Layout: Changed the PDF structure from a table to a Target-List format. This allows more room for long service version strings which usually don't fit in narrow table columns.
Root Enforcement: The script now checks for
sudoimmediately, as banner grabbing (-sV) is unreliable without raw socket access.
Would you like me to add a simple "Vulnerability Check" that flags services if they are running known insecure versions (like outdated OpenSSH)?
yes
Gemini said
To implement vulnerability checking, we will use Nmap Scripting Engine (NSE). Specifically, we'll use the vulners script, which is a famous NSE script that cross-references service versions against a database of known CVEs (Common Vulnerabilities and Exposures).
🛠️ Pre-requisites
The Nmap Library:
sudo apt install python3-nmap -yThe Vulners Script: Kali usually has this, but ensure your Nmap scripts are up to date:
Bash
sudo nmap --script-updatedb
The Final Complete Code: Advanced Auditor with CVE Vulnerability Mapping
This version performs a version scan AND runs a lightweight vulnerability script, highlighting potential risks in the PDF.
import socket
import os
import psutil
import sys
# Safety check for the nmap library
try:
import nmap
except ImportError:
print("\n[!] Error: python-nmap not found.")
print("[*] Install it using: sudo apt install python3-nmap")
sys.exit(1)
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib import colors
def get_network_interfaces():
"""Get local network interface details using psutil."""
interfaces = []
stats = psutil.net_if_addrs()
for intf, addrs in stats.items():
for addr in addrs:
if addr.family == socket.AF_INET:
interfaces.append({"name": intf, "ip": addr.address, "mask": addr.netmask})
return interfaces
def scan_with_vulnerabilities(ip):
"""Scan ports, grab versions, and check for CVEs using Nmap NSE."""
nm = nmap.PortScanner()
try:
print(f" - Auditing {ip} for vulnerabilities (be patient)...")
# -sV: Version detection
# --script=vulners: Check against CVE database
nm.scan(ip, '21,22,80,443,3389,8080', arguments="-T4 -sV --script=vulners")
if ip in nm.all_hosts():
host_results = []
for proto in nm[ip].all_protocols():
ports = nm[ip][proto].keys()
for port in ports:
service = nm[ip][proto][port]
p_name = service['name']
p_prod = service['product']
p_ver = service['version']
# Extract script output (CVEs) if found
vulns = ""
if 'script' in service and 'vulners' in service['script']:
# We grab the first few lines of the vulnerability report
vulns = service['script']['vulners'].split('\n')[1:4]
vulns = " | CVEs detected!" if vulns else ""
info = f"{port}/{proto} ({p_name}: {p_prod} {p_ver}){vulns}"
host_results.append(info)
return host_results if host_results else ["No services found"]
except Exception as e:
return [f"Scan Error: {str(e)}"]
return ["Host unreachable"]
def generate_vulnerability_report(output_path='network_audit_v3_vuln.pdf'):
"""Generates a detailed audit report including service versions and CVE flags."""
hosts_path = '/etc/hosts'
report_data = []
print("[+] Identifying local network interfaces...")
interfaces = get_network_interfaces()
print("[+] Initializing Deep Audit via /etc/hosts...")
if os.path.exists(hosts_path):
try:
with open(hosts_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'): continue
parts = line.split()
if len(parts) >= 2:
ip, hostname = parts[0], parts[1]
findings = scan_with_vulnerabilities(ip)
report_data.append({"ip": ip, "host": hostname, "findings": findings})
except PermissionError:
print("[!] Error: Root privileges required.")
return
# PDF Generation
c = canvas.Canvas(output_path, pagesize=letter)
width, height = letter
# Title Header
c.setFont("Helvetica-Bold", 18)
c.setFillColor(colors.black)
c.drawString(50, height - 50, "Security Audit: Network Intelligence Report")
c.setFont("Helvetica", 10)
c.setFillColor(colors.gray)
c.drawString(50, height - 65, "Generated via Kali Linux Python Auditor (NSE Vulners Integrated)")
# Section 1: Interfaces
c.setStrokeColor(colors.black)
c.line(50, height - 75, width - 50, height - 75)
c.setFont("Helvetica-Bold", 12)
c.setFillColor(colors.black)
c.drawString(50, height - 95, "1. Local Network Environment")
y = height - 115
c.setFont("Helvetica", 9)
for i in interfaces:
c.drawString(60, y, f"INTF: {i['name']} | IP: {i['ip']} | MASK: {i['mask']}")
y -= 14
y -= 20
c.setFont("Helvetica-Bold", 12)
c.drawString(50, y, "2. Targeted Vulnerability Assessment")
y -= 25
# Section 2: Host Audit Findings
for host in report_data:
if y < 100:
c.showPage()
y = height - 50
c.setFont("Helvetica-Bold", 11)
c.setFillColor(colors.darkblue)
c.drawString(50, y, f"TARGET: {host['host']} ({host['ip']})")
y -= 18
c.setFont("Helvetica", 9)
for item in host['findings']:
if "CVEs" in item:
c.setFillColor(colors.red) # Highlight vulnerabilities in red
else:
c.setFillColor(colors.black)
c.drawString(70, y, f"• {item}")
y -= 14
y -= 12 # Gap between hosts
c.save()
print(f"\n[!] Success! Final Vulnerability Report: {os.path.abspath(output_path)}")
if __name__ == "__main__":
if os.geteuid() != 0:
print("[!] ERROR: Vulnerability scanning requires root (sudo).")
sys.exit(1)
generate_vulnerability_report()
What makes this "Final"?
NSE Integration: It uses the
vulnersscript to check if the version of software found (like an old version of SSH) has known public exploits.Visual Alerting: In the PDF report, any line that contains detected vulnerabilities is automatically colored RED to draw the attention of the auditor.
Comprehensive Output: It balances network information, service identification, and threat intelligence in one document.
Next Step
Run it with: sudo python3 your_filename.py.
Would you like me to add an "Action Plan" section to the PDF that suggests common remediation steps for found vulnerabilities?
I unknowingly modified a scheduled completed blog post witha new one how can I get it back?
Gemini said
That sinking feeling is the worst, but don't panic! Since Blogger doesn't have a "trash bin" for specific text edits or a built-in "Version History" like Google Docs, we have to get a bit creative to recover your work.
Here is your recovery checklist, ranked from easiest to "last resort."
1. The "Undo" Shortcut (If the tab is still open)
If you haven't closed the browser tab where you made the mistake:
Click inside the post editor and press Ctrl + Z (Windows/Linux) or Cmd + Z (Mac) repeatedly.
Blogger’s editor cache sometimes holds a surprising amount of undo history.
2. Check Browser Cache / Offline Storage
If you previously viewed the post in its completed state on your computer:
Disconnect your internet (to prevent the browser from refreshing the page).
Go to your browser history and try to open the URL of the post.
Sometimes, the browser will load the "cached" version of the page even if the server has been updated. If it loads, copy-paste the text immediately.
3. Use Google Search Console / Cache
If the post was indexed by Google (even briefly), Google might have a "snapshot" of the old version.
Search Google for the exact title of your post or the URL.
Click the three vertical dots next to the search result.
Look for a button that says "Cached". This will show you the post exactly as it looked the last time Google crawled it.
4. Use the Wayback Machine (Internet Archive)
If the post was live for a while before you modified it:
Go to web.archive.org.
Paste the URL of your blog post.
If a "snapshot" exists, you can click a date on the calendar to see the old content.
5. Check your RSS Feed / Email Subscriptions
RSS Feed: If you use a feed reader (like Feedly) or have an active RSS feed, the old content might still be sitting in the feed XML. Check
yourblogname.blogspot.com/feeds/posts/default.Email Notifications: If you have "Follow by Email" set up, check your own inbox. You might have received a notification containing the original text when the post was first "published" or scheduled.
6. The "Draft" Hack
Sometimes Blogger saves a "draft" version of a post in your local browser storage.
Open Blogger in a different browser or a private/incognito window.
Sometimes (though rarely), the "autosave" on one device hasn't synced with the "autosave" on another yet.
How to Prevent This in the Future
Compose in Google Docs: It has a "Version History" feature that lets you go back to any second in time.
"Revert to Draft": If you want to change a post significantly, use the "Revert to Draft" button first, or better yet, Duplicate the post by copying the HTML into a new post.
Would you like me to help you draft a "Recovery Post" or reconstruct the content based on the Python script and topics we discussed earlier?
#KaliLinux #PythonProgramming #CyberSecurity #EthicalHacking #Nmap #InfoSec #Automation #PenetrationTesting #NetworkSecurity #PythonScripts #DevSecOps
blogger labels, title, post 150 word description, custom permalink (SEO friendly) and hashtags for this entire conversation for blog post in blogger
Gemini said
To wrap up your project, here is the complete SEO package for your Blogger post. This is designed to rank for both Python automation and Kali Linux security auditing.
🏷️ SEO Metadata Details
Blogger Title: Automating Network Audits in Kali Linux: Python, Nmap, and PDF Reporting
150-Word Post Description (Search Snippet):
Learn how to bridge the gap between raw network data and professional documentation using Python in Kali Linux. This comprehensive guide walks you through building a powerful network intelligence tool that audits /etc/hosts, performs deep port scanning, and utilizes the Nmap Scripting Engine (NSE) for service version detection and vulnerability mapping. We move beyond basic scripting to generate executive-style PDF reports using the ReportLab library, featuring color-coded security alerts for detected CVEs. Whether you are a penetration tester looking to automate reporting or a system administrator auditing local host configurations, this tutorial provides the complete code to transform terminal output into shareable, high-impact security documents. Perfect for ethical hackers wanting to enhance their automation toolkit with Python-Nmap integration and professional reporting workflows.
Custom Permalink (SEO Friendly):
kali-linux-python-network-audit-pdf-report
(In Blogger: Settings > Permalink > Custom Permalink)
Blogger Labels:
Kali Linux, Python, Cybersecurity, Network Auditing, Nmap, Automation, Ethical Hacking, ReportLab
#️⃣ Hashtag Strategy
For Social Media (LinkedIn/X/Instagram):
#KaliLinux #PythonProgramming #CyberSecurity #EthicalHacking #Nmap #InfoSec #Automation #PenetrationTesting #NetworkSecurity #PythonScripts #DevSecOps
📋 Final Content Structure (Summary)
If you are reconstructing your post, here is the logical flow we developed:
Introduction: Importance of documentation in penetration testing.
The Environment: Using
/etc/hostsas a baseline for network intelligence.The Evolution: * Phase 1: Simple host resolution to PDF.
Phase 2: Integrating
psutilfor interface info andnmapfor port scanning.Phase 3: Adding service banner grabbing (version detection).
Phase 4: Implementing the
vulnersNSE script for CVE mapping.
The Complete Final Code: (Use the script from the previous response).
Execution Guide:
sudo apt install python3-nmapand running withsudo.
Would you like me to generate a specific "Table of Contents" or a "Conclusion" paragraph to finish the post text?
yes
Gemini said
Here is a structured Table of Contents and a professional Conclusion to give your blog post a polished, authoritative finish.
📑 Table of Contents
The Documentation Gap: Why automated reporting is essential for Red Teams.
Prerequisites: Setting up your Kali environment and Nmap libraries.
Step 1: Mapping Local Intelligence: Parsing the
/etc/hostsfile.Step 2: Deep Port Scanning: Using Python-Nmap for service discovery.
Step 3: Service Banner Grabbing: Identifying software versions and vendors.
Step 4: Vulnerability Mapping: Integrating NSE
vulnersfor CVE detection.The Master Script: Complete code for the Network Intelligence Auditor.
Generating the Report: How to interpret the automated PDF results.
Remediation & Best Practices: Next steps after the audit.
🏁 Conclusion
"In the fast-paced environment of cybersecurity, the difference between a 'hacker' and a 'professional security consultant' is the quality of the documentation provided. By automating the transition from raw network data to a structured, vulnerability-aware PDF report, you not only save hours of manual entry but also ensure that no critical service is overlooked.
This Python-based auditor demonstrates the power of Kali Linux when combined with flexible automation scripts. It transforms a simple list of IP addresses into a roadmap for remediation. As you continue to build your toolkit, remember that tools are only as effective as the insights they provide. Use this script to stay organized, stay professional, and most importantly, stay secure."
💡 Quick Recap of Settings for Blogger:
Title:
Automating Network Audits in Kali Linux: Python, Nmap, and PDF ReportingPermalink:
kali-linux-python-network-audit-pdf-reportSearch Description: (Paste the 150-word description provided previously).
Final Script: Ensure you use the version with the CVE Vulnerability Mapping to give your readers the most value.
Would you like me to generate a set of "Frequently Asked Questions" (FAQs) to add to the bottom of the post for extra SEO value?
You said
yes
Gemini said
Adding an FAQ section is a brilliant SEO move. It helps your post capture "People Also Ask" snippets on Google and targets specific long-tail search queries.
❓ Frequently Asked Questions (FAQ)
1. Why does this script require sudo/root privileges?
The script uses Nmap for service version detection and vulnerability scanning. Nmap requires root privileges to send raw network packets and perform "stealth" (SYN) scans. Without sudo, the script may fail to identify open ports or grab service banners accurately.
2. Can I run this script on Windows or macOS instead of Kali?
Yes, but you must have Nmap installed on your system and added to your PATH. You would also need to change the hosts_path variable in the script from /etc/hosts to the appropriate path for your OS (e.g., C:\Windows\System32\drivers\etc\hosts for Windows).
3. Is the 'vulners' script safe to run on production networks?
The vulners NSE script is a "safe" script; it doesn't attempt to exploit the vulnerabilities it finds—it simply cross-references version numbers against a database. However, always ensure you have explicit authorization before scanning any network.
4. How do I add more ports to the scan?
In the scan_with_vulnerabilities function, find the line nm.scan(ip, '21,22,80,443,3389,8080', ...). You can add any port numbers you like to that comma-separated string, such as 3306 (MySQL) or 5432 (PostgreSQL).
5. Why is my PDF report showing "Unresolved" or "None Found"?
This usually means the target IP is either down, blocking ICMP/ping requests, or filtering the ports being scanned. You can try adjusting the Nmap arguments to -Pn (treat all hosts as online) if you are scanning a hardened environment.
🚀 Final Checklist Before You Hit "Publish"
[ ] Images: Did you include a screenshot of the Kali terminal running the script or a preview of the generated PDF? (Search engines love original images).
[ ] Formatting: Use H2 tags for the section headers and H3 for the FAQ questions.
[ ] Links: Consider adding a link to the official Nmap.org and ReportLab documentation.
Would you like me to generate a "How to Use" summary in Markdown format that you can easily copy and paste into a README file for your GitHub repository?
No comments:
Post a Comment