count_ip_countries.py 855 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Requirements:
  2. # Python 2.7
  3. import sys
  4. import GeoIP
  5. gi = GeoIP.open("/usr/share/GeoIP/GeoIP.dat", GeoIP.GEOIP_STANDARD)
  6. filename_ips = sys.argv[1]
  7. country_cnt = {}
  8. ips_all = set()
  9. fd_read = open(filename_ips, "r")
  10. cnt = 0
  11. cnt_unique = 0
  12. for ip in fd_read:
  13. cnt += 1
  14. ip = ip.strip()
  15. if ip in ips_all:
  16. continue
  17. cnt_unique += 1
  18. ips_all.add(ip)
  19. match = gi.country_name_by_addr(ip)
  20. if match is None:
  21. print("could not resolve: %s" % ip)
  22. continue
  23. country = match
  24. try:
  25. country_cnt[country] += 1
  26. except:
  27. country_cnt[country] = 1
  28. fd_read.close()
  29. print("Total: %d" % cnt)
  30. print("Unique: %d" % cnt_unique)
  31. print("Resolved: %d" % sum([count for country,count in country_cnt.items()]))
  32. print("")
  33. country_cnt_sorted = sorted(country_cnt.items(), key=lambda v: v[1])
  34. for country, cnt in country_cnt_sorted:
  35. print("%s: %d" % (country, cnt))