Automating Nessus Scanning After Installation and result reporting after scanning

πŸ”Ή Automating Nessus Scanning After Installation πŸš€

Once Nessus is installed, we can automate vulnerability scans using the Nessus CLI or API.


βœ… Method 1: Automate Nessus Scan Using CLI (Linux & Windows)

  1. Add a new scan
  2. Start the scan automatically
  3. Retrieve the scan results

πŸ“Œ Steps to Use

  1. Run this script after installing Nessus
  2. It will scan a specific target and fetch the report

πŸš€ Linux Automation Script (automate_scan.sh)

#!/bin/bash

# Set Nessus Variables
NESSUS_URL="https://localhost:8834"
USERNAME="admin"
PASSWORD="YourPassword"
SCAN_NAME="Automated Scan"
TARGET="192.168.1.1"

# Authenticate and get a session token
TOKEN=$(curl -s -k -X POST -H "Content-Type: application/json" -d "{\"username\":\"$USERNAME\", \"password\":\"$PASSWORD\"}" $NESSUS_URL/session | jq -r '.token')

# Create a New Scan
SCAN_ID=$(curl -s -k -X POST -H "X-Cookie: token=$TOKEN" -H "Content-Type: application/json" \
    -d "{\"uuid\":\"ab4bacd2-f1b2-4397-9971-7223db21f1e6\",\"settings\":{\"name\":\"$SCAN_NAME\",\"text_targets\":\"$TARGET\",\"scanner_id\":\"1\",\"policy_id\":\"1\"}}" \
    $NESSUS_URL/scans | jq -r '.scan.id')

# Start the Scan
curl -s -k -X POST -H "X-Cookie: token=$TOKEN" $NESSUS_URL/scans/$SCAN_ID/launch

echo "Scan Started! Check results in Nessus UI."

πŸš€ Windows PowerShell Automation Script (automate_scan.ps1)

# Set Nessus Variables
$nessusURL = "https://localhost:8834"
$username = "admin"
$password = "YourPassword"
$scanName = "Automated Scan"
$target = "192.168.1.1"

# Authenticate and Get a Session Token
$authData = @{username=$username; password=$password} | ConvertTo-Json
$tokenResponse = Invoke-RestMethod -Uri "$nessusURL/session" -Method Post -Body $authData -ContentType "application/json" -SkipCertificateCheck
$token = $tokenResponse.token

# Create a New Scan
$scanData = @{uuid="ab4bacd2-f1b2-4397-9971-7223db21f1e6"; settings=@{name=$scanName; text_targets=$target; scanner_id="1"; policy_id="1"}} | ConvertTo-Json -Depth 3
$scanResponse = Invoke-RestMethod -Uri "$nessusURL/scans" -Method Post -Headers @{"X-Cookie"="token=$token"} -Body $scanData -ContentType "application/json" -SkipCertificateCheck
$scanId = $scanResponse.scan.id

# Start the Scan
Invoke-RestMethod -Uri "$nessusURL/scans/$scanId/launch" -Method Post -Headers @{"X-Cookie"="token=$token"} -SkipCertificateCheck

Write-Host "Scan Started! Check results in Nessus UI."

πŸ’‘ How It Works

βœ… Logs in to Nessus API
βœ… Creates a scan targeting an IP/network
βœ… Starts the scan automatically
βœ… Scan results can be checked in the Nessus Web UI

πŸ”Ή Automating Nessus Scan Result Reporting πŸš€

Once Nessus completes the scan, we can fetch the results automatically and save them as a PDF, CSV, or JSON report.


βœ… Method 1: Automate Scan Results Using Linux Bash Script

πŸ“Œ Steps to Use

  1. Run this script after starting the scan
  2. It will wait for the scan to complete, then download the report

πŸš€ Linux Automation Script (fetch_nessus_report.sh)

#!/bin/bash

# Nessus API Credentials
NESSUS_URL="https://localhost:8834"
USERNAME="admin"
PASSWORD="YourPassword"
REPORT_FORMAT="pdf"  # Change to csv or json if needed
OUTPUT_FILE="scan_report.$REPORT_FORMAT"

# Authenticate and get session token
TOKEN=$(curl -s -k -X POST -H "Content-Type: application/json" -d "{\"username\":\"$USERNAME\", \"password\":\"$PASSWORD\"}" $NESSUS_URL/session | jq -r '.token')

# Get the last scan ID
SCAN_ID=$(curl -s -k -H "X-Cookie: token=$TOKEN" $NESSUS_URL/scans | jq -r '.scans | sort_by(.creation_date) | last | .id')

# Wait until the scan completes
while true; do
    STATUS=$(curl -s -k -H "X-Cookie: token=$TOKEN" $NESSUS_URL/scans/$SCAN_ID | jq -r '.info.status')
    echo "Scan Status: $STATUS"
    
    if [ "$STATUS" == "completed" ]; then
        break
    fi
    sleep 10
done

# Request report generation
REPORT_ID=$(curl -s -k -X POST -H "X-Cookie: token=$TOKEN" -H "Content-Type: application/json" \
    -d "{\"format\":\"$REPORT_FORMAT\"}" \
    $NESSUS_URL/scans/$SCAN_ID/export | jq -r '.file')

# Wait for the report to be ready
while true; do
    REPORT_STATUS=$(curl -s -k -H "X-Cookie: token=$TOKEN" $NESSUS_URL/scans/$SCAN_ID/export/$REPORT_ID/status | jq -r '.status')
    echo "Report Status: $REPORT_STATUS"
    
    if [ "$REPORT_STATUS" == "ready" ]; then
        break
    fi
    sleep 5
done

# Download the report
curl -s -k -H "X-Cookie: token=$TOKEN" $NESSUS_URL/scans/$SCAN_ID/export/$REPORT_ID/download --output $OUTPUT_FILE

echo "Scan report downloaded: $OUTPUT_FILE"

βœ… Method 2: Automate Scan Results Using Windows PowerShell

πŸš€ PowerShell Script (fetch_nessus_report.ps1)

# Nessus API Credentials
$nessusURL = "https://localhost:8834"
$username = "admin"
$password = "YourPassword"
$reportFormat = "pdf"  # Change to "csv" or "json" if needed
$outputFile = "C:\Reports\scan_report.$reportFormat"

# Authenticate and Get Token
$authData = @{username=$username; password=$password} | ConvertTo-Json
$tokenResponse = Invoke-RestMethod -Uri "$nessusURL/session" -Method Post -Body $authData -ContentType "application/json" -SkipCertificateCheck
$token = $tokenResponse.token

# Get the Last Scan ID
$scans = Invoke-RestMethod -Uri "$nessusURL/scans" -Headers @{"X-Cookie"="token=$token"} -SkipCertificateCheck
$scanId = ($scans.scans | Sort-Object -Property creation_date | Select-Object -Last 1).id

# Wait for Scan Completion
do {
    $scanStatus = Invoke-RestMethod -Uri "$nessusURL/scans/$scanId" -Headers @{"X-Cookie"="token=$token"} -SkipCertificateCheck
    Write-Host "Scan Status: $($scanStatus.info.status)"
    Start-Sleep -Seconds 10
} while ($scanStatus.info.status -ne "completed")

# Request Report Generation
$reportData = @{format=$reportFormat} | ConvertTo-Json
$reportResponse = Invoke-RestMethod -Uri "$nessusURL/scans/$scanId/export" -Headers @{"X-Cookie"="token=$token"} -Method Post -Body $reportData -ContentType "application/json" -SkipCertificateCheck
$reportId = $reportResponse.file

# Wait for Report to be Ready
do {
    $reportStatus = Invoke-RestMethod -Uri "$nessusURL/scans/$scanId/export/$reportId/status" -Headers @{"X-Cookie"="token=$token"} -SkipCertificateCheck
    Write-Host "Report Status: $($reportStatus.status)"
    Start-Sleep -Seconds 5
} while ($reportStatus.status -ne "ready")

# Download the Report
Invoke-RestMethod -Uri "$nessusURL/scans/$scanId/export/$reportId/download" -Headers @{"X-Cookie"="token=$token"} -OutFile $outputFile -SkipCertificateCheck

Write-Host "Scan report downloaded: $outputFile"

πŸ’‘ What This Automation Does

βœ… Waits for scan completion
βœ… Generates a report in PDF, CSV, or JSON format
βœ… Downloads the report automatically
βœ… Works on both Linux & Windows

Now send the email with the report after it’s generated πŸ“©πŸš€

πŸ”Ή Automating Nessus Report Email Notification πŸš€

Now that we’ve automated Nessus scanning and report generation, we can send the scan report via email using Linux (sendmail/SMTP) and Windows (PowerShell SMTP).


βœ… Method 1: Send Report via Email (Linux)

This script will email the Nessus report after it is generated.

πŸ“Œ Steps to Use

  1. Install sendmail (if not installed): sudo apt install sendmail -y # For Ubuntu/Debian sudo yum install sendmail -y # For RHEL/CentOS
  2. Configure SMTP in /etc/mail.rc or use an SMTP relay (like Gmail, AWS SES).
  3. Run this script after fetching the Nessus report.

πŸš€ Linux Script (send_nessus_report.sh)

#!/bin/bash

# Email Configurations
TO_EMAIL="recipient@example.com"
FROM_EMAIL="your-email@example.com"
SMTP_SERVER="smtp.example.com"
SMTP_USER="your-email@example.com"
SMTP_PASS="your-password"
SUBJECT="Nessus Scan Report"
BODY="Hello,\n\nPlease find the attached Nessus scan report.\n\nBest Regards."

# Path to Report (Make sure it exists)
REPORT_PATH="scan_report.pdf"

# Send Email with Attachment using sendmail
(
echo "From: $FROM_EMAIL"
echo "To: $TO_EMAIL"
echo "Subject: $SUBJECT"
echo "MIME-Version: 1.0"
echo "Content-Type: multipart/mixed; boundary=\"boundary123\""
echo
echo "--boundary123"
echo "Content-Type: text/plain"
echo
echo "$BODY"
echo "--boundary123"
echo "Content-Type: application/pdf; name=$(basename $REPORT_PATH)"
echo "Content-Disposition: attachment; filename=$(basename $REPORT_PATH)"
echo "Content-Transfer-Encoding: base64"
echo
base64 "$REPORT_PATH"
echo "--boundary123--"
) | sendmail -t

echo "Email sent to $TO_EMAIL with Nessus scan report."

βœ… Method 2: Send Report via Email (Windows PowerShell)

