Python脚本监控管理nginx
Python脚本监控管理nginx
在Linux环境中,Python脚本可以用来监控和管理Nginx服务器的进程状态、端口监听情况以及日志分析等。以下是一个基础的Python脚本示例,用于检查Nginx主进程是否运行,并在进程未运行时发送警报:
用python代码实现过程如下:
import subprocess
import psutil
import smtplib
import time
from email.mime.text import MIMEText
# 检查Nginx主进程是否存在函数
def is_nginx_running():
try:
# 使用`pgrep`命令查找Nginx主进程,检查 Nginx 进程是否在运行
result = subprocess.run(['pgrep', '-f', 'nginx: master process'], capture_output=True, text=True)
return bool(result.stdout.strip())
except Exception as e:
print(f"Error checking Nginx process: {e}")
return False
如果发现Nginx服务没有运行,重启 Nginx
try:
subprocess.run(['nginx', '-s', 'reload'], check=True)
print("Nginx restarted successfully.")
except subprocess.CalledProcessError as e:
print(f"Error restarting Nginx: {e}")
# 检查nginx的状态
########### 这部分代码也可以使用,根据自己的爱好
def check_nginx_status():
# 发送HTTP请求到Nginx服务器,检查其状态
try:
response = requests.get('http://192.168.10.1/nginx_status')
if response.status_code == 200:
return True
else:
return False
except requests.exceptions.RequestException as e:
print(e)
return False
###########
# 发送邮件通知函数
def send_email(subject, message):
sender = 'your_email@example.com'
receiver = 'admin_email@example.com'
password = 'your_smtp_password' # 或者使用环境变量存储密码
smtp_server = 'smtp.example.com'
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
try:
with smtplib.SMTP(smtp_server, 587) as server:
server.starttls()
server.login(sender, password)
server.sendmail(sender, receiver, msg.as_string())
except Exception as e:
print(f"Failed to send email: {e}")
# 主程序逻辑
if __name__ == "__main__":
if not is_nginx_running():
message = "Nginx主进程未运行,请尽快检查!"
send_email("Nginx服务警告", message)
else:
print("Nginx主进程正在运行。")
# 获取CPU使用率
cpu_usage = psutil.cpu_percent()
print('CPU Usage:', cpu_usage)
time.sleep(60) # 每分钟检查一次 Nginx 进程
# 如果需要更复杂的监控,比如定期检查或检查工作进程数,可以扩展此脚本功能