Skip to content

Instantly share code, notes, and snippets.

@SafeEval
Last active May 20, 2025 23:08
Show Gist options
  • Save SafeEval/e650b0a795eef9559eefeddbd63ccb88 to your computer and use it in GitHub Desktop.
Save SafeEval/e650b0a795eef9559eefeddbd63ccb88 to your computer and use it in GitHub Desktop.
Enrich a list of IP addresses
import requests
import csv
import sys
import time
# Optional: Replace with your ipinfo.io token (or use free tier)
IPINFO_TOKEN = "" # e.g., "123abc456def"
HEADERS = {
"Authorization": f"Bearer {IPINFO_TOKEN}"
} if IPINFO_TOKEN else {}
def enrich_ip(ip):
try:
response = requests.get(f"https://ipinfo.io/{ip}/json", headers=HEADERS, timeout=5)
if response.status_code == 200:
data = response.json()
return {
"ip": ip,
"hostname": data.get("hostname", ""),
"city": data.get("city", ""),
"region": data.get("region", ""),
"country": data.get("country", ""),
"org": data.get("org", ""),
"asn": data.get("asn", {}).get("asn", "") if "asn" in data else "",
"asn_org": data.get("asn", {}).get("name", "") if "asn" in data else "",
}
else:
print(f"[!] Failed to get data for {ip} (Status: {response.status_code})")
except Exception as e:
print(f"[!] Error fetching {ip}: {e}")
return {
"ip": ip,
"hostname": "", "city": "", "region": "", "country": "",
"org": "", "asn": "", "asn_org": ""
}
def main(input_file, output_file="ip_enriched.csv"):
with open(input_file, "r") as infile:
ips = [line.strip() for line in infile if line.strip()]
results = []
for ip in ips:
result = enrich_ip(ip)
results.append(result)
time.sleep(0.5) # avoid rate limiting (tune as needed)
with open(output_file, "w", newline="") as csvfile:
fieldnames = ["ip", "hostname", "city", "region", "country", "org", "asn", "asn_org"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(results)
print(f"[+] Enriched data written to: {output_file}")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python enrich_ips.py ip_list.txt outfile.csv")
sys.exit(1)
input_path = sys.argv[1]
output_path = sys.argv[2]
main(input_path, output_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment