脚本名称

dnsnamed

脚本功能:

负责DNS服务器Named进程的启动、停止和状态信息采集等。

参数:start|stop|status

运行环境

OS:Linux

Shell:Bash Shell

开发背景

源码形式安装的一些程序,编译安装后执行进程不附带start|stop|status等启动参数,同时不可编辑,所以无法加入系统自启动列表。这时候,需要编写一个脚本,然后让脚本有start|stop|status等参数

启动脚本内容

#!/bin/bash
# chkconfig: 2345 20 80
# description: Start DNS Named Process.

RETVAL=0
prog=named
lockfile="/var/run/named.pid"
msgStoped="Named Process has been stopped!"
msgStarted="Named has been started!"
start(){
# determine if the named process is running,if running exit.or started Named process

#检查状态文件是否存在,如果文件存在,进程已经被启动,提示进程已经启动,否则,启动进程

[ -f "$lockfile" ]&& echo "One Named has been started" && exit 0
# start Named process in the background
/usr/local/sbin/named -g 1>/var/dns.log 2>&1 &
RETVAL=$?
[ "$RETVAL" == 0 ] && echo "$msgStarted" && touch /var/run/named.pid && exit 0
}

stop(){

  #如果状态文件存在,则执行杀进程命令,否则,提示进程没有运行。
        if [ -f "$lockfile" ]
        then
          {

 #系统进程中查询指定程序名的进程ID,并放到列表变量PID中,如果同名进程有多个PID则只放第一行的PID
           PID=`ps -ef|grep named|grep -v 'grep'|awk '{print $2}'`
           for id in $PID
             do
              rm -rf /var/run/named.pid
              kill -9 $id
              echo "Named Process $id has been ended!"
              exit 0
              done
           }
         else
           echo "Named Process is not running!"
           exit 1
         fi
         exit 0
}

status () {

# 查询状态文件named.pid是否存在,存在即该进程正在运行;文件不存在,则进程没有运行

        if [ -f "$lockfile" ]
        then
          echo "Named process is running!"
        else
          echo "Named Process is not running!"
        fi
        exit 0
}

case "$1" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        status)
                status
                ;;
        *)
                echo $"Usage: $0 {start|stop|status}"
                RETVAL=1
esac

可以通过命令行执行

注意:

dnsnamed stop 仅能停止一个Running状态的 Named进程,无法停止相同Named进程名称的多个Running状态的不同PID进程。
 

 

添加named脚本到/etc/init.d目录下

[root@linuxas42 sbin]#  cp dnsnamed /etc/init.d/

添加到系统自启动服务列表
[root@linuxas42 sbin]# chkconfig --add dnsnamed
[root@linuxas42 sbin]#

查看列表
[root@dnscache1 dnscap]# chkconfig --list|grep dnsnamed
dnsnamed        0:off 1:off 2:on 3:on 4:on 5:on 6:off
[root@linuxas42 sbin]#

 

验证启动目录脚本

#chkconfig: 2345 20 80

2345 为 init 级别 20 为进程启动级别 80 为进程关闭级别

/etc/rc2.d/ 、/etc/rc3.d/ 、/etc/rc4.d/  、/etc/rc5.d/  四个目录下

存在 S20dnsnamed 启动脚本 指向 ../init.d/dnsnamed 脚本

在  /etc/rc0.d  目录下存在关闭Named脚本

K80dnsnamed -> ../init.d/dnsnamed 脚本