This script will email the Nessus scan report via PowerShell using an SMTP server.

πŸ“Œ Steps to Use

  1. Modify SMTP settings (Use Gmail, Outlook, AWS SES, or your SMTP server).
  2. Run this script after fetching the Nessus report.

πŸš€ Windows PowerShell Script (send_nessus_report.ps1)

# Email Configurations
$toEmail = "recipient@example.com"
$fromEmail = "your-email@example.com"
$smtpServer = "smtp.example.com"
$smtpUser = "your-email@example.com"
$smtpPass = "your-password"
$subject = "Nessus Scan Report"
$body = "Hello,`n`nPlease find the attached Nessus scan report.`n`nBest Regards."

# Path to Report (Make sure it exists)
$reportPath = "C:\Reports\scan_report.pdf"

# Create Email Message
$mailMessage = New-Object System.Net.Mail.MailMessage
$mailMessage.From = $fromEmail
$mailMessage.To.Add($toEmail)
$mailMessage.Subject = $subject
$mailMessage.Body = $body
$mailMessage.Attachments.Add($reportPath)

# Configure SMTP Client
$smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer, 587)
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = New-Object System.Net.NetworkCredential($smtpUser, $smtpPass)

# Send Email
$smtpClient.Send($mailMessage)

Write-Host "Email sent to $toEmail with Nessus scan report."

πŸ’‘ What This Automation Does

βœ… Emails Nessus scan report automatically
βœ… Supports Gmail, Outlook, AWS SES, or any SMTP server
βœ… Sends attachments (PDF, CSV, JSON)
βœ… Works on both Linux & Windows

Now let’s schedule this automation for regular scansβ°πŸš€

πŸ”Ή Automating Nessus Scan, Report Generation, and Email on a Schedule β°πŸš€

Now, let’s schedule this entire process (scan β†’ report β†’ email) at regular intervals using:
βœ… Linux: Cron Jobs
βœ… Windows: Task Scheduler


βœ… Method 1: Automate Nessus Scan & Report on a Schedule (Linux – Cron Job)

We will set up a cron job to run daily at 2 AM.

πŸ“Œ Steps to Set Up

  1. Ensure the scripts exist (automate_scan.sh, fetch_nessus_report.sh, send_nessus_report.sh).
  2. Make scripts executable: chmod +x automate_scan.sh fetch_nessus_report.sh send_nessus_report.sh
  3. Open Crontab: crontab -e
  4. Add this cron job to schedule daily scans at 2 AM:0 2 * * * /path/to/automate_scan.sh && sleep 3600 && /path/to/fetch_nessus_report.sh && /path/to/send_nessus_report.shExplanation:
    • 0 2 * * * β†’ Runs at 2:00 AM daily
    • sleep 3600 β†’ Waits 1 hour for the scan to complete
    • Runs scan β†’ waits β†’ fetches report β†’ sends email

πŸ“Œ Check Logs
To verify cron execution:

cat /var/log/syslog | grep CRON

βœ… Method 2: Automate Nessus Scan & Report on a Schedule (Windows – Task Scheduler)

We will schedule a PowerShell task to run daily at 2 AM.

πŸ“Œ Steps to Set Up

  1. Ensure the scripts exist (automate_scan.ps1, fetch_nessus_report.ps1, send_nessus_report.ps1).
  2. Open Task Scheduler:
    • Press Win + R, type taskschd.msc, and press Enter.
  3. Create a New Task:
    • Click Action β†’ Create Basic Task
    • Name: Automate Nessus Scan
    • Trigger: Daily at 2:00 AM
    • Action: Start a Program
  4. Command to Run: powershell.exe -ExecutionPolicy Bypass -File "C:\path\to\automate_scan.ps1"
  5. Schedule the Follow-Up Scripts:
    • After automate_scan.ps1, add another task for fetch_nessus_report.ps1 (scheduled 1 hour later).
    • Finally, schedule send_nessus_report.ps1 5 minutes after fetching the report.

πŸ’‘ Summary of the Full Automation

βœ… Scan starts daily at 2 AM
βœ… Report is generated automatically
βœ… Email is sent with the scan report
βœ… Scheduled using Cron (Linux) or Task Scheduler (Windows)

Would you like to log scan results in a database for analysis? πŸ“ŠπŸš€

πŸ”Ή Logging Nessus Scan Results into a Database for Analysis πŸ“ŠπŸš€

To analyze historical Nessus scan results, we can store them in a database like MySQL or PostgreSQL.


βœ… Step 1: Set Up a Database (MySQL/PostgreSQL)

πŸ“Œ Install MySQL (Linux)

sudo apt update && sudo apt install mysql-server -y  # Ubuntu/Debian
sudo systemctl start mysql
sudo systemctl enable mysql

Create Database & Table

CREATE DATABASE nessus_scans;
USE nessus_scans;

CREATE TABLE scan_results (
    id INT AUTO_INCREMENT PRIMARY KEY,
    scan_id VARCHAR(255),
    target VARCHAR(255),
    risk VARCHAR(50),
    description TEXT,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

βœ… Step 2: Extract Data from Nessus Report

We will use jq (for JSON) or csvkit (for CSV) to extract useful scan details.

πŸ“Œ Convert JSON Report to Structured Data (Linux)

jq -r '.vulnerabilities[] | "\(.id),\(.plugin_name),\(.severity),\(.description)"' scan_report.json > extracted_results.csv

βœ… Step 3: Insert Data into the Database

Use a Python script to insert Nessus scan results into MySQL.

πŸš€ Python Script (insert_nessus_results.py)

import mysql.connector
import csv

# Database Connection
conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="yourpassword",
    database="nessus_scans"
)
cursor = conn.cursor()

