Skip to content

Instantly share code, notes, and snippets.

@insanedefaults
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save insanedefaults/cae180193dd114f59c51 to your computer and use it in GitHub Desktop.

Select an option

Save insanedefaults/cae180193dd114f59c51 to your computer and use it in GitHub Desktop.
Python CLI tool for geoip lookup
from multiprocessing import Pool
import argparse
import requests
import sys
#Functions
def getgeo(ip):
"""Give this a string of an IPv4 or IPv6 address
Returns a dict with geographical data about the ip
"""
r = requests.get('http://www.telize.com/geoip/{0}'.format(ip))
info = r.json()
if r.status_code == 200:
return info
def format_geodict(geodict):
"""Give this a dictionary of geo data
Returns a pipe-formatted string of the data
"""
keys = ['ip', 'country', 'region', 'city']
formatted = {'ip': '-', 'country': '-', 'region': '-', 'city': '-'}
for key in geodict:
if key in keys:
formatted[key] = geodict[key]
result = '{ip}|{country}|{region}|{city}'.format(**formatted)
return result
#Parse the arguments
parser = argparse.ArgumentParser(description='provides geo information for IPs', prog='geoip')
parser.add_argument('ip', nargs='?', default=sys.stdin, help='the ip to check; \
this can also come from stdin as a single IP or a newline-separated series of IPs.')
args = parser.parse_args()
#Format input into a list of strings
if type(args.ip) == type('string'):
ip_list = [args.ip]
else:
ip_list = [item.rstrip('\n') for item in args.ip.readlines()]
#call getgeo on the list of strings, use mp if the string is a list > 1
if len(ip_list) > 1:
if len(ip_list) in range(2,8):
pool = Pool(len(ip_list))
else:
pool = Pool(8)
result = pool.map(getgeo, ip_list)
for line in result:
if line is not None:
print(format_geodict(line))
else:
answer = getgeo(ip_list[0])
if answer is not None:
print(format_geodict(answer))
@insanedefaults
Copy link
Author

Go here for more (now with ++bugs!) https://github.com/sudomilk/whoip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment