Skip to content

Instantly share code, notes, and snippets.

@hackersoup
Last active July 7, 2021 12:14
Show Gist options
  • Save hackersoup/0c205083534be37c28485369165fd926 to your computer and use it in GitHub Desktop.
Save hackersoup/0c205083534be37c28485369165fd926 to your computer and use it in GitHub Desktop.
IP to Country Lookup Script
#!/usr/bin/env python3
try:
import geoip2.database
except ImportError:
print('[!] Could not find "geoip2" library')
print('[!] Try running the following command to install it:')
print('python3 -m pip install geoip2')
exit(-1)
try:
import click
except ImportError:
print('[!] Could not find "click" library')
print('[!] Try running the following command to install it:')
print('python3 -m pip install click')
exit(-1)
@click.command()
@click.argument('mmdb_file')
@click.argument('input_file')
def main(mmdb_file, input_file):
"""
Use a (free) MaxMind GeoLite2-Country database to
search for the country that a list of IPs are registered to.
Create an account on maxmind.com and then download the
GeoLite2-Country database. Provide the path to the .mmdb
file and path to the list of IPs and/or IP subnets to check.
If the IPs are given as a subnet, the tool will just rip
the slash off and treat the preceeding IP as the IP to search.
They tend to be allocated in blocks so that should be fine
with smaller subnet ranges.
Example: python3 lookup.py /path/to/GeoLite2-Country.mmdb /path/to/ip-list.txt
"""
with geoip2.database.Reader(mmdb_file) as mmdb:
with open(input_file, 'r') as fp:
output = []
lines = fp.readlines()
lines = [line.strip() for line in lines]
for line in lines:
ip = line.split('/')[0]
response = mmdb.country(ip)
country = response.country.name
code = response.country.iso_code
output.append(f'{code}\t{line}')
output.sort()
for line in output:
print(line)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment