本帖最后由 15820394839 于 2022-4-16 20:16 编辑
前几天领导交给我一个任务,让我监控一台服务器是否正常开机,因为服务器有问题,会自动重启,但是需要按F1才能进入,所以有问题时要及时通知机房,于是就写了一个脚本,ping不通自动发邮件提醒机房。纯属新手,因为能力有限,在目录新建了一个count.txt,内容:replacecount=0|1;用来持续判断,然后用crontab按分钟运行;
[Python] 纯文本查看 复制代码 import os
import sys
import smtplib
import pandas as pd
import re
import time
from email.mime.text import MIMEText
#主函数
def ping():
global ip
ip = '192.168.0.0'
backinfo = os.system('ping -c 1 -w 1 %s'%ip) # 实现pingIP地址的功能,-c1指发送报文一次,-w1指等待1秒
if backinfo:
pring("ip无法ping通")
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
print('----------------------------------------------');
checkcount();
else:
#iplist.append(ip)
#print(iplist)
print('ip正常')
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
print('----------------------------------------------');
checkcountrestore();
def goToma(notice):
msg_from="111@qq.com"#发送方
pwe="11111"#授权码
to="111@qq.com"#接收方
subjedt="这是PYthon发送的提醒邮件"#邮件主题
content=notice#邮件内容
#构造邮件
msg=MIMEText(content)#msg邮件对象,也可以发送html格式,比如msg=MIMEText(content,"html","utf-8")
msg["Subject"]=subjedt
msg["From"]=msg_from
msg["To"]=to
#发送邮件
try:
ss = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
ss.login(msg_from, pwe)
ss.sendmail(msg_from, to, msg.as_string()) # 发送
print("发送成功!")
except Exception as e:
print("发送失败!详情",e)
def getcount():
#路径
path = r"/root/ping/count.txt"
#读入
f = open(path, "r", encoding="utf-8")
#获取内容
str1 = f.read()
recount = r'replacecount=(.*?);'
count=re.findall(recount,str1)
count=int(count[0]);
f.close()
return count
def checkcount():
count = getcount()
if count == 0:
goToma('error ip:'+ip+'ping不通了');
stc1 = "replacecount=0;"
stc2 = "replacecount=1;"
writecount(stc1,stc2)
else:
exit();
def checkcountrestore():
count = getcount()
if count == 1:
stc1 = "replacecount=1;"
stc2 = "replacecount=0;"
writecount(stc1,stc2)
goToma("success ip:"+ip+ "已恢复正常")
else:
exit();
def writecount(st1,st2):
#路径
path = r"/root/ping/count.txt"
#读入
f = open(path, "r", encoding="utf-8")
#获取内容
str1 = f.read()
#替换内容
str2 = str1.replace(st1,st2)
#重新写入
ff = open(path, "w")
#将信息写入缓冲区
ff.write(str2)
#刷新缓冲区
ff.flush()
if __name__=='__main__':
ping()
|