在CentOS系统中利用Crontab监控进程是否被结束并自动重启。
附加每天凌晨4点自动重启服务器。
1、编辑Crontab
crontab -e
2、按i进行编辑
*/1 * * * * /root/monitor.sh # 每分钟运行一遍monitor.sh脚本
0 5 * * * /sbin/reboot # 每天凌晨5点自动重启服务器
1
2
*/1 * * * * /root/monitor.sh # 每分钟运行一遍monitor.sh脚本
0 5 * * * /sbin/reboot # 每天凌晨5点自动重启服务器
3、root下创建monitor.sh脚本
#! /bin/sh
host_dir=`echo ~` # 当前用户根目录
proc_name="net_speeder" # 进程名
file_name="/root/log/netspeed.log" # 日志文件
pid=0
proc_num() # 计算进程数
{
num=`ps -ef | grep $proc_name | grep -v grep | wc -l`
return $num
}
proc_id() # 进程号
{
pid=`ps -ef | grep $proc_name | grep -v grep | awk '{print $2}'`
}
proc_num
number=$?
if [ $number -eq 0 ] # 判断进程是否存在
then
~/net-speeder-master/net_speeder venet0 "tcp src port 443" >/dev/null 2>&1 & # 重启进程的命令
proc_id # 获取新进程号
echo ${pid}, `date` >> $host_dir$file_name # 将新进程号和重启时间记录
fi
4、赋予脚本执行权限
chmod 777 /root/monitor.sh
5、添加log文件夹及log文件并赋予权限
mkdir 777 /root/log
touch /root/log/netspeed.log create file
chmod 646 /root/log/netspeed.log
6、重启服务器以应用更改
7、重启后有可能出现crond进程没有运行的问题,需要在rc.local增加crond随系统启动
vi /etc/rc.local
键入
nohup /etc/init.d/crond restart
利用:wq命令保存。
8、设置每次重启后清除log文件
在步骤7中键入
nohup echo '' > /root/log/netspeed.log
9、需要删除文件夹或文件
rm -rf /root/log/netspeed.log