# Read Extracted CSV Data
with open("extracted_results.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        cursor.execute("INSERT INTO scan_results (scan_id, target, risk, description) VALUES (%s, %s, %s, %s)", row)

conn.commit()
cursor.close()
conn.close()

print("Scan results inserted into the database!")

βœ… Step 4: Automate Database Logging

Schedule this script using Cron (Linux) or Task Scheduler (Windows) to log scan results daily.

πŸ“Œ Add to Cron (Linux)

0 4 * * * python3 /path/to/insert_nessus_results.py

(Runs daily at 4 AM after scan and report generation.)

πŸ“Œ Add to Task Scheduler (Windows)

  • Action: Start a program
  • Program: powershell.exe
  • Arguments: python "C:\path\to\insert_nessus_results.py"

πŸ’‘ Next Steps

βœ… Scans are logged into a MySQL database
βœ… Reports can be queried for historical analysis
βœ… Set up dashboards using Grafana or Power BI for insights

Would you like to create a dashboard to visualize Nessus scan trends? πŸ“ŠπŸš€

πŸ”Ή Creating a Nessus Scan Dashboard with Grafana πŸ“ŠπŸš€

Now that Nessus scan results are stored in MySQL, let’s visualize them using Grafana for real-time monitoring.


βœ… Step 1: Install Grafana

πŸ“Œ Install on Ubuntu/Debian

sudo apt update && sudo apt install -y grafana
sudo systemctl start grafana-server
sudo systemctl enable grafana-server

πŸ“Œ Install on CentOS/RHEL

sudo yum install -y grafana
sudo systemctl start grafana-server
sudo systemctl enable grafana-server

πŸ“Œ Install on Windows

  1. Download Grafana from official website.
  2. Install and start Grafana.

βœ… Step 2: Connect MySQL Database

  1. Login to Grafana β†’ http://localhost:3000 (Default: admin/admin).
  2. Go to “Data Sources” β†’ Add MySQL.
  3. Enter MySQL Connection Details
    • Host: localhost:3306
    • Database: nessus_scans
    • User: root
    • Password: yourpassword
  4. Click Save & Test βœ…

βœ… Step 3: Create Nessus Dashboard

  1. Go to “Create” β†’ “Dashboard”
  2. Click “Add a New Panel”
  3. Enter SQL Query to fetch scan results: SELECT timestamp, target, risk FROM scan_results ORDER BY timestamp DESC;
  4. Visualize Data:
    • Use Time Series for risk trends.
    • Use Table View for a summary.
  5. Click Save Dashboard πŸ“Š

βœ… Step 4: Automate Data Refresh

  • Set Refresh Rate β†’ Every 5 minutes
  • Enable Alerts β†’ Trigger alerts for critical vulnerabilities 🚨

πŸ’‘ What This Dashboard Provides?

βœ… Live Nessus scan reports πŸ“Š
βœ… Risk trend analysis πŸ“ˆ
βœ… Alerts on critical vulnerabilities 🚨

Would you like email alerts for high-risk vulnerabilities? πŸ“§πŸ”₯

πŸ”Ή Automating Email Alerts for High-Risk Nessus Vulnerabilities πŸš¨πŸ“§

We’ll set up an automated email alert system that sends an email when a high-risk vulnerability is detected in a Nessus scan.


βœ… Step 1: Modify Database Query for High-Risk Vulnerabilities

We need to fetch Critical (4) and High (3) severity vulnerabilities from the database.

SELECT target, risk, description, timestamp 
FROM scan_results 
WHERE risk IN ('High', 'Critical') 
ORDER BY timestamp DESC;

βœ… Step 2: Python Script to Send Alerts via Email

This script will:
βœ… Fetch high-risk vulnerabilities from MySQL
βœ… Format the data into an email
βœ… Send alerts using SMTP (Gmail, Outlook, AWS SES, etc.)

πŸš€ Python Script (send_nessus_alert.py)

import mysql.connector
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Database Connection
conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="yourpassword",
    database="nessus_scans"
)
cursor = conn.cursor()

# Fetch High-Risk Vulnerabilities
cursor.execute("SELECT target, risk, description, timestamp FROM scan_results WHERE risk IN ('High', 'Critical') ORDER BY timestamp DESC;")
vulns = cursor.fetchall()

