今天中午的时候,网站莫名奇妙地出现无法访问的现象,持续了两个多小时,等发现问题的时候立刻重启了服务器才恢复正常。为防止同样的事情再次发生,所以就想编写一个自动化脚本来监控网站服务,今天为大家分享一下使用 python 脚本实现网站自动监控并发送告警邮件的方法。
1、编写 python 脚本
需要编写两个 python 脚本,一个用来发送邮件 sendmail.py,另一个用来监控服务 checkserver.py,其中 checkserver.py 中会调用 sendmail.py。
a. 发送邮件脚本
首先,编写发送邮件的 pytyon 程序,并保存到指定目录下(比如 /opt),命名为 sendmail.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#!/usr/bin/python
# -*- coding: UTF-8 -*-
importsys
importsmtplib
importemail.mime.multipart
importemail.mime.text
server='smtp.qq.com'
port='25'
defsendmail(server,port,user,pwd,msg):
smtp=smtplib.SMTP()
smtp.connect(server,port)
smtp.login(user,pwd)
smtp.sendmail(msg['from'],msg['to'],msg.as_string())
smtp.quit()
print('邮件发送成功email has send out !')
if__name__=='__main__':
msg=email.mime.multipart.MIMEMultipart()
msg['Subject']='服务器报警请注意!'
msg['From']='pieruo@foxmail.com'
msg['To']='326709862@qq.com'
user='pieruo@foxmail.com'
pwd='ugndbioandhkecuj'
content='%s\n%s'%('\n'.join(sys.argv[1:4]),' '.join(sys.argv[4:]))#格式处理,专门针对我们的邮件格式
txt=email.mime.text.MIMEText(content,_charset='utf-8')
msg.attach(txt)
# 测试发送邮件,测试的时候取消注释
# sendmail(server,port,user,pwd,msg)
可以通过 python sendmail.py 命令执行上述脚本,查看能否正常接收邮件。
b. 监控服务脚本
其次,编写监控服务的 pytyon 程序,保存到指定目录下(比如 /opt),命名为 checkserver.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#!/usr/bin/env python
# -*- coding: UTF-8 -*-
importos
importsys
importsmtplib
importrequests
importemail.mime.multipart
importemail.mime.text
fromrequestsimportReadTimeout
#sys.path.append("/root/pydir") #系统路径中填写存放.py文件地址,然后通过import方法导入
fromsendmailimport *
if__name__=='__main__':
msg=email.mime.multipart.MIMEMultipart()
msg['Subject']='服务器报警请注意!'
msg['From']='pieruo@foxmail.com'
msg['To']='326709862@qq.com'
user='pieruo@foxmail.com'
pwd='ugndbioandhkecci'
content='%s\n%s'%('\n'.join(sys.argv[1:4]),' '.join(sys.argv[4:]))#格式处理,专门针对我们的邮件格式
txt=email.mime.text.MIMEText(content,_charset='utf-8')
msg.attach(txt)
#sendmail(server,port,user,pwd,msg)
try:
#比如这里监控一个网址:夏日阳光
r=requests.get('https://www.pieruo.com',timeout=5)
ifr.status_code!=200:
sendmail(server,port,user,pwd,msg)# 发送状态码不是200的邮件内容
else:
sendmail(server,port,user,pwd,msg)# 发送状态码是200的邮件内容
except(requests.exceptions.ConnectionError,ReadTimeout):
print('Crawling Failed','https://www.pieruo.com')
sendmail(server,port,user,pwd,msg)# 发送访问超时的邮件内容
同样,可以通过 python checkserver.py 命令执行上述脚本,上面 sendmail 方法的内容可以自定义,不同状态发送不同内容的提醒邮件。
2、添加定时任务
添加一个定时任务,每 5 分钟执行一次,执行上面编写好的监控脚本,检查网站服务是否正常。
1crontab-e
添加内容:
1*/5****python/opt/checkserver.py>/dev/null2>&1
可以将上述 python 脚本及此定时任务添加到备用服务器,一旦主服务器挂了我们可以及时收到告警邮件。
3、查收邮件
如果网站服务不能正常访问,我们会及时收到告警邮件。
结束语
使用脚本可以帮我们做很多事情,本文简单分享了一下使用 python 脚本实现网站自动监控并发送告警邮件的实现方法,脚本程序来源于网络,经本人亲自调试通过。如果你喜欢本文,别忘了点赞哦。如果有任何意见或建议,欢迎在下方评论处留言。