IP - geoiplookup.py - statistic
input file (ip_country.txt)
111.222.333.444,CN,China
111.222.333.444,MX,Mexico
111.222.333.444,BR,Brazil
111.222.333.444,ML,Mali
run
./ip_country_statistic.py ips_country.txt
./ip_country_statistic.py ips_country.txt TABLE
./ip_country_statistic.py ips_country.txt JIRA
./ip_country_statistic.py ips_country.txt CSV
ip_country_statistic.py
#!/usr/bin/env python3
import sys
from prettytable import PrettyTable
# TABLE, CSV, JIRA
FORMAT_OUT_PUT = sys.argv[2] if len(sys.argv) >= 3 else 'TABLE'
def read_ip_list():
ip_file = sys.argv[1]
try:
with open(ip_file) as file:
return file.read().splitlines()
except IOError:
sys.stderr.write('Unable to open file {}\n'.format(ip_file))
exit(1)
ip_list = read_ip_list()
country_statistic = {'!!! IPAddressnotfound': 0}
for ip_c in ip_list:
ip_data = ip_c.split(",")
if ip_data[1] == "IPAddressnotfound":
country_statistic['!!! IPAddressnotfound'] = country_statistic['!!! IPAddressnotfound'] + 1
elif ip_data[2] in country_statistic:
country_statistic[ip_data[2]] = country_statistic[ip_data[2]] + 1
else:
country_statistic[ip_data[2]] = 1
if FORMAT_OUT_PUT == 'TABLE':
x = PrettyTable()
x.field_names = ["Country", "Number of IPs"]
for k, v in sorted(country_statistic.items(), key=lambda item: item[1]):
x.add_row([k, v])
print(x)
elif FORMAT_OUT_PUT == 'CSV':
print("Country,Number of IPs")
for k, v in sorted(country_statistic.items(), key=lambda item: item[1]):
print("{},{}".format(k, v))
elif FORMAT_OUT_PUT == 'JIRA':
print("||Country||Number of IPs||")
for k, v in sorted(country_statistic.items(), key=lambda item: item[1]):
print("|{}|{}|".format(k, v))
else:
print("Format not provided or invalid")
output - TABLE
./ip_country_statistic.py ips_country.txt TABLE
+-------------------------------+---------------+
| Country | Number of IPs |
+-------------------------------+---------------+
| Brazil | 553 |
| Indonesia | 678 |
| UnitedStates | 1245 |
| China | 5678 |
+-------------------------------+---------------+
output - JIRA
./ip_country_statistic.py ips_country.txt JIRA
|| Country || Number of IPs ||
| Brazil | 553 |
| Indonesia | 678 |
| UnitedStates | 1245 |
| China | 5678 |
output - CSV
./ip_country_statistic.py ips_country.txt CSV