A while back I wrote about an AI agent for GitLab CI/CD pipelines. This one is a smaller idea from the same hobby list: an agent that keeps an eye on a website running on Nginx on an AWS EC2 instance.
If you have ever opened the access log of a public server, you know what it looks like. Within minutes of the server going live, bots start asking for /.env, /wp-login.php and /.git/config, even when the site has nothing to do with WordPress or PHP. Real errors get buried somewhere in between. The logs have all the information. Nobody has the time to read them.
So I wanted something that reads the logs for me every 15 minutes and tells me, in a few lines, how many requests came in, whether anyone is attacking the site, and whether anything is broken. I also wanted it to run fully on the server with open source tools, with no paid API and no log data going out of the machine.
What the agent does

Every 15 minutes a Python script picks up the new entries from the Nginx access log and error log. It counts the requests, status codes and the busiest IPs, and checks each request against a small set of attack patterns (SQL injection, path traversal, XSS, command injection, probes for sensitive files, and well-known scanner tools). The result is a compact JSON summary.
That summary is then given to a small LLM running locally through Ollama. The model writes a short report with a health status (OK, WARNING or CRITICAL), what the traffic looked like, any attacks, any errors and what to do about them. The report goes into a log file, and to Slack if you want.
You might ask why not just give the raw logs to the LLM and let it figure everything out. I tried to keep the LLM away from the parts that regex can do better. Counting and pattern matching are cheap and give the same answer every time. A small model reading thousands of raw log lines is slow, and it starts making up numbers. So the code does the counting, and the model only does the part it is actually good at, which is explaining what the numbers mean.
What you need
The stack is simple: Ollama to run the model, Llama 3.2 3B as the model, Python 3 with the ollama library, and cron. Everything else in the script comes from the Python standard library.
On the server side, this is what I would plan for:
| Item | Requirement |
|---|---|
| OS | Ubuntu 22.04 / 24.04 or Amazon Linux 2023 (x86_64 or ARM64/Graviton) |
| Python | 3.9 or newer |
| Nginx | Default combined access log format |
| vCPU | 2 minimum, 4 if you want faster reports |
| Disk | 20 GB gp3 is enough |
| GPU | Not needed |
| Ports | Nothing new. Do not open 11434 (Ollama) in the security group. |
| Outbound | HTTPS, to install Ollama, pull the model and post to Slack |
| IAM role | Not needed for this version |
RAM depends on the model you choose. This is roughly how I would size it:
| Model | Download | Instance RAM | Example instance |
|---|---|---|---|
qwen2.5:1.5b | ~1 GB | 4 GB | t3.medium |
llama3.2:3b | ~2 GB | 8 GB | t3.large / m7g.large |
llama3.1:8b | ~4.9 GB | 16 GB | t3.xlarge / m7g.xlarge |
I went with llama3.2:3b as the middle ground. Smaller models tend to write thinner reports, and the 8B model is slow on a CPU for something that runs every 15 minutes. If your application already uses most of the memory on the box, either add the model’s RAM on top of what you have, or run Ollama on a separate small instance and point the script to it.
How heavy is it?
This was my first question too, because nobody wants a monitoring tool that slows down the website it is monitoring. The numbers below are my estimates for the 3B model on a 2 to 4 vCPU instance, so please check them on your own server with top and ollama ps.
The Python part is very light. It reads the log line by line, so it stays under 50 MB of RAM and finishes in a second or two for a normal daily log. The model is the expensive part. While it is loaded it takes about 3 GB of RAM, and for 30 to 90 seconds it will use almost all of your CPU. Ollama unloads the model after 5 minutes of no activity, so the memory comes back between runs. Averaged over an hour, that works out to around 5 to 10% CPU, which fits within the baseline of a t3.large. On disk, Ollama takes about 2 GB, the model another 2 GB, and the report log grows by around 10 MB a month.
The CPU spike is the one thing I would not ignore on a production server. A systemd override for Ollama (sudo systemctl edit ollama) makes sure Nginx always gets the CPU first:
[Service]
Nice=10
CPUQuota=150%
This limits Ollama to 1.5 vCPUs. The report takes a bit longer, which nobody will notice. Run sudo systemctl daemon-reload && sudo systemctl restart ollama to apply it. If you are on a T-series instance with a busy site, also keep an eye on CPU credits, or move to an m-series instance.
Setting it up
Install Ollama and pull the model. The install script also creates a systemd service for it.
curl -fsSL https://ollama.com/install.sh | sh
ollama pull llama3.2:3b
Ollama listens on 127.0.0.1:11434 by default and its API has no authentication. Leave it on localhost.
Next, create a virtual environment for the script:
mkdir -p ~/nginx-agent && cd ~/nginx-agent
python3 -m venv venv
./venv/bin/pip install ollama
The script needs to read the Nginx logs. On Ubuntu the logs belong to the adm group, so add your user to it and log in again:
sudo usermod -aG adm ubuntu
On Amazon Linux the log directory is root-only. There you can either run the script from root’s crontab or change the permissions on /var/log/nginx.
The code
Save this as ~/nginx-agent/nginx_agent.py. It expects the default combined log format. If you have a custom log_format, you will need to change LOG_PATTERN.
#!/usr/bin/env python3
"""nginx_agent.py - a simple AI agent that monitors an Nginx web server."""
import json
import os
import re
import urllib.request
from collections import Counter
from datetime import datetime, timedelta, timezone
from urllib.parse import unquote
import ollama
ACCESS_LOG = "/var/log/nginx/access.log"
ERROR_LOG = "/var/log/nginx/error.log"
WINDOW_MINUTES = 15
MODEL = os.getenv("AGENT_MODEL", "llama3.2:3b")
# Nginx default "combined" log format
LOG_PATTERN = re.compile(
r'(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] '
r'"(?P<method>\S+) (?P<path>\S+) \S+" (?P<status>\d{3}) (?P<size>\d+|-) '
r'"(?P<referer>[^"]*)" "(?P<agent>[^"]*)"'
)
TIME_PATTERN = re.compile(r"\[(?P<time>[^\]]+)\]")
# Simple signatures for common attacks (checked on the URL-decoded path)
SUSPICIOUS = {
"sql_injection": re.compile(r"(union\s+select|or\s+1=1|sleep\(|information_schema)", re.I),
"path_traversal": re.compile(r"(\.\./|/etc/passwd)", re.I),
"xss": re.compile(r"(<script|javascript:|onerror=)", re.I),
"sensitive_files": re.compile(r"(/\.env|/\.git|wp-login\.php|phpmyadmin|xmlrpc\.php|\.aws/)", re.I),
"command_injection": re.compile(r"(;\s*wget|;\s*curl|\|\s*sh|/bin/bash|cmd=)", re.I),
}
SCANNER_AGENTS = re.compile(r"(sqlmap|nikto|nmap|masscan|zgrab|nuclei|gobuster|dirbuster)", re.I)
def parse_time(value):
return datetime.strptime(value, "%d/%b/%Y:%H:%M:%S %z")
def parse_access_log(path, since):
entries, malformed = [], 0
with open(path, errors="replace") as f:
for line in f:
match = LOG_PATTERN.match(line)
if not match:
# Lines that don't fit the format are often junk sent by bots
t = TIME_PATTERN.search(line)
if t and parse_time(t["time"]) >= since:
malformed += 1
continue
entry = match.groupdict()
if parse_time(entry["time"]) >= since:
entries.append(entry)
return entries, malformed
def read_error_log(path, since):
levels = ("[error]", "[crit]", "[alert]", "[emerg]")
errors = []
with open(path, errors="replace") as f:
for line in f:
try:
ts = datetime.strptime(line[:19], "%Y/%m/%d %H:%M:%S")
except ValueError:
continue
if ts >= since and any(level in line for level in levels):
errors.append(line.strip()[:300])
return errors
def build_summary(entries, malformed, errors):
status = Counter(e["status"] for e in entries)
threats = []
for e in entries:
path = unquote(e["path"])
for name, pattern in SUSPICIOUS.items():
if pattern.search(path):
threats.append({"type": name, "ip": e["ip"], "path": path[:200], "status": e["status"]})
if SCANNER_AGENTS.search(e["agent"]):
threats.append({"type": "scanner_user_agent", "ip": e["ip"],
"agent": e["agent"][:120], "status": e["status"]})
return {
"window_minutes": WINDOW_MINUTES,
"total_requests": len(entries),
"status_codes": dict(status),
"client_errors_4xx": sum(v for k, v in status.items() if k.startswith("4")),
"server_errors_5xx": sum(v for k, v in status.items() if k.startswith("5")),
"top_ips": Counter(e["ip"] for e in entries).most_common(5),
"top_paths": Counter(e["path"] for e in entries).most_common(5),
"malformed_requests": malformed,
"suspicious_requests": len(threats),
"threat_types": dict(Counter(t["type"] for t in threats)),
"threat_ips": Counter(t["ip"] for t in threats).most_common(5),
"threat_samples": threats[:15],
"nginx_errors": errors[-15:],
}
PROMPT = """You are an SRE assistant monitoring an Nginx web server on AWS EC2.
Below is a JSON summary of the last {window} minutes of traffic and errors.
Write a short report with these sections:
1. Health status: OK, WARNING or CRITICAL, and why
2. Traffic overview
3. Malicious activity: attack types, source IPs, and whether any look successful
(a suspicious request that got a 2xx status)
4. Errors and their likely causes
5. Recommended actions
Use only the facts in the data. Do not invent numbers.
DATA:
{data}"""
def ask_llm(summary):
response = ollama.chat(
model=MODEL,
messages=[{"role": "user", "content": PROMPT.format(
window=WINDOW_MINUTES, data=json.dumps(summary, indent=2))}],
# Room for the prompt plus the report; low temperature keeps it factual
options={"num_ctx": 4096, "temperature": 0.2},
)
return response["message"]["content"]
def notify(webhook_url, text):
body = json.dumps({"text": text}).encode()
req = urllib.request.Request(webhook_url, data=body,
headers={"Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=10)
def main():
window = timedelta(minutes=WINDOW_MINUTES)
now = datetime.now(timezone.utc)
entries, malformed = parse_access_log(ACCESS_LOG, now - window)
errors = read_error_log(ERROR_LOG, datetime.now() - window) # error log uses local time
summary = build_summary(entries, malformed, errors)
report = ask_llm(summary)
output = f"Nginx agent report - {now:%Y-%m-%d %H:%M} UTC\n\n{report}"
print(output)
webhook = os.getenv("SLACK_WEBHOOK_URL")
if webhook:
notify(webhook, output)
if __name__ == "__main__":
main()
How the code works
The script runs from top to bottom once and exits. Cron takes care of running it again. Here is a walk through the main parts.
Reading the access log
A line in the default Nginx format looks like this:
203.0.113.45 - - [03/Dec/2026:17:09:40 +0000] "GET /index.php?id=1 HTTP/1.1" 404 153 "-" "sqlmap/1.7"
LOG_PATTERN breaks this into named groups: IP, time, method, path, status, size, referer and user agent. parse_access_log() goes through the file one line at a time, converts every match into a dictionary with groupdict(), and keeps only the requests from the last 15 minutes. The timestamp in the access log has the timezone offset, so it can be compared directly with a UTC time.
Some lines will not match the pattern. These are usually bots sending binary junk, like a TLS handshake to port 80, which Nginx logs as a garbage request. I did not want to just skip them, because a sudden increase in these lines is itself a sign of scanning. So the script pulls out the timestamp separately and counts them as malformed. The file is opened with errors="replace", so a few invalid bytes in the log will not crash the script.
Reading the error log
The error log has a different format, with one small catch. Its timestamp (2026/12/03 17:09:40 [error]) has no timezone and is in the server’s local time. That is why main() uses local time for the error log and UTC for the access log. read_error_log() keeps only error, crit, alert and emerg lines and cuts each one to 300 characters. Warnings are skipped. They make the report noisy and rarely need action.
Spotting the bad requests
Before checking anything, build_summary() URL-decodes the path with unquote(). Attackers almost always encode their payloads, so %20UNION%20SELECT has to become UNION SELECT before a simple pattern can match it. The decoded path is then checked against the patterns in SUSPICIOUS:
- SQL injection:
UNION SELECT,OR 1=1,sleep(for time-based blind injection, andinformation_schema - Path traversal:
../and requests for/etc/passwd - XSS:
<script,javascript:andonerror= - Sensitive files:
.env,.git, AWS credentials, phpMyAdmin,wp-login.phpandxmlrpc.php - Command injection: commands chained with
;or|,/bin/bashandcmd=
The user agent is checked separately against common scanning tools like sqlmap, Nikto, Nmap, masscan, zgrab and Nuclei. One request can match more than one rule. A sqlmap request with an injection payload shows up twice, and that is fine.
For every match the script also keeps the status code, and I think this is the most useful field in the whole summary. A 404 on /.env means some bot tried and failed. A 200 on /.env means your environment file was just downloaded by a stranger. Those are very different situations, and the status code is the only thing that tells them apart.
To be honest about the limits: these are plain signatures. They will miss anything clever, and they can flag normal traffic if your application uses something like a cmd= parameter. Treat the list as a starting point and tune it for your own site.
The summary
All the counting is done with Counter. The script adds up 4xx and 5xx separately, since those two numbers tell you the most at a glance. It keeps only 15 threat samples and the last 15 errors. Without that limit, a heavy attack could make the prompt huge, and the LLM step would get slow at exactly the moment you need the report. For a window with a couple of attacks and a broken backend, the summary looks like this (shortened):
{
"window_minutes": 15,
"total_requests": 7,
"status_codes": {"200": 3, "404": 2, "400": 1, "502": 1},
"client_errors_4xx": 3,
"server_errors_5xx": 1,
"top_ips": [["198.51.100.7", 4], ["203.0.113.45", 2], ["192.0.2.10", 1]],
"malformed_requests": 0,
"suspicious_requests": 4,
"threat_types": {"sql_injection": 1, "scanner_user_agent": 1, "path_traversal": 1, "sensitive_files": 1},
"threat_ips": [["203.0.113.45", 3], ["192.0.2.10", 1]],
"threat_samples": [
{"type": "sql_injection", "ip": "203.0.113.45", "path": "/index.php?id=1 UNION SELECT password", "status": "404"},
{"type": "scanner_user_agent", "ip": "203.0.113.45", "agent": "sqlmap/1.7", "status": "404"}
],
"nginx_errors": [
"2026/12/03 17:09:40 [error] 1234#1234: *88 connect() failed (111: Connection refused) while connecting to upstream, ..."
]
}
The LLM part
ask_llm() puts this JSON into a prompt. The prompt tells the model it is an SRE assistant, asks for the same five sections every time, and has one rule that matters more than the rest: use only the facts in the data and do not invent numbers. Small models do invent numbers when you don’t say this. The prompt also tells the model that a suspicious request with a 2xx status may have succeeded, so it does not have to work that out on its own.
The call goes to Ollama on localhost:11434. I set two options. num_ctx is 4,096 tokens so a busy window’s summary and the report both fit in the context. temperature is 0.2 so the wording stays factual and similar from one run to the next. For the summary above, I would expect a good report to say that the attacks from 203.0.113.45 failed (404 and 400), connect the 502 with the connect() failed error, and point at the backend on port 8000 as the actual problem.
Sending the report
notify() posts the report as {"text": ...}, which is what a Slack incoming webhook expects. Mattermost accepts the same format. It uses urllib instead of requests to avoid one more dependency, and it has a 10-second timeout so a slow webhook does not leave cron jobs hanging around.
Running it
Run it once by hand first:
./venv/bin/python nginx_agent.py
If the report looks sensible, add it to cron with crontab -e. The schedule has to match WINDOW_MINUTES in the script, otherwise you will count some requests twice or miss some.
*/15 * * * * SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXX /home/ubuntu/nginx-agent/venv/bin/python /home/ubuntu/nginx-agent/nginx_agent.py >> /home/ubuntu/nginx-agent/agent.log 2>&1
Drop the SLACK_WEBHOOK_URL part if you only want the reports in agent.log. One small gap to be aware of: when logrotate rotates the Nginx logs, the first run after that only sees the new file, so you can lose a few minutes of data once a day. For this kind of report, I can live with that.
What I would add next
Right now the agent only reports. The obvious next step is to let it act, for example by adding a deny rule in Nginx or an entry in the AWS Network ACL for an IP that keeps attacking. I would still keep a human approval step there. I don’t want a 3B model blocking IPs on its own.
Two smaller improvements: post to Slack only when the status is WARNING or CRITICAL, so the channel doesn’t fill up with “all good” messages, and store each summary in SQLite so the agent can compare the current window with the last few hours and catch unusual spikes.
It also works well next to tools that already exist. fail2ban can do the automatic banning, and GoAccess gives you a live dashboard. The agent fills the gap between them by explaining what happened in plain words.
That’s it. Around 150 lines of Python, and you no longer have to open the access log every time you want to know what is going on with your server.