Skip to content

Instantly share code, notes, and snippets.

@putnik
Created April 17, 2023 23:46
Show Gist options
  • Save putnik/a74fe7ce5d7fd9f94809ee1d57b88360 to your computer and use it in GitHub Desktop.
Save putnik/a74fe7ce5d7fd9f94809ee1d57b88360 to your computer and use it in GitHub Desktop.
Script to count most popular countries by IP
# pip3 install python-geoip-python3
# pip3 install python-geoip-geolite2
from geoip import geolite2
import csv
ips = {}
countries = {}
total = 0
with open('ips_month.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
next(reader, None)
for row in reader:
ip = row[0]
if ip not in ips:
ips[ip] = geolite2.lookup(row[0])
country = ips[ip].country if ips[ip] is not None and ips[ip].country is not None else 'None'
countries[country] = countries[country] + 1 if country in countries else 1
total += 1
countries_sorted = sorted(countries.items(), key=lambda x:x[1], reverse=True)
other = 0
threshold = countries_sorted[10][1]
for country, country_total in countries_sorted:
if country_total >= threshold:
print("%s\t%d\t%d%%" % (country, country_total, 100 * country_total / total))
else:
other += country_total
print('Other\t%d\t%d%%' % (other, 100 * other / total))
print('Total\t%d\t%d%%' % (total, 100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment