-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathalerts.py
More file actions
executable file
·85 lines (66 loc) · 2.08 KB
/
alerts.py
File metadata and controls
executable file
·85 lines (66 loc) · 2.08 KB
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
81
82
83
84
85
import smtplib
import subprocess
import datetime
import jinja2
import base64
from email.mime.text import MIMEText
def get_host_name():
try:
command = "uname -n"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
return output
except:
return None
def get_ip_address():
try:
command = "hostname -I"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
return output
except:
return None
def sendEmail(emailserver, username, port, security, fromAddr, toAddr, b64Password, msgSubjectTemplate, msgBodyTemplate):
try:
port = int(port)
except ValueError:
port = 0
try:
now = datetime.datetime.now()
host = get_host_name().decode('utf-8')
ipaddress = get_ip_address()
except:
raise
password = base64.b64decode(b64Password).decode('utf-8')
tVars = {'now': now, 'host': host, 'ipaddress': ipaddress}
try:
templateLoader = jinja2.FileSystemLoader(searchpath="/")
templateEnv = jinja2.Environment(loader=templateLoader)
subjectTemplate = templateEnv.get_template(msgSubjectTemplate)
bodyTemplate = templateEnv.get_template(msgBodyTemplate)
msgSubject = subjectTemplate.render(tVars)
msgBody = bodyTemplate.render(tVars)
except:
raise
# Writing the message
msg = MIMEText(msgBody)
msg['Subject'] = msgSubject
msg['From'] = fromAddr
msg['To'] = toAddr
# Sending the message
try:
if port:
serverstring = format("%s:%d" % (emailserver, port))
else:
serverstring = emailserver
if security.lower() in ['ssl']:
server = smtplib.SMTP_SSL(serverstring)
else:
server = smtplib.SMTP(serverstring)
server.starttls()
server.login(username, password)
server.sendmail(fromAddr, [toAddr], msg.as_string())
server.quit()
except:
raise
return True