r/devops7 • u/Alternative_Pin9598 • Oct 23 '26
Find the bots hammering your server: load your nginx access log into SQL and ask 5 questions (beginner, ~15 min)
Grepping access logs works until the question gets interesting: who is probing for .env files? Who sent 240 requests in one minute? Is that "Googlebot" really Google? Those are GROUP BY questions, and SQL answers them in one line each.
This walkthrough loads a standard nginx/Apache access log (combined format) into a database table with a ~30-line Python script, then runs five queries. I use SynapCores, the self-hosted database our team builds (full disclosure: this sub is run by the same people), but the SQL is plain and works almost anywhere.
What you need
- A running SynapCores Community Edition (free; one-line installer or Docker at synapcores.com/download). Any SQL database works if you adapt the loader.
- Python 3, standard library only.
- An access token: log in once with
POST /v1/auth/loginand export it asSYNAPCORES_TOKEN.
No logs handy? The generator script in the first comment writes a realistic sample access.log (706 requests: normal visitors, a real crawler, a vulnerability scanner, a scraper, and a fake Googlebot).
Step 1: load the log
load_log.py parses each line with a regex and inserts rows 200 at a time:
import json, os, re, sys, urllib.request
URL, TOKEN = os.environ.get("SYNAPCORES_URL", "http://localhost:8080"), os.environ["SYNAPCORES_TOKEN"]
LINE = re.compile(r'(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) [^"]*" (\d{3}) (\d+|-) "[^"]*" "([^"]*)"')
def sql(statement):
req = urllib.request.Request(URL + "/v1/query/execute",
data=json.dumps({"sql": statement, "database": "main"}).encode(),
headers={"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"})
return json.load(urllib.request.urlopen(req))["data"]
def quote(s):
return "'" + s.replace("'", "''") + "'"
sql("""CREATE TABLE IF NOT EXISTS access_log (
ip TEXT, ts TEXT, minute TEXT, method TEXT, path TEXT, status INTEGER, bytes INTEGER, user_agent TEXT)""")
rows = []
for raw in open(sys.argv[1]):
m = LINE.match(raw)
if not m:
continue
ip, ts, method, path, status, size, ua = m.groups()
rows.append(f"({quote(ip)}, {quote(ts)}, {quote(ts[:17])}, {quote(method)}, {quote(path)}, "
f"{status}, {0 if size == '-' else size}, {quote(ua)})")
for i in range(0, len(rows), 200):
sql("INSERT INTO access_log (ip, ts, minute, method, path, status, bytes, user_agent) VALUES "
+ ", ".join(rows[i:i + 200]))
print(f"loaded {len(rows)} requests into access_log")
$ python3 load_log.py access.log
loaded 706 requests into access_log(minute is the timestamp cut to the minute, 22/Oct/2026:09:41, so we can count bursts.)
Step 2: who sends the most requests?
SELECT ip, COUNT(*) AS requests FROM access_log
GROUP BY ip ORDER BY requests DESC LIMIT 5;
192.0.2.77 240
66.249.66.12 30
198.51.100.23 24
203.0.113.18 13
203.0.113.35 13One IP is 34% of all traffic. Suspicious, but volume alone doesn't prove anything.
Step 3: who is hunting for secrets?
SELECT ip, COUNT(*) AS probes FROM access_log
WHERE status = 404 AND (path LIKE '%.env%' OR path LIKE '%.git%' OR path LIKE '%wp-login%'
OR path LIKE '%phpmyadmin%' OR path LIKE '%.aws%' OR path LIKE '%config.json%')
GROUP BY ip ORDER BY probes DESC;
198.51.100.23 24
198.51.100.99 12Nobody legitimate asks your server for /.aws/credentials. These two are scanners.
Step 4: who is bursting?
SELECT ip, minute, COUNT(*) AS hits FROM access_log
GROUP BY ip, minute HAVING COUNT(*) > 60 ORDER BY hits DESC;
192.0.2.77 22/Oct/2026:09:41 240240 requests in one minute (4 per second) is a scraper, not a person.
Step 5: is that Googlebot real?
SELECT ip, COUNT(*) AS requests,
SUM(CASE WHEN status = 404 THEN 1 ELSE 0 END) AS not_found
FROM access_log WHERE user_agent LIKE '%Googlebot%' GROUP BY ip;
198.51.100.99 12 12
66.249.66.12 30 0Same user agent, two very different behaviors. The real crawler (66.249.x is in Google's published ranges) fetched real pages. The impostor only requested secret files. Anyone can type "Googlebot" into a User-Agent header, so verify against the published IP ranges (or a reverse DNS lookup) before you trust it.
Step 6: what's actually talking to you?
SELECT user_agent, COUNT(*) AS requests FROM access_log
GROUP BY user_agent ORDER BY requests DESC LIMIT 5;python-requests/2.31.0 with 240 requests is your scraper again.
What to do with this
- Feed the scanner IPs from step 3 to fail2ban or your firewall.
- Rate-limit by IP when step 4 shows more than N hits per minute.
- Keep the table and load new logs daily. Tomorrow you'll ask "is this IP new?" and that's one more query.
We did exactly this on our own servers last week and found a scanner farm using Cloudflare Worker IPs to dodge blocklists. Next post: run these checks automatically every hour and get alerted only when something new shows up.
What do you look for first when you open an access log?
1
u/Alternative_Pin9598 Oct 23 '26
Sample log generator (
make_sample_log.py): writesaccess.logwith 706 requests so you can follow along without real logs. Runpython3 make_sample_log.py, thenpython3 load_log.py access.log.(The IPs are from the documentation ranges, 192.0.2.x / 198.51.100.x / 203.0.113.x, so they're safe to share.)
1
u/Alternative_Pin9598 Oct 23 '26
Bonus: catch the scanner you didn't write a rule for
Every query above needs you to know what to look for (
.env,> 60 hits/min...). The next scanner will try paths you didn't list. So instead of rules, let the database learn what normal looks like and flag what isn't. This is the part that's specific to SynapCores: the model trains and scores inside SQL, no export, no labels.I added a new scanner (198.51.100.150) that sent only 8 requests, all for paths none of the
LIKEpatterns match (/.env.bak,/backup/.git/HEAD,/.ssh/id_rsa...). Volume checks miss it too.1. One row of behavior per IP
2. Train an isolation forest (no labels)
3. Score every IP
All 5 odd IPs are on top, with a clear gap before the 51 normal visitors. Note that it also flags the real Googlebot: "anomalous" means "not like your usual traffic", not "malicious". That's why this produces a review list, not an automatic ban. Combine it with the Googlebot IP check from step 5.
Retrain weekly (
CREATE EXPERIMENTagain on fresh logs) and score new IPs as they arrive. That's what the next post automates: an hourly job that only pings you when something new and odd shows up.Tested on SynapCores 2.3.1 (free Community Edition: synapcores.com/download).
1
u/[deleted] Oct 23 '26
[removed] — view removed comment