#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# E:\Programs\Python\Python312\python.exe -m pip install requests
import requests
import csv
import argparse
import logging
import sys
# Configure logging to output to stderr
logging.basicConfig(stream=sys.stderr, level=logging.ERROR, format='%(asctime)s %(levelname)s: %(message)s')
def get_location(ip):
try:
response = requests.get(f'http://ip-api.com/json/{ip}')
response.raise_for_status() # Raise an HTTPError for bad responses (4xx and 5xx)
data = response.json()
if data['status'] == 'success':
return data['country'], data['regionName'], data['city'], data['isp']
else:
logging.error(f"Failed to get location for IP {ip}: {data['message']}")
return 'N/A', 'N/A', 'N/A', 'N/A'
except Exception as e:
logging.exception(f"Exception occurred while getting location for IP {ip}")
return 'N/A', 'N/A', 'N/A', 'N/A'
def bulk_lookup(ip_generator, output_file):
with open(output_file, 'w', newline='') as csvfile:
fieldnames = ['IP', 'Country', 'Region', 'City', 'ISP']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for ip in ip_generator:
country, region, city, isp = get_location(ip)
writer.writerow({'IP': ip, 'Country': country, 'Region': region, 'City': city, 'ISP': isp})
print(f'{ip}: {country}, {region}, {city}, {isp}')
def ip_generator(input_file):
with open(input_file, 'r') as file:
for line in file:
ip = line.strip()
if ip and not ip.startswith('#'):
yield ip
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Bulk IP to location lookup')
parser.add_argument('input_file', type=str, help='File containing list of IP addresses')
parser.add_argument('output_file', type=str, help='Output CSV file to store results')
args = parser.parse_args()
# Create a generator for IP addresses from the input file
ips = ip_generator(args.input_file)
bulk_lookup(ips, args.output_file)
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.