forked from duanjunhyq/cidgoh_ip_monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcidgoh_ip_monitor.py
80 lines (66 loc) · 2.8 KB
/
cidgoh_ip_monitor.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
78
79
80
#!/usr/bin/env python3
# Written by [email protected] to check IP status and send out email to notify latest IP
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP_SSL
import socket
import os.path
import logging
import configparser
import inspect, os.path
def sendMail(server_url, sender_email, sender_email_pass, message,subject, recipient_emails):
server = smtplib.SMTP_SSL(server_url, 465)
server.login(sender_email,sender_email_pass)
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient_emails
msg['Subject'] = subject
body = message
msg.attach(MIMEText(body, 'plain'))
text = msg.as_string()
server.sendmail(sender_email, recipient_emails.split(','), text)
if __name__ =='__main__':
# load config file
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
config = configparser.ConfigParser()
config.read(path+'/config.ini')
local_ip_file = path+'/.local_ip'
# check current ip address
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
current_ip=s.getsockname()[0]
# set log file
logging.basicConfig(filename=path+"/logs.txt",
format='%(asctime)s %(message)s',
filemode='a')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# Get email settings from config file
machine_name = config['DEFAULT']['Machine']
server_url = config['EMAIL']['Server_URL']
subject = config['EMAIL']['Subject'] + " for " + machine_name
sender_email = config['EMAIL']['Sender_email']
sender_email_pass = config['EMAIL']['Sender_email_pass']
recipient_emails = config['EMAIL']['Recipient_emails']
if os.path.isfile(local_ip_file):
with open(local_ip_file) as f:
lines = f.read()
last_ip = lines.split('\n', 1)[0]
if(current_ip == last_ip):
logger.info("Same IP")
else:
message = 'CIDGOH IP montior found IP address status change. The IP has been changed from '+last_ip+' to '+current_ip +" for "+ machine_name+"."
logger.warning(message)
sendMail(server_url, sender_email, sender_email_pass, message,subject, recipient_emails)
f = open(local_ip_file, "w")
f.write(current_ip)
f.close()
else:
message = 'CIDGOH IP monitor is running. The current IP for '+ machine_name + ' is '+current_ip+"."
sendMail(server_url, sender_email, sender_email_pass, message,subject, recipient_emails)
f = open(local_ip_file, "w")
f.write(current_ip)
f.close()
logger.info(message)