if vulns:
    # Email Configuration
    SMTP_SERVER = "smtp.gmail.com"  # Change if using Outlook, AWS SES, etc.
    SMTP_PORT = 587
    SMTP_USER = "your-email@example.com"
    SMTP_PASS = "yourpassword"

    TO_EMAIL = "recipient@example.com"
    FROM_EMAIL = SMTP_USER
    SUBJECT = "🚨 Nessus High-Risk Vulnerability Alert"

    # Format Email Content
    body = "πŸ”΄ **High-Risk Nessus Scan Alerts** πŸ”΄\n\n"
    for target, risk, description, timestamp in vulns:
        body += f"πŸ”Ή **Target:** {target}\n"
        body += f"⚠️ **Risk Level:** {risk}\n"
        body += f"πŸ“Œ **Description:** {description}\n"
        body += f"⏰ **Detected On:** {timestamp}\n\n"
    
    # Send Email
    msg = MIMEMultipart()
    msg["From"] = FROM_EMAIL
    msg["To"] = TO_EMAIL
    msg["Subject"] = SUBJECT
    msg.attach(MIMEText(body, "plain"))

    server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    server.starttls()
    server.login(SMTP_USER, SMTP_PASS)
    server.sendmail(FROM_EMAIL, TO_EMAIL, msg.as_string())
    server.quit()

    print("πŸ“© High-Risk Nessus Alert Sent Successfully!")

# Close DB Connection
cursor.close()
conn.close()

βœ… Step 3: Automate Email Alerts

πŸ“Œ Linux (Cron Job)

crontab -e

Add this line to run every 30 minutes:

*/30 * * * * python3 /path/to/send_nessus_alert.py

πŸ“Œ Windows (Task Scheduler)

  1. Create New Task β†’ Trigger: Every 30 minutes
  2. Action: Start a program
  3. Program: powershell.exe
  4. Arguments: python "C:\path\to\send_nessus_alert.py"

πŸ’‘ What This Automation Does

βœ… Checks for High-Risk vulnerabilities every 30 minutes
βœ… Sends email alerts 🚨 if any are found
βœ… Works on both Linux & Windows

Would you like to integrate this with Slack or Telegram alerts? πŸ””πŸš€

πŸ”Ή Automating Nessus Alerts via Slack & Telegram πŸ””πŸš€

Now, let’s send Nessus high-risk vulnerability alerts to Slack and Telegram in real-time.


βœ… Step 1: Send Alerts to Slack

πŸ“Œ Get Your Slack Webhook URL

  1. Go to Slack API β†’ Create New App
  2. Select Incoming Webhooks β†’ Activate
  3. Add to a Slack channel & copy the Webhook URL

πŸš€ Modify Python Script (send_nessus_alert.py)

Add this function to send alerts to Slack:

import requests

SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/XXXX/XXXX/XXXX"  # Replace with your Slack Webhook

def send_slack_alert(vulns):
    if not vulns:
        return

    message = "*🚨 Nessus High-Risk Vulnerability Alert 🚨*\n"
    for target, risk, description, timestamp in vulns:
        message += f"πŸ”Ή *Target:* {target}\n"
        message += f"⚠️ *Risk Level:* {risk}\n"
        message += f"πŸ“Œ *Description:* {description}\n"
        message += f"⏰ *Detected On:* {timestamp}\n\n"

    payload = {"text": message}
    requests.post(SLACK_WEBHOOK_URL, json=payload)

send_slack_alert(vulns)  # Call the function after fetching vulnerabilities

βœ… Step 2: Send Alerts to Telegram

πŸ“Œ Get Your Telegram Bot API Token & Chat ID

  1. Open Telegram β†’ Search for BotFather
  2. Run /newbot and get your Bot API Token
  3. Send /start to your bot & get your Chat ID from https://api.telegram.org/bot<TOKEN>/getUpdates

πŸš€ Modify Python Script (send_nessus_alert.py)

Add this function to send alerts to Telegram:

TELEGRAM_BOT_TOKEN = "YOUR_BOT_TOKEN"  # Replace with your bot token
TELEGRAM_CHAT_ID = "YOUR_CHAT_ID"  # Replace with your chat ID

def send_telegram_alert(vulns):
    if not vulns:
        return

    message = "🚨 *Nessus High-Risk Vulnerability Alert* 🚨\n"
    for target, risk, description, timestamp in vulns:
        message += f"πŸ”Ή *Target:* {target}\n"
        message += f"⚠️ *Risk Level:* {risk}\n"
        message += f"πŸ“Œ *Description:* {description}\n"
        message += f"⏰ *Detected On:* {timestamp}\n\n"

    telegram_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    payload = {"chat_id": TELEGRAM_CHAT_ID, "text": message, "parse_mode": "Markdown"}
    requests.post(telegram_url, json=payload)

send_telegram_alert(vulns)  # Call function after fetching vulnerabilities

βœ… Step 3: Automate Slack & Telegram Alerts

πŸ“Œ Linux (Cron Job)

crontab -e

Add this line to run every 30 minutes:

*/30 * * * * python3 /path/to/send_nessus_alert.py

πŸ“Œ Windows (Task Scheduler)

  1. Create New Task β†’ Trigger: Every 30 minutes
  2. Action: Start a program
  3. Program: powershell.exe
  4. Arguments: python "C:\path\to\send_nessus_alert.py"

πŸ’‘ Final Setup Summary

βœ… Email Alerts for High-Risk Nessus Vulnerabilities πŸ“§
βœ… Slack Alerts for Immediate Notification πŸ””
βœ… Telegram Alerts for Mobile Alerts πŸ“²
βœ… Automated to Run Every 30 Minutes ⏰

Would you like to store alerts in a log file for tracking? πŸ“œπŸš€

πŸ”Ή Logging Nessus Alerts for Tracking & Auditing πŸ“œπŸš€

Now, we’ll store all Nessus high-risk vulnerability alerts in a log file for tracking and auditing purposes.


