Skip to content

Instantly share code, notes, and snippets.

@poteto
Created May 27, 2012 13:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poteto/2814239 to your computer and use it in GitHub Desktop.
Save poteto/2814239 to your computer and use it in GitHub Desktop.
Batch IP Geolocation script
#!/usr/bin/python
# ip_lookup.py by poteto
#
# Batch processes many IP addresses, and traces their geolocation.
# The script outputs a .txt file which is then renamed to .csv, and is usable in Excel
#
# Use:
# 1. Save your user email and IP addresses in a .csv file
# - Each email and IP should be in its own column in Excel (or separated by commas)
# - Enter the name of your .csv file:
#
batch_filename = "batch.csv"
#
# 2. Go to http://www.ipinfodb.com/ip_location_api.php and get your own API key
# 3. Update the config with your API key:
#
key = "your_api_key"
#
# 4. Run the script:
# $ python ip_lookup.py
import xml.etree.ElementTree as ET
import urllib
import csv
import os
# Process batch csv into list 'current_batch'
def get_batch(batch_filename):
"Creates list containing all the email and IP addresses from your batch file"
batch = csv.reader(open(batch_filename, 'rb'), delimiter=',')
return [[email, ip_addr] for email, ip_addr in batch]
def batch_process(batch):
"Runs your batch file through the IPInfoDB API"
try:
i = 0
output = open('output.txt', 'a')
for email, ip_addr in batch:
response = urllib.urlopen(url + "&ip=" + str(ip_addr)).read()
tree = ET.fromstring(response)
output.write(str(email) + ",")
for child in tree:
if child.tag == 'ipAddress':
output.write(str(child.text) + ",")
if child.tag == 'countryCode':
output.write(str(child.text) + ",")
if child.tag == 'timeZone':
output.write(str(child.text) + "\n")
i += 1
print "\t" + str(i) + " of " + str(len(batch)) + ":\t" + str(email)
output.close()
os.rename('output.txt', 'output.csv')
print "Complete."
except KeyboardInterrupt:
output.close()
print "\nExiting..."
base_url = "http://api.ipinfodb.com/v3/ip-city/?format=xml&key="
url = base_url + key
current_batch = get_batch(batch_filename)
print "Added " + str(len(current_batch)) + " entries from " + str(batch_filename) + "\n"
print "Working... This may take a while, please be patient.\n"
batch_process(current_batch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment