#!/usr/bin/env python3 """botsum: summarise an nginx access log into counts. Nothing leaves your server. Usage: python3 botsum.py /var/log/nginx/access.log [access.log.1 access.log.2.gz ...] zcat access.log.*.gz | python3 botsum.py - Reads the default nginx "combined" log format, prints a short summary and writes botsum.json next to you. The JSON holds counts only: no IP addresses, no URLs, no referrers, no cookies. User agents appear only as a family ("Chrome 109 / Windows", "GPTBot"). Open the file in any editor before you upload it. The script makes no network requests and needs nothing but Python 3.6+. How visitors are sorted (heuristics, version 1): search_ads user agent says it is a search or ad crawler (Googlebot, AdsBot, Mediapartners-Google, Google-Display-Ads-Bot, bingbot, YandexBot...). Not verified by DNS. ai user agent says it is an AI crawler (GPTBot, ClaudeBot, Bytespider...) other_declared any other self-declared bot, script or library; empty user agent no_render looks like a browser but never asked for a single page file (css, js, image, ajax call): 3+ pages from one address, or one of the signals below without page files. Only when your log has such files at all. render_suspect looks like a browser, loads page files and shows one of the signals below. These are the ones that can load ads. human_like everything else that opened at least one page Addresses that look like a browser but never opened a page (page files only, redirects, errors) are not visitors: they are counted apart as "no_pages", with how many of them send the same user agents as the waves. A wave that fetches the page and its files from different addresses shows up there. Signals ("why" in the file). Most bot waves that hurt ad revenue come through thousands of home addresses, one page each, so per-address counts alone miss them: old_version browser ~20 releases behind your other visitors full_build desktop Chrome with a full build number (real ones send NNN.0.0.0) equal_counts 5+ different user agents with almost exactly the same page counts search_referrer says it came from google.*/search?q=... (Google does not send that) home_referrer says it came from your home page but never opened it stale_version a browser 3+ releases behind that outnumbers the current one on the same system one_page_wave a user agent whose addresses, unlike your other visitors, load no page files many_pages 200+ pages a day from one address What this version cannot see: bots on a current browser that load pages in full and differ only in headers (Sec-CH-UA, Accept-Language). They need a longer log format than "combined". """ import collections import gzip import json import re import sys import time VERSION = 1 LINE = re.compile(r'(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+)[^"]*" (\d{3}) \S+ "([^"]*)" "([^"]*)"') ASSET = {"css", "js", "mjs", "png", "jpg", "jpeg", "gif", "svg", "webp", "avif", "ico", "woff", "woff2", "ttf", "otf", "eot", "map", "mp4", "webm", "mp3"} NOT_PAGE = {"xml", "txt", "json", "rss", "atom", "pdf", "zip", "gz"} XHR = re.compile(r"/(?:ajax|api|wp-json)/|/admin-ajax\.php$") # asked for by page scripts: counts as a page file SEARCH_ADS = re.compile(r"googlebot|adsbot-google|mediapartners-google|google-display-ads-bot|google-adwords|" r"google-inspectiontool|storebot-google|googleother|bingbot|adidxbot|yandex\w*bot|" r"yandeximages|yandexdirect|yadirectfetcher|yandexadnet|yandexrca|yandexpartner|" r"yandexmetrika|yandexwebmaster|duckduckbot|applebot|baiduspider|" r"facebookexternalhit|twitterbot|pinterestbot|mail\.ru_bot", re.I) AI = re.compile(r"gptbot|chatgpt-user|oai-searchbot|claudebot|claude-user|claude-web|claude-searchbot|" r"anthropic-ai|perplexitybot|perplexity-user|ccbot|bytespider|amazonbot|meta-externalagent|" r"exasearchbot|exabot|diffbot|cohere-ai|youbot|petalbot|imagesiftbot|timpibot", re.I) DECLARED = re.compile(r"bot\b|bot/|crawl|spider|slurp|fetch|monitor|curl|wget|python|go-http|okhttp|java/|" r"libwww|scrapy|headless|phantom|axios|node|httpclient|feed|preview|scan|check|" r"archive|uptime|lighthouse", re.I) FULL_BUILD = re.compile(r"Chrome/(\d+)\.0\.[1-9]\d*\.\d+") SEARCH_REF = re.compile(r"https?://(?:www\.)?google\.[a-z.]{2,7}/search\?", re.I) REF = re.compile(r"https?://(?:www\.)?([^/:?#]+)(?::\d+)?(/[^?#]*)?", re.I) ROOT = {"/", "/index.php", "/index.html"} WORD = re.compile(r"[A-Za-z0-9_.\-]") MONTHS = {m: "%02d" % (i + 1) for i, m in enumerate("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split())} OLD_BY = 20 # browser releases behind the newest common one FIREFOX_ESR = {115, 128, 140} # long-support releases people really use HEAVY = 200 # pages a day from one address + user agent MIN_PAGES = 3 # pages from one address before "never loads page files" counts on its own GROUP = 30 # addresses before a user agent is judged as a group EQUAL = 5 # user agents with page counts within 5% of each other STALE_BY = 3 # releases behind before a version that outnumbers the current one counts as a wave STALE_MIN = 100 # addresses on that version TOP = 15 PAGES, FILES, OTHER, HOURS, HOME_REF, SAW_HOME, FAKE_REF, ERRORS = range(8) def opener(path): if path == "-": return sys.stdin if path.endswith(".gz"): return gzip.open(path, "rt", encoding="utf-8", errors="replace") return open(path, encoding="utf-8", errors="replace") def kind(method, path, status): name = path.rsplit("/", 1)[-1] ext = name.rsplit(".", 1)[-1].lower() if "." in name else "" if ext in ASSET or XHR.search(path): return "asset" if method == "GET" and status in ("200", "304") and ext not in NOT_PAGE: return "page" return "other" def browser(ua): """('Chrome', 109, 'Windows') for a browser-like user agent, else None.""" if not ua.startswith("Mozilla/"): return None name, ver = "Other", 0 for label, pat in (("Edge", r"Edg[A-Z]*/(\d+)"), ("Opera", r"OPR/(\d+)"), ("Yandex", r"YaBrowser/(\d+)"), ("Chrome", r"(?:Chrome|CriOS)/(\d+)"), ("Firefox", r"(?:Firefox|FxiOS)/(\d+)"), ("Safari", r"Version/(\d+)[\d.]* (?:Mobile/\S+ )?Safari")): m = re.search(pat, ua) if m: name, ver = label, int(m.group(1)) break os_ = "Other" for label, pat in (("Android", "Android"), ("iOS", "iPhone|iPad"), ("Windows", "Windows"), ("macOS", "Mac OS X"), ("Linux", "Linux|X11")): if re.search(pat, ua): os_ = label break return name, ver, os_ def family(b): return "%s %s / %s" % (b[0], b[1] or "?", b[2]) def full_build(ua, b): """Desktop Chrome has sent 'Chrome/NNN.0.0.0' since version 110; a full build number there is made up.""" if b[2] not in ("Windows", "macOS", "Linux") or "Electron" in ua: return False m = FULL_BUILD.search(ua) return bool(m) and int(m.group(1)) >= 110 def bot_name(ua, rx): """The word of the user agent that gave the bot away: 'Googlebot-Image', 'python-requests'.""" if not ua or ua == "-": return "(empty user agent)" m = rx.search(ua) if not m: return ua.split("/")[0][:32] a, b = m.start(), m.end() while a > 0 and WORD.match(ua[a - 1]): a -= 1 while b < len(ua) and WORD.match(ua[b]): b += 1 return ua[a:b].strip("/")[:32] def net(ip): if ":" in ip: return ":".join(ip.split(":")[:4]) return ip.rsplit(".", 1)[0] def main(paths): # client = address + user agent; value: pages, page files, other requests, {hour: pages}, # host of a "came from the home page" referrer, opened the home page, fake search referrer, # other requests answered 4xx or 5xx clients = {} lines = skipped = 0 first = last = None ref_hosts = collections.Counter() # hosts of referrers with a path: internal navigation, so the site itself for path in paths: with opener(path) as f: for line in f: lines += 1 m = LINE.match(line) if not m: skipped += 1 continue ip, tl, method, url, status, ref, ua = m.groups() try: hour = "%s-%s-%s %s" % (tl[7:11], MONTHS[tl[3:6]], tl[0:2], tl[12:14]) except KeyError: skipped += 1 continue if first is None or hour < first: first = hour if last is None or hour > last: last = hour c = clients.get((ip, ua)) if c is None: c = clients[(ip, ua)] = [0, 0, 0, {}, None, False, False, 0] url = url.split("?", 1)[0] k = kind(method, url, status) if url in ROOT: c[SAW_HOME] = True if len(ref) > 1: r = REF.match(ref) if r and (r.group(2) or "/") != "/": ref_hosts[r.group(1).lower()] += 1 elif r and k == "page" and url not in ROOT: c[HOME_REF] = sys.intern(r.group(1).lower()) if k == "page": c[PAGES] += 1 c[HOURS][hour] = c[HOURS].get(hour, 0) + 1 if SEARCH_REF.match(ref): c[FAKE_REF] = True elif k == "asset": c[FILES] += 1 else: c[OTHER] += 1 if status >= "400": c[ERRORS] += 1 if not clients: sys.exit("no lines in nginx combined format found (%d read, %d skipped)" % (lines, skipped)) days = max(1, (len({h[:10] for c in clients.values() for h in c[HOURS]}) or 1)) own = {h for h, n in ref_hosts.items() if n * 10 >= sum(ref_hosts.values())} # which browser version counts as current: the newest one used by at least 0.2% of clients of that browser seen = collections.defaultdict(collections.Counter) parsed = {} ua_clients, ua_nofiles, ua_pages = collections.Counter(), collections.Counter(), collections.Counter() on_os = collections.defaultdict(collections.Counter) # (browser, system) -> {version: addresses} for (ip, ua), c in clients.items(): if ua not in parsed: declared = SEARCH_ADS.search(ua) or AI.search(ua) or DECLARED.search(ua) or not ua or ua == "-" parsed[ua] = None if declared else browser(ua) b = parsed[ua] if not b: continue if b[1]: seen[b[0]][b[1]] += 1 if c[PAGES]: ua_clients[ua] += 1 ua_pages[ua] += c[PAGES] ua_nofiles[ua] += not c[FILES] if b[1]: on_os[(b[0], b[2])][b[1]] += 1 current = {} for name, vers in seen.items(): total = sum(vers.values()) common = [v for v, n in vers.items() if n >= 5 and n * 500 >= total] current[name] = max(common) if common else max(vers) br_assets = sum(c[FILES] for (ip, ua), c in clients.items() if parsed[ua]) br_pages = sum(c[PAGES] for (ip, ua), c in clients.items() if parsed[ua]) # page files are in the log: at least one per 20 pages, and some group of visitors mostly loads them shares = [ua_nofiles[u] / n for u, n in ua_clients.items() if n >= GROUP] base = min(shares) if shares else None assets_logged = br_assets * 20 >= br_pages and (base is None or base <= 0.4) # one_page_wave: a user agent whose addresses skip page files far more often than the best-behaved group wave_at = min(0.8, max(0.5, 3 * (base or 0))) wave_uas = {u for u, n in ua_clients.items() if assets_logged and n >= GROUP and ua_nofiles[u] >= wave_at * n} # equal_counts: 5+ user agents, each with 1%+ of browser pages, page counts within 5% of each other big = sorted(((n, u) for u, n in ua_pages.items() if n >= 100 and n * 100 >= br_pages), reverse=True) equal_uas = set() for i in range(len(big)): j = i while j + 1 < len(big) and big[i][0] <= big[j + 1][0] * 1.05: j += 1 if j - i + 1 >= EQUAL: equal_uas.update(u for n, u in big[i:j + 1]) # stale_version: browsers update themselves, so people cluster on the current release and the one before; # an older release with more addresses than those two on the same system is not people. Safari is left out: # its version follows the system, and people do stay on old systems stale = set() for (name, os_), vers in on_os.items(): cur = current.get(name, 0) if name in ("Safari", "Other") or not cur: continue fresh = vers[cur] + vers[cur - 1] for v, n in vers.items(): if v <= cur - STALE_BY and n >= STALE_MIN and n > fresh and not (name == "Firefox" and v in FIREFOX_ESR): stale.add((name, v, os_)) classes = collections.defaultdict(lambda: {"clients": 0, "pages": 0, "requests": 0}) signals = collections.defaultdict(lambda: {"clients": 0, "pages": 0}) no_pages = {"clients": 0, "one_request": 0, "files": 0, "errors": 0, "other": 0, "wave_agents": 0} hours = collections.defaultdict(lambda: collections.Counter()) sig = {} full = {} for (ip, ua), c in clients.items(): pages, assets, other, by_hour = c[:4] b = parsed[ua] why = [] if b is None: if SEARCH_ADS.search(ua): cls, name = "search_ads", bot_name(ua, SEARCH_ADS) elif AI.search(ua): cls, name = "ai", bot_name(ua, AI) else: cls, name = "other_declared", bot_name(ua, DECLARED) else: name = family(b) if ua not in full: full[ua] = full_build(ua, b) if b[1] and b[1] <= current.get(b[0], 0) - OLD_BY and not (b[0] == "Firefox" and b[1] in FIREFOX_ESR): why.append("old_version") if full[ua]: why.append("full_build") if ua in equal_uas: why.append("equal_counts") if c[FAKE_REF]: why.append("search_referrer") if c[HOME_REF] in own and not c[SAW_HOME]: why.append("home_referrer") if b in stale: why.append("stale_version") if ua in wave_uas and pages and not assets: why.append("one_page_wave") if pages >= HEAVY * days: why.append("many_pages") if assets_logged and pages >= MIN_PAGES and assets == 0: cls = "no_render" elif why and pages: cls = "render_suspect" if assets or not assets_logged else "no_render" elif not pages: # never opened a page: not a visitor, so not in the classes no_pages["clients"] += 1 no_pages["one_request"] += assets + other == 1 no_pages["files"] += assets no_pages["errors"] += c[ERRORS] no_pages["other"] += other - c[ERRORS] no_pages["wave_agents"] += b in stale or ua in wave_uas if assets >= 20: signals["files_without_pages"]["clients"] += 1 continue else: cls = "human_like" if assets_logged and pages == 1 and not assets: signals["one_page_no_files_unsorted"]["clients"] += 1 signals["one_page_no_files_unsorted"]["pages"] += 1 k = classes[cls] k["clients"] += 1 k["pages"] += pages k["requests"] += pages + assets + other for h, n in by_hour.items(): hours[h][cls] += n if cls != "human_like": for w in why: signals[w]["clients"] += 1 signals[w]["pages"] += pages s = sig.get((cls, name)) if s is None: s = sig[(cls, name)] = {"class": cls, "name": name, "clients": 0, "pages": 0, "requests": 0, "_why": set(), "_nets": set(), "_hours": collections.Counter()} s["clients"] += 1 s["pages"] += pages s["requests"] += pages + assets + other s["_why"].update(why) s["_nets"].add(net(ip)) s["_hours"].update(by_hour) top = sorted(sig.values(), key=lambda s: (-s["pages"], -s["requests"]))[:TOP] for s in top: hs = s.pop("_hours") s["why"] = sorted(s.pop("_why")) s["networks"] = len(s.pop("_nets")) s["hours_active"] = len(hs) if hs: s["first_hour"], s["last_hour"] = min(hs), max(hs) s["peak_hour"], s["peak_pages"] = max(hs.items(), key=lambda x: x[1]) pages_total = sum(k["pages"] for k in classes.values()) out = { "botsum": VERSION, "made": time.strftime("%Y-%m-%d"), "from_hour": first, "to_hour": last, "lines": lines, "skipped": skipped, "pages": pages_total, "assets_logged": assets_logged, "current_browsers": current, "classes": dict(classes), "no_pages": no_pages, "signals": dict(signals), "hours": [[h, dict(hours[h])] for h in sorted(hours)], "top": top, } with open("botsum.json", "w", encoding="utf-8") as f: json.dump(out, f, ensure_ascii=False, indent=1) print("log: %s .. %s, %d lines (%d not in combined format)" % (first, last, lines, skipped)) if not assets_logged: print("note: css/js/image requests are not in this log (CDN?), so 'no_render' is not used") print("%-16s %10s %10s %7s" % ("class", "clients", "pages", "pages%")) for cls in ("human_like", "render_suspect", "no_render", "ai", "search_ads", "other_declared"): k = classes.get(cls) if k: print("%-16s %10d %10d %6.1f%%" % (cls, k["clients"], k["pages"], 100.0 * k["pages"] / max(pages_total, 1))) if no_pages["clients"]: print("%-16s %10d (%d page files, %d errors, %d other requests; %d on the user agents of the waves)" % ( "no pages at all", no_pages["clients"], no_pages["files"], no_pages["errors"], no_pages["other"], no_pages["wave_agents"])) for w, k in sorted(signals.items(), key=lambda x: -x[1]["pages"]): print("signal %-26s %8d clients %8d pages" % (w, k["clients"], k["pages"])) print("wrote botsum.json (counts only: no IPs, no URLs). Look inside, then upload it for the full report.") if __name__ == "__main__": if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"): sys.exit(__doc__) main(sys.argv[1:])