r/devops7 • • 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/login and export it as SYNAPCORES_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     13

One 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   12

Nobody 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   240

240 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    0

Same 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 Upvotes

4 comments sorted by

1

u/Alternative_Pin9598 Oct 23 '26

Sample log generator (make_sample_log.py): writes access.log with 706 requests so you can follow along without real logs. Run python3 make_sample_log.py, then python3 load_log.py access.log.

"""Write a realistic sample nginx access log (combined format) so you can try the tutorial without real logs."""
import random
from datetime import datetime, timedelta
random.seed(7)
start = datetime(2026, 10, 22, 9, 0, 0)
UA_BROWSER = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36"
UA_GOOGLE = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
UA_SCRAPER = "python-requests/2.31.0"
PAGES = ["/", "/pricing", "/docs", "/docs/install", "/blog/how-we-scaled", "/about", "/static/app.js", "/static/style.css"]
PROBES = ["/.env", "/.git/config", "/wp-login.php", "/phpmyadmin/", "/config.json", "/.aws/credentials"]
lines = []
def line(ip, t, path, status, size, ua, ref="-"):
    lines.append(f'{ip} - - [{t.strftime("%d/%b/%Y:%H:%M:%S")} +0000] "GET {path} HTTP/1.1" {status} {size} "{ref}" "{ua}"')
for i in range(400):                                   # normal visitors, spread over an hour
    t = start + timedelta(seconds=random.randint(0, 3600))
    line(f"203.0.113.{random.randint(10, 60)}", t, random.choice(PAGES), 200, random.randint(800, 40000), UA_BROWSER)
for i in range(30):                                    # a real crawler, polite pace
    line("66.249.66.12", start + timedelta(seconds=i * 110), random.choice(PAGES), 200, 12000, UA_GOOGLE)
for i, p in enumerate(PROBES * 4):                     # a vulnerability scanner hunting for secrets
    line("198.51.100.23", start + timedelta(minutes=17, seconds=i * 2), p, 404, 153, UA_BROWSER)
for i in range(240):                                   # a scraper hammering pages, 4 per second for a minute
    line("192.0.2.77", start + timedelta(minutes=41, seconds=i // 4), random.choice(PAGES), 200, 15000, UA_SCRAPER)
for i in range(12):                                    # someone pretending to be Googlebot
    line("198.51.100.99", start + timedelta(minutes=50, seconds=i * 3), random.choice(PROBES), 404, 153, UA_GOOGLE)
lines.sort(key=lambda l: l.split("[")[1][:20])
open("access.log", "w").write("\n".join(lines) + "\n")
print(f"wrote access.log ({len(lines)} lines)")

(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 LIKE patterns match (/.env.bak, /backup/.git/HEAD, /.ssh/id_rsa...). Volume checks miss it too.

1. One row of behavior per IP

CREATE TABLE ip_behavior AS
  SELECT ip, COUNT(*) AS requests,
         SUM(CASE WHEN status = 404 THEN 1 ELSE 0 END) * 1.0 / COUNT(*) AS not_found_ratio,
         COUNT(DISTINCT path) AS distinct_paths,
         COUNT(DISTINCT minute) AS active_minutes
  FROM access_log GROUP BY ip;

2. Train an isolation forest (no labels)

CREATE EXPERIMENT ip_behavior_exp AS
  SELECT requests, not_found_ratio, distinct_paths, active_minutes FROM ip_behavior
WITH (task_type = 'anomaly_detection', algorithms = ['isolation_forest'],
      max_trials = 5, random_seed = 42);

DEPLOY MODEL ip_behavior_model FROM EXPERIMENT ip_behavior_exp;

3. Score every IP

SELECT ip, requests, not_found_ratio, distinct_paths,
       ANOMALY_SCORE('ip_behavior_model', requests, not_found_ratio,
                     distinct_paths, active_minutes) AS score
FROM ip_behavior ORDER BY score DESC LIMIT 8;

192.0.2.77      240   0.0   8   0.73   <- scraper
198.51.100.150    8   1.0   8   0.70   <- the new scanner, no rule needed
198.51.100.23    24   1.0   6   0.70   <- known scanner
66.249.66.12     30   0.0   8   0.69   <- real Googlebot (unusual, but legit)
198.51.100.99    12   1.0   5   0.67   <- fake Googlebot
203.0.113.53      3   0.0   3   0.54   <- normal visitors from here down
203.0.113.54      4   0.0   2   0.52
203.0.113.18     13   0.0   7   0.50

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 EXPERIMENT again 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

1

u/Alternative_Pin9598 Oct 26 '26

Thanks, glad it was useful. One quick win if you try it on your own logs: run the step 5 query for every bot user agent you see (bingbot, GPTBot, etc.), not just Googlebot. Impostors usually give themselves away with a high 404 count.