Python homemade geoip tool for IP information

Geoip

Logo of the company that offer geoip database

Let say you want to check 10000 IP to find a location, states, timezones, etc. So you can use command whois and automate and it would take some minutes. But what if you want to do faster, less then 1 second?

Build one CLI tool to check all IP but using the Maxmind geoip database.

First, we need to install:

virtualenv -p python3 .
source bin/activate
pip3 install python-geoip-python3
pip3 install python-geoip-geolite2

Then we could use ip.txt file with content:

8.8.8.8
1.2.4.8

And finally - the code that would help us to run this adventure:

import sys
from geoip import geolite2


if len(sys.argv) < 2:
    print("missing file with ip")
    exit(0)

filepath = sys.argv[1]

with open(filepath) as fp:
   line = "something"

   while line:
       line = fp.readline().strip()

       if not line:
            break

       match = geolite2.lookup(line)

       print(line + " " + match.country + " " + match.continent + " " + match.timezone + " " + str(match.location[0]) + " " + str(match.location[1]))

fp.close()

Output would be something like this:

python3 checkip.py ip.txt 
8.8.8.8 US NA America/Los_Angeles 37.386 -122.0838
1.2.4.8 CN AS None 35.0 105.0

One golden advice run update after some time for the geoip Maxmind database. you can also:

git clone https://github.com/vladimircicovic/python_geoip

Related Posts

  • No related post found

Published by

Vladimir Cicovic

Vladimir Cicovic

Author: Vladimir Cicovic