网站首页 > 技术教程 正文
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 进程
# 如果需要更复杂的监控,比如定期检查或检查工作进程数,可以扩展此脚本功能
猜你喜欢
- 2024-10-10 平台进程监控介绍(系统进程监控软件)
- 2024-10-10 Zabbix监控系统系列之八:监控nginx服务
- 2024-10-10 深度|掌握Nginx监控运维,这一篇足矣!
- 2024-10-10 Nginx 监控(nginx监控工具)
- 2024-10-10 如何轻松监控Nginx?(nginx 监控)
- 2024-09-11 这可能是把Nginx讲解的最透彻的一本新书
- 2024-09-11 nginx动态添加nginx-module-vts监控流量
- 2024-09-11 Docker 容器操作:运行、监控与维护
- 2024-09-11 用groovry做简单的nginx日志实时监控脚本
- 2024-09-11 教你三种方法,用 Python实时监控文件
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- 下划线是什么 (87)
- 精美网站 (58)
- qq登录界面 (90)
- nginx 命令 (82)
- nginx .http (73)
- nginx lua (70)
- nginx 重定向 (68)
- Nginx超时 (65)
- nginx 监控 (57)
- odbc (59)
- rar密码破解工具 (62)
- annotation (71)
- 红黑树 (57)
- 智力题 (62)
- php空间申请 (61)
- 按键精灵 注册码 (69)
- 软件测试报告 (59)
- ntcreatefile (64)
- 闪动文字 (56)
- guid (66)
- abap (63)
- mpeg 2 (65)
- column (63)
- dreamweaver教程 (57)
- excel行列转换 (56)
本文暂时没有评论,来添加一个吧(●'◡'●)