Last active
January 27, 2024 01:19
-
-
Save athyuttamre/f10a64b2861f4ba7c2a3df03c88a1c2d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
import csv | |
import sys | |
KEY = "1dd922548150f47ec2980e90b659b793" | |
BULK = False | |
# One-by-one | |
def map_ip_to_location(ip): | |
print("Getting data for " + ip) | |
url = "http://api.ipstack.com/" + ip + "?access_key=" + KEY | |
response = requests.get(url) | |
try: | |
data = json.loads(response.text) | |
except: | |
print("Error parsing response: " + response.text) | |
lat = data['latitude'] | |
lon = data['longitude'] | |
country = data['country_name'] | |
city = data['city'] | |
region = data['region_code'] | |
return [lat, lon, country, city, region] | |
def map_ips_to_locations(ips): | |
ips_to_data = {} | |
for ip in ips: | |
data = map_ip_to_location(ip) | |
ips_to_data[ip] = data | |
return ips_to_data | |
# Bulk | |
def map_ip_chunk_to_location(ip_chunk): | |
print("Getting data for " + str(ip_chunk)) | |
url = "http://api.ipstack.com/" + ",".join(ip_chunk) + "?access_key=" + KEY | |
response = requests.get(url) | |
try: | |
data = json.loads(response.text) | |
if not data['success']: | |
sys.exit() | |
except: | |
print("Error:" + response.text) | |
chunk_data = {} | |
for item in data: | |
ip_data = json.loads(item) | |
ip = ip_data['ip'] | |
lat = ip_data['latitude'] | |
lon = ip_data['longitude'] | |
country = ip_data['country_name'] | |
city = ip_data['city'] | |
region = ip_data['region_code'] | |
chunk_data[ip] = [lat, lon, country, city, region] | |
return chunk_data | |
def chunks(data, chunk_length): | |
chunk_length = max(1, chunk_length) | |
return (data[i:i+chunk_length] for i in range(0, len(data), chunk_length)) | |
def map_ips_to_locations_bulk(ips): | |
ips_to_data = {} | |
ip_chunks = chunks(ips, 100) | |
for chunk in ip_chunks: | |
chunk_data = map_ip_chunk_to_location(chunk) | |
for ip, data in chunk_data.items(): | |
ips_to_data[ip] = data | |
return ips_to_data | |
def export_to_csv(ips_to_data): | |
result = [['ip', 'lat', 'lon', 'country', 'city', 'region']] | |
for ip, data in ips_to_data.items(): | |
result.append([ip] + data) | |
with open("output.csv", "w") as f: | |
writer = csv.writer(f) | |
writer.writerows(result) | |
with open('ip.csv') as f: | |
lines = f.readlines() | |
ips = [line.replace('\"', '').strip() for line in lines[1:]] | |
limited_set_of_ips = ips[:5] | |
if (BULK): | |
ips_to_data = map_ips_to_locations_bulk(limited_set_of_ips) | |
else: | |
ips_to_data = map_ips_to_locations(limited_set_of_ips) | |
export_to_csv(ips_to_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment