温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何监控服务器Shell脚本

发布时间:2026-11-08 19:18:36 来源:亿速云 阅读:100 作者:小樊 栏目:系统运维

监控服务器上的 Shell 脚本,核心目标是:及时发现脚本是否在执行、是否异常退出、是否卡死、输出是否正确。下面按“常见场景 + 常用方案”系统讲一下。


一、最基础的监控方式(轻量级)

1. 进程级监控(是否在运行)

ps -ef | grep your_script.sh | grep -v grep

或更准确:

pgrep -f your_script.sh

✅ 适合:定时任务、常驻脚本


2. 日志监控(看输出和报错)

在脚本里统一输出日志:

#!/bin/bash
LOG=/var/log/my_script.log
echo "$(date) start" >> $LOG
# your code
echo "$(date) end" >> $LOG

监控关键字:

grep -i error /var/log/my_script.log

3. 退出码监控(是否失败)

your_script.sh
echo $?

非 0 即异常,可配合定时任务报警。


二、定时任务脚本监控(cron)

1. cron + 邮件

* * * * * /path/your_script.sh >> /var/log/script.log 2>&1

查看邮件或日志判断是否执行。


2. 防止重复执行(锁文件)

#!/bin/bash
LOCK=/tmp/your_script.lock
[ -f $LOCK ] && exit 1
touch $LOCK
trap "rm -f $LOCK" EXIT

三、高级监控方案(推荐)

1. 使用 supervisor(常驻脚本首选)

[program:shell_monitor]
command=/path/your_script.sh
autostart=true
autorestart=true
stderr_logfile=/var/log/shell.err.log
stdout_logfile=/var/log/shell.out.log

✅ 自动重启
✅ 崩溃可感知


2. 使用 systemd(服务器级)

[Unit]
Description=My Shell Script

[Service]
ExecStart=/path/your_script.sh
Restart=always

[Install]
WantedBy=multi-user.target
systemctl enable my_script
systemctl status my_script

3. 健康检查 + 心跳文件

脚本定期写心跳:

echo $(date +%s) > /tmp/script_heartbeat

监控脚本:

NOW=$(date +%s)
LAST=$(cat /tmp/script_heartbeat)
[ $((NOW - LAST)) -gt 300 ] && echo "脚本可能卡死"

四、企业级监控(告警)

1. Prometheus + Node Exporter(不推荐直接监控 shell)

更适合:

  • 进程是否存在
  • 日志关键字
  • 自定义 exporter

2. Zabbix / Nagios

  • 监控进程
  • 监控日志文件
  • 自定义脚本返回值

3. 日志平台(ELK / Loki)

  • 收集脚本日志
  • 配置 error / timeout 告警

五、常见监控指标总结

指标 方法
是否运行 ps / pgrep
是否失败 退出码
是否卡死 心跳文件
是否重复 锁文件
是否异常 日志关键字
是否自动恢复 supervisor / systemd

六、推荐组合(实战)

✅ 常驻脚本
systemd / supervisor + 日志 + 心跳

✅ 定时脚本
cron + 锁文件 + 日志 + 退出码

✅ 关键业务
日志平台 + 告警


如果你愿意,可以告诉我:

  • 脚本是 定时还是常驻
  • 是否在 生产环境
  • 用的是什么系统(CentOS / Ubuntu)

我可以直接帮你写一套可落地的监控方案或脚本。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手