如何在RHEL7中将shell脚本作为服务?

时间:2016-07-10 15:34:15

标签: linux bash shell

我有一个下面的脚本基本上开始|开始|停止|重新启动

脚本名称amr.sh 例如:我现在如何执行:./ amr.sh start

我想将此脚本作为服务:

#!/bin/bash
# chkconfig: 2345 20 80
# description: AMR Service shell script
# Author: NSK

# Source function library.
. /etc/init.d/functions

start() {
    # code to start app
    # example: daemon program_name &
        echo "Starting AMR service..... "
        daemon /root/amr/bin/LoggerServer &
        echo "Starting Logger...."
        sleep 2
        daemon /root/amr/bin/mediaController -i 192.168.117.119 &
        echo "Starting Mediacontroller....."
        sleep 4
        daemon /root/amr/bin/mstdaemon --daemon &
        echo "Starting Media Streamer...."
        sleep 4
        daemon /root/amr/bin/pcdaemon --daemon -i ens192 -f "'udp && portrange 3000-8000 && not(src host localhost)'" &
        sleep 3
        echo "Starting Packetcapture...."
        daemon /root/amr/bin/stund &
        echo "Starting Stun..."
        daemon /root/amr/bin/tdaemon &
        sleep 2
        echo "Starting Transcoder...."
        status LoggerServer
        status mediaController
        status mstdaemon
        status pcdaemon
        status stund
        status tdaemon
        echo "Started AMR services. "
}
stop() {
    # code to stop app
    # example: killproc program_name
        echo "Stopping AMR service..... "
        killproc LoggerServer
        echo "Stoping Logger..... "
        killproc mediaController
        echo "Stoping MediaController...."
        killproc mstdaemon
        echo "Stoping Mediastreamer..."
        killproc pcdaemon
        echo "Stoping Packet Capture....."
        killproc stund
        echo "Stoping Stun....."
        killproc tdaemon
        echo "Stoping Transcoder....."
        status LoggerServer
        status mediaController
        status mstdaemon
        status pcdaemon
        status stund
        status tdaemon
        echo "Stopped AMR service "
}

case "$1" in
    start)
       start
        echo "success AMR server startup"
       ;;
    stop)
       stop
       ;;
    restart)
       stop
       start
       ;;
    status)
       # code to check status of app comes here

      # example: status program_name
        status LoggerServer
        status mediaController
        status mstdaemon
        status pcdaemon
        status stund
        status tdaemon
       ;;
    *)
       echo "Usage: $0 {start|stop|status|restart}"
esac

exit 0

1 个答案:

答案 0 :(得分:0)

首先,将您的脚本复制到/usr/sbin/目录中。

/usr/sbin/amr

然后,在/usr/lib/systemd/system/目录中创建一个单元文件。

/usr/lib/systemd/system/amr.service

文件内容应为:

[Unit]
Description=AMR Service

[Service]
Type=simple
ExecStart=/usr/sbin/amr start
ExecReload=/usr/sbin/amr restart
ExecStop=/usr/sbin/amr stop

[Install]
WantedBy=multi-user.target

开始服务

systemctl start amr

检查状态

systemctl status amr

停止服务

systemctl stop amr

重新启动服务

systemctl reload amr

启动时启用

systemctl enable amr

启动时禁用

systemctl disable amr