Linux already provides several tools for monitoring security events. The problem is that raw logs are not always easy to read.
For example, a server may contain failed SSH logins, unexpected service restarts, privilege changes, or other unusual events. You can search these events manually, but an AI model can make the analysis easier by turning the raw events into a short explanation.
In this project, we will build a simple Linux security monitor that:
- Reads recent Linux security logs
- Looks for suspicious events
- Sends selected events to an AI model
- Gets a human-readable explanation
- Prints a security report
This is not a replacement for tools such as auditd, a SIEM, EDR, or a firewall. The goal is to add an AI analysis layer on top of existing Linux logging.
How It Works
The basic architecture is:
Linux Server
|
+-- SSH logs
+-- systemd journal
+-- auditd
|
v
Security Monitor
|
v
Filter suspicious events
|
v
AI model
|
v
Security Report
Linux distributions using systemd can collect system events through the journal. The journalctl command can then be used to inspect those events.
For more detailed auditing, Linux provides auditd. The ausearch and aureport utilities can search and summarize audit events.
The Linux Audit system is documented by Red Hat, including persistent rules and tools such as ausearch and aureport.
1. Install the Required Tools
On Ubuntu or Debian:
sudo apt update
sudo apt install audit python3 python3-pip -y
Enable the Audit service:
sudo systemctl enable --now auditd
Check its status:
sudo systemctl status auditd
You can also check the system journal:
sudo journalctl -n 50
And view recent authentication-related messages:
sudo journalctl -u ssh --since "1 hour ago"
The exact SSH service name can differ between distributions. On some systems it may be sshd instead of ssh.
2. Check Linux Audit Logs
Audit logs are normally stored under:
/var/log/audit/
Check the directory:
sudo ls -lah /var/log/audit/
You can search for failed login events with:
sudo ausearch -m USER_LOGIN --success no --interpret
You can also generate a summary of failed login attempts:
sudo aureport --login --failed --summary -i
These tools are useful because we do not need to send every log entry to an AI model.
Instead, we can first collect relevant security events and then ask the AI model to analyze them.
3. Create the Security Monitor
Create a project directory:
mkdir -p ~/linux-security-monitor
cd ~/linux-security-monitor
Create the Python script:
nano monitor.py
Add:
#!/usr/bin/env python3
import subprocess
import json
import os
import urllib.request
def run_command(command):
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True
)
return result.stdout.strip()
def collect_events():
events = {}
events["failed_logins"] = run_command(
"sudo ausearch -m USER_LOGIN --success no --interpret"
)
events["recent_ssh_logs"] = run_command(
"sudo journalctl -u ssh --since '1 hour ago' --no-pager"
)
events["recent_system_events"] = run_command(
"sudo journalctl --since '1 hour ago' -p warning..alert --no-pager"
)
return events
def build_prompt(events):
return f"""
You are analyzing security events from a Linux server.
Review the following events and provide:
1. Important security events
2. Possible suspicious activity
3. Events that are probably normal
4. Recommended actions
5. A severity rating: LOW, MEDIUM, HIGH, or CRITICAL
Do not claim that an attack definitely happened unless the evidence supports it.
Linux security events:
{json.dumps(events, indent=2)}
"""
def main():
events = collect_events()
print("Collected security events.")
print()
prompt = build_prompt(events)
print("AI analysis prompt:")
print(prompt)
if __name__ == "__main__":
main()
At this stage, the script does not call an AI API yet.
It simply collects the information and creates the analysis prompt.
That is intentional.
You should first verify that the data being collected is actually useful.
Run:
python3 monitor.py
4. Add an AI Model
There are two practical approaches.
Option 1: Use a local AI model
You can run a local model using software such as Ollama.
The advantage is that sensitive server logs do not have to leave the server.
The disadvantage is that running a useful local model requires CPU, RAM, and storage, and the quality depends heavily on the model.
For a small server, you should avoid running a large model just for log analysis.
Option 2: Use an AI API
The monitor can send the selected security events to an AI API.
The important part is to avoid sending everything.
Do not blindly upload:
/var/log/*
Instead, filter the events first.
For example:
Failed SSH login
Unknown user
Unexpected sudo usage
Unexpected service failure
Audit event
Unexpected privileged command
This reduces the amount of data sent to the model and makes the AI response more useful.
5. Example AI Analysis
Suppose the monitor finds:
Failed login for user admin
Failed login for user root
Failed login for user test
Failed login for user ubuntu
The AI could summarize the situation as:
Severity: MEDIUM
Several failed SSH authentication attempts were detected
against multiple usernames.
The events are consistent with automated SSH login scanning.
Recommended actions:
1. Confirm whether SSH is exposed to the internet.
2. Check the source IP addresses.
3. Disable password authentication if SSH keys are available.
4. Verify that root login over SSH is disabled.
5. Consider restricting SSH access with a firewall.
This is more useful than simply reading dozens of individual log entries.
However, the AI should not automatically decide that an attack occurred.
It should explain the evidence and let the administrator verify it.
6. Add Source IP Analysis
SSH authentication logs often contain the source address.
You can extract suspicious addresses and count how frequently they appear.
For example:
sudo journalctl -u ssh --since "1 hour ago" --no-pager
| grep -i "failed"
You could then process the output with Python.
A simple approach is:
from collections import Counter
import re
text = run_command(
"sudo journalctl -u ssh --since '1 hour ago' --no-pager"
)
ips = re.findall(
r'from ([0-9]{1,3}(?:.[0-9]{1,3}){3})',
text
)
counts = Counter(ips)
for ip, count in counts.most_common(10):
print(ip, count)
The result might look like:
203.0.113.10 34
198.51.100.25 21
192.0.2.50 7
The monitor can then tell the AI:
203.0.113.10 generated 34 failed SSH authentication attempts
during the last hour.
That gives the AI useful context instead of forcing it to process thousands of unrelated log lines.
7. Monitor Important System Changes
You can expand the monitor beyond SSH.
For example, check failed services:
systemctl --failed --no-legend
Check listening ports:
sudo ss -tulpn
Check logged-in users:
who
Check recent logins:
last -n 20
Check privileged commands with Audit:
sudo ausearch -m USER_CMD -ts recent -i
You can combine these results into the same report.
For example:
def collect_system_state():
return {
"failed_services": run_command(
"systemctl --failed --no-legend"
),
"listening_ports": run_command(
"sudo ss -tulpn"
),
"logged_in_users": run_command(
"who"
),
"recent_logins": run_command(
"last -n 20"
)
}
Now the AI has both events and current system state.
8. Do Not Let the AI Automatically Execute Commands
This is an important design decision.
Do not build the first version like this:
AI detects problem
|
v
AI executes command
|
v
AI modifies server
Instead, use:
AI detects problem
|
v
AI explains problem
|
v
Administrator reviews it
|
v
Administrator takes action
For example, if the AI thinks an SSH account is suspicious, it can recommend:
sudo passwd -l username
But the monitor should not execute that command automatically.
A false positive could lock out a legitimate administrator.
9. Create a Simple Security Report
Instead of printing raw AI output, you can structure the report:
Linux Security Monitor
======================
Time:
2026-09-12 20:00:00
Severity:
MEDIUM
Findings:
- 62 failed SSH login attempts
- 3 different usernames targeted
- 2 source IP addresses generated most attempts
- No failed system services detected
Assessment:
The SSH activity appears consistent with automated
internet scanning.
Recommended actions:
- Verify SSH authentication configuration
- Check source IP addresses
- Disable password authentication if possible
- Restrict SSH access where practical
This format is much easier to read than a large block of log data.
10. Run It Automatically
Once the monitor works correctly, you can run it periodically.
For example, using cron:
crontab -e
Add:
*/15 * * * * /usr/bin/python3 /home/user/linux-security-monitor/monitor.py >> /home/user/linux-security-monitor/monitor.log 2>&1
This runs the monitor every 15 minutes.
For a production server, you should use the actual absolute path to the Python script and make sure the account running it has permission to read the required logs.
11. A Better Production Architecture
The simple version can eventually become:
Linux Server
|
+------------+------------+
| | |
SSH auditd systemd
logs logs journal
| | |
+------------+------------+
|
v
Event Collector
|
v
Event Filtering
|
v
Security Database
|
v
AI Analysis
|
+----------+----------+
| |
v v
Dashboard Alert
The database is useful because you can compare current activity with previous activity.
For example:
Normal:
5 failed SSH attempts/hour
Current:
450 failed SSH attempts/hour
That change is much more interesting than simply seeing:
Failed SSH login
12. What the AI Should Actually Do
AI is most useful for interpretation.
It can help answer questions such as:
- What happened?
- Is this probably normal?
- Is this unusual compared with recent activity?
- Which events are related?
- What should I investigate?
- What commands can I use to verify the finding?
It is less useful as a replacement for the underlying monitoring system.
Linux should continue collecting the evidence.
The AI should help explain that evidence.
Security Considerations
There are several things to keep in mind.
Do not send secrets to the AI
Before sending logs to an external API, remove things such as:
Passwords
API keys
Private keys
Session tokens
Authorization headers
Database credentials
Personal information
Logs can contain more sensitive information than expected.
Keep the original logs
Do not replace your Linux logging system with the AI monitor.
The original logs are your evidence.
The AI-generated report is only an interpretation of that evidence.
Treat AI output as a recommendation
AI can misunderstand logs.
A message that looks suspicious may have a legitimate explanation, and a sophisticated attack may not look obviously suspicious.
Always verify important findings against the actual system.
Useful Linux Commands
Here are some commands worth knowing when building this type of monitor:
# View recent journal entries
journalctl -n 100
# View SSH logs
journalctl -u ssh
# View warnings and errors
journalctl -p warning..alert
# Search failed Audit events
ausearch --success no --interpret
# Search failed login events
ausearch -m USER_LOGIN --success no --interpret
# Generate login reports
aureport --login --summary -i
# Show listening ports
ss -tulpn
# Show logged-in users
who
# Show recent login history
last
The exact service names and available log sources vary between Linux distributions.
Conclusion
An AI-powered Linux security monitor does not need to be complicated.
The useful approach is to build it in layers:
Linux logs
↓
Collect events
↓
Filter important events
↓
Add context
↓
AI analysis
↓
Human-readable report
The important part is not making the AI perform every security task.
The important part is giving the AI good security data and using it to reduce the amount of time required to understand that data.
Start with SSH authentication events and system warnings. Once that works reliably, add Audit events, service failures, privilege changes, listening ports, and historical comparisons.
That gives you a practical security monitor without trying to build a full SIEM from scratch.
Related DevStackIO Resources
- Run an Open-Weight LLM on Ubuntu With Ollama — Install the local model used in Option 1 above
- How to Protect Git Repositories From AI Agent Abuse — Never let the triage AI execute commands — enforce the same agent boundaries
- AI Impact on Linux Kernel Updates — How AI is changing the Linux auditing landscape
External Resources
- Linux Audit documentation and examples: Red Hat’s Auditing the System
ausearchand Audit log searching: Red Hat’s Searching the Audit Log Files- Audit reporting with
aureport: Red Hat’s Creating Audit Reports - systemd documentation: systemd
Related Tools
Try these companion tools on DevStackIO Tools:
- hash generator — generate integrity hashes for security monitoring.