Skip to content

Instantly share code, notes, and snippets.

@vnetman vnetman/ilgeoip.py
Created May 19, 2019

Embed
What would you like to do?
Program appends Geo IP information to IPv4 addresses
#!/usr/bin/env python2.7
# This program reads lines on stdin and copies them to stdout, after
# appending any IPv4 addresses found on the line with geo information.
#
# Examples:
#
# $ echo "Hello there" | ./ilgeoip.py
# Hello there
#
# $ echo "Hello there, 58.242.83.28" | ./ilgeoip.py
# Hello there, 58.242.83.28 (CN, 34)
#
# tcpdump -f -i ens2 | ./ilgeoip.py
# ...
# ...
# 07:35:14.157416 IP 192.168.1.9.42524 > 172.217.167.129 (US, CA).https: Flags [R], seq 1321755834, win 0, length 0
# 07:35:14.157419 IP 172.217.167.129 (US, CA).https > 192.168.1.9.42524: Flags [.], ack 794, win 244, options [nop,nop,TS val 4285242698 ecr 1566394895], length 0
# ...
# ...
#
# This program uses the python-geoip library documented at
#
# https://pythonhosted.org/python-geoip/
#
# which in turn uses the MaxMind GeoIP database. First install the python-geoip
# library as documented in the URL above, then run this program. Using a
# virtualenv is recommended.
from __future__ import print_function
import fileinput
import re
from geoip import geolite2
def country_subdiv(ipv4_address_groups):
ipv4_address = ipv4_address_groups.group(1)
match = geolite2.lookup(ipv4_address)
if match:
ipv4_address += ' ({}'.format(match.country)
for subd in match.subdivisions:
ipv4_address += ', {}'.format(subd)
ipv4_address += ')'
return ipv4_address
ipv4_re = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
for line in fileinput.input():
xline = ipv4_re.sub(country_subdiv, line)
print(xline, end='')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.