服务器经常内存爆满,系统就会自动kill掉某些进程。想起来使用Python写一个脚本判断这几个web进程是否存在,不存在直接发送邮件给我并且尝试启动 - 使用psutil模块查找进程
def name(a):
import psutil
pids = psutil.pids() #获取所有的进程的pid
names = []
for i in pids: #遍历循环ID
name = psutil.Process(i) #通过pid查找进程的详细信息
names.append(name.name()) #返回集成名称并添加到names
if a in names:
return True #存在就返回真
else:
return False #不存在返回假
- 运行全部代码
__author__ = 'xiaobing'
import socket,os
def mail(seiz, anb):
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
# qq邮箱smtp服务器
host_server = 'smtp.qq.com'
# sender_qq为发件人的qq号码
sender_qq = '358400845@qq.com'
# pwd为qq邮箱的授权码
pwd = 'sdfsdfsdfsdf' # xh**********bdc
# 发件人的邮箱
sender_qq_mail = '358400845@qq.com'
# 收件人邮箱
receiver = 'lhb0703love@163.com'
hostname = socket.gethostname()
# 邮件的正文内容
mail_content = '''
stop %s进程已停止\n
start %s
''' % (seiz, nab)
# 邮件标题
mail_title = '%s主机进程' % hostname
# ssl登录
smtp = SMTP_SSL(host_server)
# set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式
smtp.set_debuglevel(0)
smtp.ehlo(host_server)
smtp.login(sender_qq, pwd)
msg = MIMEText(mail_content, "plain", 'utf-8')
msg["Subject"] = Header(mail_title, 'utf-8')
msg["From"] = sender_qq_mail
msg["To"] = receiver
smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
smtp.quit()
def name(a):
import psutil
pids = psutil.pids()
names = []
for i in pids:
name = psutil.Process(i)
names.append(name.name())
if a in names:
return True
else:
return False
def if_pid(abc):
ps1 = name(abc)
if ps1 == False:
na = "%s进程启动失败" % abc
else:
na = "%s进程启动成功" % abc
mail(abc, na)
def ifi(a):
for i in a:
ps = name(i)
if ps == False:
if i != "mysqld":
os.system("systemctl start %s" % i)
if_pid(i)
else:
os.system("systemctl start mariadb")
if_pid(i)
if __name__ == '__main__':
hostname = socket.gethostname()
a = ["php-fpm", "nginx", "mysqld"]
ifi(a)
发表评论
共 0 条评论
暂无评论