Welcome to li chao's blog

若逢新雪初霁,满月当空,下面平铺着皓影,上面流转着亮银,而你带笑地向我步来,月色与雪色之间,你是第三种绝色!

利用python监测linux上的服务(简单实现服务宕掉自动发送邮件)

python 

这里用到了四个python 模块 : 

import time (时间模块)  import re (正则模块) import socket (监测端口模块)import yagmail (发送邮件模块)

代码如下:

import time
import re
import socket
import yagmail
def sendmail(subject,contents):
yag = yagmail.SMTP(user='xxxxxxxxx@qq.com',password='xxxxxxxxx',host='smtp.qq.com')
yag.send(to='xxxxxxxxx@qq.com',subject=subject, contents=contents)
yag.close()
hosts = ['x.x.x.x']
while True:
time.sleep(15)
for host in hosts:
ip = re.compile('(.*?):(.*)').search(host).group(1)
port = re.compile('(.*?):(.*)').search(host).group(2)
server = socket.socket()
server.settimeout(1)
res = server.connect_ex((ip, int(port)))
if res == 0:
print('%s---%s:连接成功' % (ip, port))
else:
print('%s---%s:连接失败' % (ip, port))
sendmail('警告!','你的%s端口所对应的服务宕掉了' %port)

posted on 2019-04-29 20:56  lichaoyx  阅读(244)  评论(0编辑  收藏  举报

导航