-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip-geo.py
77 lines (62 loc) · 1.82 KB
/
ip-geo.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
import pprint
import requests
import subprocess
from getpass import getpass
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import json
IP_count = {}
subprocess.call('cat /var/log/nginx/access.log | cut -d" " -f1 > output.txt', shell=True)
with open('output.txt', 'r') as f:
data = f.read()
data = data.split("\n")
for line in data:
ip = line.strip()
if ip == '':
pass
elif ip not in IP_count:
IP_count[ip] = 1
else:
IP_count[ip] += 1
output = sorted(IP_count.items(), key=lambda x: x[1], reverse=True)
f = open('message.txt','w')
for item in output:
r = requests.get("http://ip-api.com/json/" + item[0])
data = r.json()
f.write('IP: %s\n' % item[0])
f.write('Connections: %s\n' % item[1])
try:
f.write('Location: %s, %s\n' % (data['city'], data['country']))
except:
pass
f.write('\n')
f.close()
def mail_ips():
'''
email ips to myself
'''
s = smtplib.SMTP(host='smtp.gmail.com', port=587, timeout=120)
s.starttls()
while True:
try:
s.login('[email protected]','redacted-password')
break
except:
print("Authentication failed... try again.")
print("Emailing logged IPs...")
msg = MIMEMultipart()
f = open('message.txt','r')
message = f.read()
msg['From']'[email protected]'
msg['To']='[email protected]'
msg['Subject']="Nginx - IP Connection Logging"
msg.attach(MIMEText(message, 'plain'))
# send the message via the server set up earlier.
s.send_message(msg)
del msg
# Terminate the SMTP session and close the connection
s.quit()
mail_ips()