Trying to help the LLM
This commit is contained in:
@@ -15,6 +15,8 @@ import nmap
|
||||
import logging
|
||||
from logging.handlers import TimedRotatingFileHandler
|
||||
|
||||
import schedule
|
||||
|
||||
# Load configuration
|
||||
import config
|
||||
|
||||
@@ -192,7 +194,7 @@ def get_nmap_scan_results():
|
||||
|
||||
# --- LLM Interaction Function ---
|
||||
|
||||
def build_llm_prompt(data, baselines, nmap_changes, constraints, known_issues):
|
||||
def build_llm_prompt(data, baselines, nmap_changes, constraints, known_issues, port_applications):
|
||||
"""Builds the prompt for the LLM analysis."""
|
||||
return f"""
|
||||
**Role:** You are a dedicated and expert system administrator. Your primary role is to identify anomalies and provide concise, actionable reports.
|
||||
@@ -211,6 +213,9 @@ def build_llm_prompt(data, baselines, nmap_changes, constraints, known_issues):
|
||||
**Known Issues Feed:**
|
||||
{json.dumps(known_issues, indent=2)}
|
||||
|
||||
**Known Port Applications:**
|
||||
{json.dumps(port_applications, indent=2)}
|
||||
|
||||
**Constraints and Guidelines:**
|
||||
{constraints}
|
||||
|
||||
@@ -228,6 +233,9 @@ def analyze_data_with_llm(data, baselines):
|
||||
with open("known_issues.json", "r") as f:
|
||||
known_issues = json.load(f)
|
||||
|
||||
with open("port_applications.json", "r") as f:
|
||||
port_applications = json.load(f)
|
||||
|
||||
# Compare current nmap results with baseline
|
||||
nmap_changes = {"new_hosts": [], "changed_ports": {}}
|
||||
if "nmap_results" in data and "host_ports" in baselines:
|
||||
@@ -250,7 +258,7 @@ def analyze_data_with_llm(data, baselines):
|
||||
if newly_opened or newly_closed:
|
||||
nmap_changes["changed_ports"][host_ip] = {"opened": newly_opened, "closed": newly_closed}
|
||||
|
||||
prompt = build_llm_prompt(data, baselines, nmap_changes, constraints, known_issues)
|
||||
prompt = build_llm_prompt(data, baselines, nmap_changes, constraints, known_issues, port_applications)
|
||||
|
||||
try:
|
||||
response = ollama.generate(model="llama3.1:8b", prompt=prompt)
|
||||
@@ -282,8 +290,10 @@ def analyze_data_with_llm(data, baselines):
|
||||
|
||||
# --- Alerting Functions ---
|
||||
|
||||
def send_discord_alert(message):
|
||||
def send_discord_alert(llm_response, combined_data):
|
||||
"""Sends an alert to Discord."""
|
||||
reason = llm_response.get('reason', 'No reason provided.')
|
||||
message = f"**High Severity Alert:**\n> {reason}\n\n**Relevant Data:**\n```json\n{json.dumps(combined_data, indent=2)}\n```"
|
||||
webhook = DiscordWebhook(url=config.DISCORD_WEBHOOK_URL, content=message)
|
||||
try:
|
||||
response = webhook.execute()
|
||||
@@ -332,7 +342,25 @@ def is_alerting_time():
|
||||
|
||||
daily_events = []
|
||||
|
||||
|
||||
def send_daily_recap():
|
||||
"""Sends a daily recap of events to Discord."""
|
||||
global daily_events
|
||||
if daily_events:
|
||||
recap_message = "\n".join(daily_events)
|
||||
webhook = DiscordWebhook(url=config.DISCORD_WEBHOOK_URL, content=f"**Daily Recap:**\n{recap_message}")
|
||||
try:
|
||||
response = webhook.execute()
|
||||
if response.status_code == 200:
|
||||
logger.info("Daily recap sent successfully.")
|
||||
else:
|
||||
logger.error(f"Error sending daily recap: {response.status_code} - {response.content}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending daily recap: {e}")
|
||||
daily_events = [] # Reset for the next day
|
||||
|
||||
def run_monitoring_cycle(nmap_scan_counter):
|
||||
|
||||
"""Runs a single monitoring cycle."""
|
||||
logger.info("Running monitoring cycle...")
|
||||
system_logs = get_system_logs()
|
||||
@@ -368,7 +396,7 @@ def run_monitoring_cycle(nmap_scan_counter):
|
||||
if llm_response and llm_response.get('severity') != "none":
|
||||
daily_events.append(llm_response.get('reason'))
|
||||
if llm_response.get('severity') == "high" and is_alerting_time():
|
||||
send_discord_alert(llm_response.get('reason'))
|
||||
send_discord_alert(llm_response, combined_data)
|
||||
send_google_home_alert(llm_response.get('reason'))
|
||||
return nmap_scan_counter
|
||||
|
||||
@@ -378,17 +406,11 @@ def main():
|
||||
logger.info("Running in test mode...")
|
||||
run_monitoring_cycle(0)
|
||||
else:
|
||||
schedule.every().day.at(config.DAILY_RECAP_TIME).do(send_daily_recap)
|
||||
nmap_scan_counter = 0
|
||||
while True:
|
||||
nmap_scan_counter = run_monitoring_cycle(nmap_scan_counter)
|
||||
|
||||
# Daily Recap Logic
|
||||
current_time = time.strftime("%H:%M")
|
||||
if current_time == config.DAILY_RECAP_TIME and daily_events: # type: ignore
|
||||
recap_message = "\n".join(daily_events)
|
||||
send_discord_alert(f"**Daily Recap:**\n{recap_message}")
|
||||
daily_events = [] # Reset for the next day
|
||||
|
||||
schedule.run_pending()
|
||||
time.sleep(300) # Run every 5 minutes
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user