Finding IP localities in server logs
Server logs often mix useful network evidence with noise. A source address can help an administrator separate local traffic from an overseas scan, identify an unfamiliar cloud provider, or decide which event deserves attention first. Geographic data adds context, provided the result is treated as an estimate rather than proof of a person’s physical location.
Building a Python script that calculates the geographic locality of IP addresses from logs becomes useful when it extracts only valid public addresses, resolves each one against a local database, and produces a compact report. The same workflow can process web, authentication, and application logs while keeping raw records out of the final output.
Why locality belongs in log analysis
Locality helps answer operational questions that an IP address alone cannot. A sudden increase in requests from one country may indicate a distributed scan, while traffic from several Australian cities could reflect normal branch-office activity. The result gives investigators a useful first filter before examining request paths, user agents, or authentication failures.
For Australian administrators, this distinction matters. Requests reaching a server in Perth may originate from a local household, a national branch network, or an international content-delivery edge. Mapping can separate those patterns, but it cannot identify an individual or prove where a device was physically used.
Preparing logs and mapping data
Start with representative samples of the logs being analysed. Apache common and combined formats, SSH authentication records, and structured JSON entries require different extraction rules. A parser should use explicit patterns for each format, retain the event timestamp, and avoid treating version numbers or malformed address-like strings as real traffic.
The Python environment can use ipaddress for validation, argparse for command-line options, and geoip2 to read a local MaxMind GeoLite2 City database. The geographic data has its own licence and update cycle, so it should remain outside source control. Recording the database version in the report makes later comparisons reproducible.
Extracting and validating addresses
A reliable parser first isolates candidate addresses, then lets ipaddress.ip_address() decide whether each candidate is valid. Private, loopback, link-local, multicast, and reserved ranges should normally be excluded from geographic lookup. IPv6 support requires careful handling of colons, compressed notation, and interface scopes.
try:
address = ipaddress.ip_address(candidate)
except ValueError:
continue
if not address.is_global:
continue
For a wider review of address handling, the background in this IP address primer provides a useful companion to the parser documentation. The script should then pass the normalised string representation of the address to the database reader.
Resolving readable localities
Each accepted address can be queried through the local GeoIP2 reader. Useful fields include country, city, state or territory, time zone, and approximate coordinates. The report should preserve the distinction between an exact database value and an inferred one, especially when a city is unavailable but the country is known.
Lookup failures must remain non-fatal because an address may be absent from the database or assigned to a network with incomplete geolocation. APNIC manages much of the Asia-Pacific address space, but its allocation records do not establish a user’s physical location. Similarly, an Australian address can represent a hosted service, VPN exit, mobile network, or cloud platform rather than the location of the person using it.
Summarising activity and time
A single lookup rarely tells the whole story, so the script should aggregate events by city, country, and time period. Counts, first-seen timestamps, last-seen timestamps, and representative event types can be stored in dictionaries while the log is processed. This avoids loading an entire archive into memory and makes it easier to export a CSV or JSON summary.
Timestamps should remain in UTC internally and receive an IANA time zone only when presented. Australian environments commonly use Australia/Sydney, Australia/Melbourne, Australia/Brisbane, and Australia/Perth; the first two observe daylight saving, while Brisbane and Perth retain a fixed UTC offset. For the Australian market, the report can also distinguish traffic associated with hosting regions around Sydney and Melbourne from international traffic reaching the same service.
Testing against realistic edge cases
Unit tests should use synthetic fixtures rather than copies of genuine production logs. They can cover malformed addresses, private ranges, IPv6 notation, missing city names, database errors, and records containing several addresses. Mocked database responses make expected results stable even when the underlying geographic dataset changes.
Performance testing should process a large file without excessive memory use and should stop cleanly when interrupted. Output needs deterministic ordering so that repeated runs can be compared. The same discipline fits the existing portfolio: Kodos helps inspect regular expressions, DenyHosts reacts to repeated SSH failures, and Scratchy analyses Apache logs, while this script adds a geographic reporting layer.
Release safeguards for an open-source tool
The project page can follow the portfolio’s established pattern by explaining the script’s purpose, Python requirements, licence, downloads, and usage statistics. The geographic database must be documented separately from the source code because their licences and distribution methods differ. Sample output should also show that the tool reports uncertainty instead of presenting a city as an exact position.
Release verification falls into two groups:
Data controls
- Exclude private, reserved, loopback, and multicast addresses by default.
- Keep the geographic database outside source control and record its licence.
- Avoid retaining raw addresses unless a documented need justifies them.
- Set a short retention period for exported records containing identifiers.
Operational checks
- Test Apache, authentication, and JSON formats with Australian examples.
- Handle unknown addresses and database errors without aborting the run.
- Export UTC timestamps with the resolved IANA time zone.
- Document dependencies, sample output, download files, and usage figures.
Together, these controls produce a small, auditable tool that turns noisy network records into a useful geographic summary while keeping privacy, licensing, and uncertainty visible.
