python检测进程,不存在自动重启服务发送邮件

这是一个Python脚本的基本框架,它检查指定的进程和端口。如果进程或端口不存在,脚本将自动重新启动进程并发送警报邮件。请注意,你可能需要根据你的具体需求和环境进行一些调整。

在这个示例中,我将假设你想要检查一个名为 “myprocess” 的进程,以及一个在端口 “8080” 上运行的服务。

import subprocess
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# 检查进程是否存在
def check_process(process_name):
    call = 'pgrep -f ' + process_name
    try:
        output = subprocess.check_output(call, shell=True)
        if str(process_name) in output.strip():
            return True
    except Exception as e:
        return False

# 检查端口是否打开
def check_port(port):
    call = 'netstat -tuln | grep ' + str(port)
    try:
        output = subprocess.check_output(call, shell=True)
        if ':' + str(port) + ' ' in output.strip():
            return True
    except Exception as e:
        return False

# 重新启动进程
def restart_process(process_name):
    call = 'systemctl restart ' + process_name
    try:
        subprocess.check_output(call, shell=True)
    except Exception as e:
        print(f"Failed to restart {process_name}: {e}")

# 发送警报邮件
def send_email(subject, body):
    msg = MIMEMultipart()
    msg['From'] = 'your_email@example.com'
    msg['To'] = 'your_email@example.com'
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    server = smtplib.SMTP('smtp.example.com', 587)
    server.starttls()
    server.login(msg['From'], 'your_password')
    server.sendmail(msg['From'], msg['To'], msg.as_string())
    server.quit()

# 主函数
def main():
    process_name = 'myprocess'
    port = 8080

    if not check_process(process_name):
        restart_process(process_name)
        send_email(f'Process {process_name} was not running', f'{process_name} has been restarted.')

    if not check_port(port):
        restart_process(process_name)
        send_email(f'Port {port} was not open', f'The process serving port {port} has been restarted.')

if __name__ == "__main__":
    main()

这个脚本使用了 pgrep 和 netstat 命令来检查进程和端口的状态,使用 systemctl restart 来重新启动进程,使用 SMTP 服务器来发送警告邮件。你需要提供你的电子邮件地址和密码,以及你的SMTP服务器的地址和端口。这些值都需要根据你的环境进行修改。

另外,请注意,这个脚本需要在具有适当权限的环境中运行,才能成功检查进程,重新启动进程和发送电子邮件。

发表评论

后才能评论