一个简单的shell脚本,用来找出关键的服务是否正在运行,适用于Linux操作系统或Unix操作系统。
原文出处::http://www.jbxue.com/article/11440.html
该脚本还可以使用电子邮件发送通知。
代码:
复制代码代码如下:
#!/bin/bash
# Name : service.chk 服务检测脚本
## 根据自己的环境修改
_pgrep="/usr/bin/pgrep"
_mail="/usr/bin/mail"
## 环境变量
_chklist="/usr/bin/php-cgi /usr/sbin/nginx /usr/sbin/lighttpd /usr/sbin/mysqld /usr/sbin/apache2 /usr/sbin/named /usr/sbin/pgsqld"
## yes | no
_sendemail="no"
_email="test@jbxue.com"
## 不要修改如下配置
_failed="false"
_service="Service:"
_running() {
local p="${1##*/}"
local s="true"
$_pgrep "${p}" >/dev/null || { s="false"; _failed="true"; _service="${_service} $1,"; }
[[ "$s" == "true" ]] && echo "$1 running" || { echo -n "$1 not running"; [[ ! -f "$1" ]] && echo " [ $1 not found ]" || echo ; }
}
## header
echo "Service status on ${HOSTNAME} @ $(date)"
echo "------------------------------------------------------"
## Check if your service is running or not
for s in $_chklist
do
_running "$s"
done
## Send a quick email update (good for cron jobs) ##
[[ "$_failed" == "true" && "$_sendemail" == "yes" ]] && { _mess="$_service failed on $HOSTNAME @ $(date)";
$_mail -s 'Service not found' "$_email" < "${_mess}";
}
下面是一些小段代码,大家也可以参考下
脚本一:
#!/bin/sh
program=XXXX #进程名
sn=`ps -ef | grep $program | grep -v grep |awk '{print $2}'` #获得进程端口号
if [ "${sn}" = "" ] #如果为空,表示进程未启动
then
nohup /home/oracle/XXXX & #后台启动进程
echo start ok !
else
echo running
fi
sn=`ps -ef | grep $program | grep -v grep |awk '{print $2}'` #获得进程端口号
if [ "${sn}" = "" ] #如果为空,表示进程未启动
then
nohup /home/oracle/XXXX & #后台启动进程
echo start ok !
else
echo running
fi
脚本二:
#!/bin/sh
ps -ef |grep ./FileServer > /dev/null 2>&1 #检测进程写入/dev/null
if [ $? -eq 0 ] #0为正常
then
echo logprocess run ok!
else
nohup /home/oracle/XXXX &
ps -ef |grep ./FileServer > /dev/null 2>&1 #检测进程写入/dev/null
if [ $? -eq 0 ] #0为正常
then
echo logprocess run ok!
else
nohup /home/oracle/XXXX &
echo start ok !
fi
脚本三:
#!/bin/sh
count=`ps -fe |grep "a.out" | grep -v "grep" | wc -l`
if [ $count -lt 1 ]; then
/root/sh/restart.sh
脚本四:
PNAME="authd"
PATHNAME=/root/cauthd/build/
LENGTH=`ps -ef|grep "$PNAME"|grep -v grep|cut -b 49-200|wc -c `
if test $LENGTH -eq 0
then
cd $PATHNAME
nohup $PNAME >/dev/null
LENGTH=`ps -ef|grep "$PNAME"|grep -v grep|cut -b 49-200|wc -c `
if test $LENGTH -eq 0
then
cd $PATHNAME
nohup $PNAME >/dev/null
脚本五:
#! /bin/bash
echo "请输入进程名:"
read process
echo "你要查找的进程是 $process ,正在查找..."
ps > text1
grep "$process" text1
declare -i a=$?
if [ $a -eq 0 ]
then
echo "该进程存在"
else
echo "该进程不存在"
fi
rm text1
read process
echo "你要查找的进程是 $process ,正在查找..."
ps > text1
grep "$process" text1
declare -i a=$?
if [ $a -eq 0 ]
then
echo "该进程存在"
else
echo "该进程不存在"
fi
rm text1