通用的进程监控重拉起bash脚本

简介:  process_monitor.zip   #!/bin/sh# http://code.google.com/p/mooon# 进程监控脚本,当指定进程不存在时,执行重启脚本将它拉起# 特色:# 1.

 process_monitor.zip   

#!/bin/sh
# http://code.google.com/p/mooon
# 进程监控脚本,当指定进程不存在时,执行重启脚本将它拉起
# 特色:
# 1.本监控脚本可重复执行,它会自动做互斥,保证总是只有一个监控脚本进程存在
# 2.互斥不仅依据监控脚本文件名,而且包含了它的命令行参数,只有整体相同时互斥才生效
# 3.对于被监控的进程,可以只指定进程名,也可以包含命令行参数
# 4.不管是监控脚本还是被监控进程,总是只针对属于当前用户下的进程


# 需要指定个数的命令行参数
# 参数1:被监控的进程名
# 参数2:重启被监控进程的脚本
if test $# -ne 2; then
printf "\033[1;33musage: $0 process_cmdline restart_script\033[m\n"
exit 1
fi


process_cmdline="$1" # 需要监控的进程名,或完整的命令行,也可以为部分命令行
restart_script="$2"  # 用来重启进程的脚本,要求具有可执行权限
monitor_interval=10  # 定时检测时间间隔,单位为秒
cur_user=`whoami`    # 执行本监控脚本的用户名


# 取指定网卡上的IP地址
#eth=1&&netstat -ie|awk -F'[: ]' 'begin{found=0;} { if (match($0,"eth'"$eth"'")) found=1; else if ((1==found) && match($0,"eth")) found=0; if ((1==found) && match($0,"inet addr:") && match($0,"Bcast:")) print $13; }'


# 下面这段脚本,用来阻止多个监控脚本进程出现
uid=`id -u $cur_user`
self_name=`basename $0`
self_cmdline="$0 $*"
process_name=$(basename `echo "$process_cmdline"|cut -d" " -f1`)


# 以死循环方式,定时检测指定的进程是否存在
while true; do
self_count=`ps -C $self_name h -o euser,args| awk 'BEGIN { num=0; } { if (($1==uid || $1==cur_user) && match($0, self_cmdline)) {++num;}} END { printf("%d",num); }' uid=$uid cur_user=$cur_user self_cmdline="$self_cmdline"`
if test $self_count -gt 2; then
# 如果监控脚本已经运行,则退出不重复运行
printf "\033[0;32;31m$0 is running[$self_count], current user is $cur_user.\033[m\n"
exit
fi


# 检查被监控的进程是否存在,如果不存在则重启
process_count=`ps -C $process_name h -o euser,args| awk 'BEGIN { num=0; } { if (($1==uid || $1==cur_user) && match($0, process_cmdline)) {++num;}} END { printf("%d",num); }' uid=$uid cur_user=$cur_user process_cmdline="$process_cmdline"`
if test $process_count -lt 1; then
# 执行重启脚本,要求这个脚本能够将指定的进程拉起来
printf "\033[0;32;34mrestart \"$process_cmdline\"\033[m\n"
sh -c "$restart_script" # 注意一定要以“sh -c”方式执行
fi


sleep $monitor_interval
done

相关文章
|
监控 安全 Shell
防止员工泄密的措施:在Linux环境下使用Bash脚本实现日志监控
在Linux环境下,为防止员工泄密,本文提出使用Bash脚本进行日志监控。脚本会定期检查系统日志文件,搜索敏感关键词(如"password"、"confidential"、"secret"),并将匹配项记录到临时日志文件。当检测到可疑活动时,脚本通过curl自动将数据POST到公司内部网站进行分析处理,增强信息安全防护。
406 0
|
存储 Shell Linux
Linux Bash 脚本中的 IFS 是什么?
【4月更文挑战第25天】
477 0
Linux Bash 脚本中的 IFS 是什么?
|
Devops 关系型数据库 大数据
1000个开源免费的bash脚本合集
【10月更文挑战第4天】
343 0
|
Shell
一个能够生成 Markdown 表格的 Bash 脚本
【8月更文挑战第20天】这是一个使用Bash脚本生成Markdown表格的示例。脚本首先设置表头与内容数据,然后输出Markdown格式的表格。用户可以根据需要自定义表格内容。使用时,只需将脚本保存为文件(如 `generate_table.sh`),赋予执行权限,并运行它,即可在终端看到生成的Markdown表格。
237 2
|
Unix Shell Linux
在Linux中,什么是Bash脚本,并且如何使用它。
在Linux中,什么是Bash脚本,并且如何使用它。
|
Shell 开发者
深入理解Bash脚本中的函数
【8月更文挑战第20天】
410 0
|
存储 Shell 数据处理
深入探讨Bash脚本中的数组
【8月更文挑战第20天】
239 0
|
存储 Shell
Bash 脚本中的 `hash` 命令
【8月更文挑战第19天】
210 0
|
存储 弹性计算 运维
用bash脚本创建目录
【4月更文挑战第29天】
169 3
|
Unix Shell Linux
技术经验分享:Bash脚本命令使用详解
技术经验分享:Bash脚本命令使用详解
740 0

热门文章

最新文章