45 lines
1.6 KiB
Python
45 lines
1.6 KiB
Python
import geoip2.database
|
|
import geoip2.errors
|
|
import csv
|
|
|
|
# File names
|
|
INPUT_FILE = 'mascan_results.txt' # Your list of IPs, one per line
|
|
OUTPUT_FILE = 'results.csv' # The CSV file that will be created
|
|
DB_FILE = 'GeoLite2-ASN.mmdb' # The MaxMind database file
|
|
|
|
# We use 'with' statements to ensure files and databases close automatically
|
|
with geoip2.database.Reader(DB_FILE) as reader, \
|
|
open(INPUT_FILE, 'r') as infile, \
|
|
open(OUTPUT_FILE, 'w', newline='') as outfile:
|
|
|
|
# Initialize the CSV writer
|
|
writer = csv.writer(outfile)
|
|
|
|
# Write the column headers to the CSV
|
|
writer.writerow(['IP Address', 'ISP / Provider', 'Subnet', 'ASN'])
|
|
|
|
# Loop through each line in your input text file
|
|
for line in infile:
|
|
ip = line.strip() # Remove spaces and line breaks
|
|
|
|
if not ip:
|
|
continue # Skip blank lines
|
|
|
|
try:
|
|
# Query the Radix Tree database
|
|
response = reader.asn(ip)
|
|
provider = response.autonomous_system_organization
|
|
subnet = str(response.network) # Convert subnet object to string
|
|
asn = response.autonomous_system_number
|
|
|
|
# Write the successful result to the CSV
|
|
writer.writerow([ip, provider, subnet, asn])
|
|
|
|
except geoip2.errors.AddressNotFoundError:
|
|
# IP isn't in the database
|
|
writer.writerow([ip, 'Not Found', 'Not Found', 'Not Found'])
|
|
|
|
except ValueError:
|
|
# The text on this line wasn't a valid IP address format
|
|
writer.writerow([ip, 'Invalid IP format', 'N/A', 'N/A'])
|