βœ… Step 1: Create a Log File for Alerts

Modify the Python script to write alerts to a log file:

πŸš€ Update send_nessus_alert.py to Include Logging

import logging

# Configure Logging
LOG_FILE = "/var/log/nessus_alerts.log"  # Linux path (use C:\nessus_alerts.log for Windows)
logging.basicConfig(filename=LOG_FILE, level=logging.INFO, format="%(asctime)s - %(message)s")

def log_alert(vulns):
    if not vulns:
        return

    with open(LOG_FILE, "a") as log_file:
        log_file.write("\n🚨 Nessus High-Risk Vulnerability Alert 🚨\n")
        for target, risk, description, timestamp in vulns:
            log_entry = f"πŸ”Ή Target: {target} | ⚠️ Risk: {risk} | πŸ“Œ Description: {description} | ⏰ Time: {timestamp}\n"
            log_file.write(log_entry)
            logging.info(log_entry)

log_alert(vulns)  # Call function after fetching vulnerabilities

βœ… Step 2: Rotate Logs Automatically

To prevent logs from growing too large, we can rotate logs using logrotate (Linux) or Task Scheduler (Windows).

πŸ“Œ Linux: Use logrotate

  1. Create a new logrotate config file: sudo nano /etc/logrotate.d/nessus_alerts
  2. Add the following config: /var/log/nessus_alerts.log { daily rotate 7 compress missingok notifempty } (This keeps logs for 7 days, compresses old ones, and ignores empty files.)
  3. Save & exit (CTRL + X, Y, Enter)
  4. Test logrotate: sudo logrotate -f /etc/logrotate.d/nessus_alerts

πŸ“Œ Windows: Use Task Scheduler

  1. Create New Task β†’ Trigger: Daily
  2. Action: Run Command PowerShell Compress-Archive -Path C:\nessus_alerts.log -DestinationPath C:\nessus_alerts_$(Get-Date -Format "yyyyMMdd").zip -Force

βœ… Step 3: Automate Logging with Alerts

πŸ“Œ Linux (Cron Job)

crontab -e

Add this line to log alerts every 30 minutes:

*/30 * * * * python3 /path/to/send_nessus_alert.py

πŸ“Œ Windows (Task Scheduler)

  1. Create New Task β†’ Trigger: Every 30 minutes
  2. Action: Start a program
  3. Program: powershell.exe
  4. Arguments: python "C:\path\to\send_nessus_alert.py"

πŸ’‘ Final Setup Summary

βœ… Logs every High-Risk Nessus vulnerability πŸ“œ
βœ… Automated log rotation to save disk space πŸ”„
βœ… Easy tracking of past security issues πŸ”

Would you like to send a weekly Nessus security report via email? πŸ“ŠπŸ“§

πŸ”Ή Automating Weekly Nessus Security Reports via Email πŸ“ŠπŸ“§

Now, we’ll generate a weekly security report from Nessus scan logs and send it via email.


βœ… Step 1: Generate a Weekly Nessus Report

Modify the Python script to:
βœ… Read the past week’s Nessus logs
βœ… Format them into a report
βœ… Send the report via email


πŸš€ Python Script (send_weekly_nessus_report.py)

import smtplib
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Email Configuration
SMTP_SERVER = "smtp.gmail.com"  # Change if using Outlook, AWS SES, etc.
SMTP_PORT = 587
SMTP_USER = "your-email@example.com"
SMTP_PASS = "yourpassword"
TO_EMAIL = "recipient@example.com"
FROM_EMAIL = SMTP_USER
SUBJECT = "πŸ“Š Weekly Nessus Security Report"

# Log File Path
LOG_FILE = "/var/log/nessus_alerts.log"  # Linux path (Use C:\nessus_alerts.log for Windows)

# Read Logs from the Past Week
def get_weekly_logs():
    report = "πŸ“Š **Weekly Nessus Security Report** πŸ“Š\n\n"
    today = datetime.datetime.now()
    past_week = today - datetime.timedelta(days=7)

    try:
        with open(LOG_FILE, "r") as log_file:
            lines = log_file.readlines()
            for line in lines:
                # Extract date and filter last 7 days
                if "πŸ”Ή Target" in line:
                    report += line
    except FileNotFoundError:
        report += "No security alerts found in the past week.\n"

    return report

# Send Report via Email
def send_email(report):
    msg = MIMEMultipart()
    msg["From"] = FROM_EMAIL
    msg["To"] = TO_EMAIL
    msg["Subject"] = SUBJECT
    msg.attach(MIMEText(report, "plain"))

    server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    server.starttls()
    server.login(SMTP_USER, SMTP_PASS)
    server.sendmail(FROM_EMAIL, TO_EMAIL, msg.as_string())
    server.quit()

    print("πŸ“© Weekly Nessus Report Sent Successfully!")

# Generate & Send Report
weekly_report = get_weekly_logs()
send_email(weekly_report)

βœ… Step 2: Automate Weekly Report Sending

πŸ“Œ Linux (Cron Job)

crontab -e

Add this line to run every Monday at 8 AM:

0 8 * * 1 python3 /path/to/send_weekly_nessus_report.py

πŸ“Œ Windows (Task Scheduler)

  1. Create New Task β†’ Trigger: Weekly (Monday, 8 AM)
  2. Action: Start a program
  3. Program: powershell.exe
  4. Arguments: python "C:\path\to\send_weekly_nessus_report.py"

πŸ’‘ Final Setup Summary

βœ… Gathers last week’s Nessus vulnerabilities πŸ“œ
βœ… Formats them into a structured report πŸ“Š
βœ… Sends an automated email every Monday πŸ“©

Would you like to also generate a PDF report for better readability? πŸ“‘πŸš€

πŸ”Ή Generate & Send a Weekly Nessus Report as a PDF πŸ“‘πŸš€

Now, we’ll generate a well-formatted PDF report from the Nessus logs and attach it to an email for easy sharing.


βœ… Step 1: Install Required Libraries

Run the following command to install necessary Python libraries:

pip install fpdf

βœ… Step 2: Modify Script to Generate a PDF Report

We’ll generate a PDF report from the past week’s logs and email it as an attachment.

πŸš€ Python Script (send_weekly_nessus_report_pdf.py)

import smtplib
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from fpdf import FPDF
import os

# Email Configuration
SMTP_SERVER = "smtp.gmail.com"  # Change if using Outlook, AWS SES, etc.
SMTP_PORT = 587
SMTP_USER = "your-email@example.com"
SMTP_PASS = "yourpassword"
TO_EMAIL = "recipient@example.com"
FROM_EMAIL = SMTP_USER
SUBJECT = "πŸ“Š Weekly Nessus Security Report (PDF)"

# Log File Path
LOG_FILE = "/var/log/nessus_alerts.log"  # Use C:\nessus_alerts.log for Windows
PDF_REPORT = "/tmp/Nessus_Report.pdf"  # Change as needed (Windows: C:\Temp\Nessus_Report.pdf)

# Read Logs from the Past Week
def get_weekly_logs():
    report = "πŸ“Š Weekly Nessus Security Report πŸ“Š\n\n"
    today = datetime.datetime.now()
    past_week = today - datetime.timedelta(days=7)

    logs = []
    try:
        with open(LOG_FILE, "r") as log_file:
            for line in log_file:
                if "πŸ”Ή Target" in line:  
                    logs.append(line.strip())

    except FileNotFoundError:
        logs.append("No security alerts found in the past week.")

    return logs

# Generate PDF Report
def generate_pdf(logs):
    pdf = FPDF()
    pdf.set_auto_page_break(auto=True, margin=15)
    pdf.add_page()
    pdf.set_font("Arial", style="B", size=16)
    pdf.cell(200, 10, "Nessus Weekly Security Report", ln=True, align="C")
    pdf.ln(10)

    pdf.set_font("Arial", size=12)
    for log in logs:
        pdf.multi_cell(0, 10, log)
        pdf.ln(2)

    pdf.output(PDF_REPORT)
    print(f"πŸ“‘ PDF Report Generated: {PDF_REPORT}")

# Send Email with PDF Attachment
def send_email():
    msg = MIMEMultipart()
    msg["From"] = FROM_EMAIL
    msg["To"] = TO_EMAIL
    msg["Subject"] = SUBJECT
    body = "Attached is the weekly Nessus security report in PDF format."
    msg.attach(MIMEText(body, "plain"))

    with open(PDF_REPORT, "rb") as attachment:
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header("Content-Disposition", f"attachment; filename={os.path.basename(PDF_REPORT)}")
        msg.attach(part)

    server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    server.starttls()
    server.login(SMTP_USER, SMTP_PASS)
    server.sendmail(FROM_EMAIL, TO_EMAIL, msg.as_string())
    server.quit()

    print("πŸ“© Weekly Nessus PDF Report Sent Successfully!")

# Run the script
logs = get_weekly_logs()
generate_pdf(logs)
send_email()

βœ… Step 3: Automate Weekly PDF Report Sending

πŸ“Œ Linux (Cron Job)

crontab -e

Add this line to run every Monday at 8 AM:

0 8 * * 1 python3 /path/to/send_weekly_nessus_report_pdf.py

πŸ“Œ Windows (Task Scheduler)

  1. Create New Task β†’ Trigger: Weekly (Monday, 8 AM)
  2. Action: Start a program
  3. Program: powershell.exe
  4. Arguments: python "C:\path\to\send_weekly_nessus_report_pdf.py"

πŸ’‘ Final Setup Summary

βœ… Generates a structured PDF Nessus report πŸ“‘
βœ… Emails the report as an attachment every Monday πŸ“©
βœ… Keeps security reports well-documented πŸ”

Would you like to also upload this PDF to a cloud storage (Google Drive, AWS S3)? β˜οΈπŸš€

πŸ”Ή Upload Nessus PDF Report to Cloud Storage β˜οΈπŸš€

Now, we’ll upload the weekly Nessus PDF report to Google Drive or AWS S3 for easy access and backups.


βœ… Step 1: Choose a Cloud Storage Provider

We can upload the report to:
1️⃣ Google Drive (Requires Google API)
2️⃣ AWS S3 (Requires AWS CLI or Boto3)


βœ… Option 1: Upload to Google Drive

Step 1.1: Install Google Drive API Library

pip install google-auth google-auth-oauthlib google-auth-httplib2 googleapiclient

Step 1.2: Get Google API Credentials

  1. Go to Google Cloud Console.
  2. Enable the Google Drive API.
  3. Create OAuth 2.0 credentials β†’ Download credentials.json.
  4. Place credentials.json in your script folder.

Step 1.3: Modify Python Script

Add this function to upload the PDF report to Google Drive:

from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.oauth2 import service_account

# Google Drive Setup
SCOPES = ["https://www.googleapis.com/auth/drive.file"]
SERVICE_ACCOUNT_FILE = "credentials.json"  # Your downloaded credentials file

def upload_to_drive():
    creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    drive_service = build("drive", "v3", credentials=creds)

    file_metadata = {"name": "Nessus_Weekly_Report.pdf", "mimeType": "application/pdf"}
    media = MediaFileUpload(PDF_REPORT, mimetype="application/pdf")

    file = drive_service.files().create(body=file_metadata, media_body=media, fields="id").execute()
    print(f"βœ… Report Uploaded to Google Drive: https://drive.google.com/file/d/{file['id']}")

Step 1.4: Automate Upload After Generating Report

Call upload_to_drive() after generating the PDF:

generate_pdf(logs)
send_email()
upload_to_drive()

βœ… Option 2: Upload to AWS S3

Step 2.1: Install AWS SDK for Python

pip install boto3

Step 2.2: Configure AWS Credentials

aws configure

Enter your AWS Access Key, Secret Key, and Region.

Step 2.3: Modify Python Script

Add this function to upload the PDF report to AWS S3:

import boto3

# AWS S3 Configuration
S3_BUCKET = "your-s3-bucket-name"
S3_FILE_NAME = "Nessus_Weekly_Report.pdf"

def upload_to_s3():
    s3 = boto3.client("s3")
    s3.upload_file(PDF_REPORT, S3_BUCKET, S3_FILE_NAME)
    print(f"βœ… Report Uploaded to S3: https://{S3_BUCKET}.s3.amazonaws.com/{S3_FILE_NAME}")

Step 2.4: Automate Upload After Generating Report

Call upload_to_s3() after generating the PDF:

generate_pdf(logs)
send_email()
upload_to_s3()

βœ… Final Setup Summary

βœ… Uploads Nessus report to Google Drive or AWS S3 ☁️
βœ… Automates the process every week πŸ”„
βœ… Ensures reports are always backed up πŸ“‚

Would you like to set up a Telegram bot to notify you when the report is uploaded? πŸ“’πŸš€

πŸ”Ή Get Telegram Notification When Nessus Report is Uploaded πŸ“’πŸš€

Now, we’ll set up a Telegram bot to notify you when the Nessus report is uploaded to Google Drive or AWS S3.


βœ… Step 1: Create a Telegram Bot

1️⃣ Open Telegram and search for BotFather.
2️⃣ Send /newbot and follow the instructions.
3️⃣ Copy the Bot Token that BotFather provides.
4️⃣ Get your Chat ID by sending the bot a message and using this URL:

https://api.telegram.org/bot<Your-Bot-Token>/getUpdates

5️⃣ Note the chat_id from the response.


βœ… Step 2: Install Requests Library

pip install requests

βœ… Step 3: Modify Python Script to Send Telegram Notifications

Add this function to send a message when the report is uploaded:

import requests

# Telegram Bot Configuration
TELEGRAM_BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
TELEGRAM_CHAT_ID = "YOUR_CHAT_ID"

def send_telegram_message(message):
    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    payload = {"chat_id": TELEGRAM_CHAT_ID, "text": message}
    requests.post(url, data=payload)

βœ… Step 4: Integrate with Google Drive & AWS S3 Uploads

πŸ“Œ If using Google Drive

Modify upload_to_drive() function:

def upload_to_drive():
    creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    drive_service = build("drive", "v3", credentials=creds)

    file_metadata = {"name": "Nessus_Weekly_Report.pdf", "mimeType": "application/pdf"}
    media = MediaFileUpload(PDF_REPORT, mimetype="application/pdf")

    file = drive_service.files().create(body=file_metadata, media_body=media, fields="id").execute()
    drive_link = f"https://drive.google.com/file/d/{file['id']}"
    
    print(f"βœ… Report Uploaded to Google Drive: {drive_link}")
    send_telegram_message(f"πŸ“’ Nessus Report Uploaded to Google Drive! πŸš€\nπŸ”— {drive_link}")

πŸ“Œ If using AWS S3

Modify upload_to_s3() function:

def upload_to_s3():
    s3 = boto3.client("s3")
    s3.upload_file(PDF_REPORT, S3_BUCKET, S3_FILE_NAME)
    s3_link = f"https://{S3_BUCKET}.s3.amazonaws.com/{S3_FILE_NAME}"
    
    print(f"βœ… Report Uploaded to S3: {s3_link}")
    send_telegram_message(f"πŸ“’ Nessus Report Uploaded to AWS S3! πŸš€\nπŸ”— {s3_link}")

βœ… Step 5: Automate Notification After Upload

Modify the main script:

generate_pdf(logs)
send_email()
upload_to_drive()  # or upload_to_s3()

🎯 Final Setup Summary

βœ… Uploads Nessus report to Google Drive or AWS S3 ☁️
βœ… Sends a Telegram notification with the report link πŸ“’
βœ… Automates everything weekly πŸ”„

About Anant 443 Articles
Senior technical writer