需求:實現shell腳本對rsync的start|stop|restart
rsync pid所在路徑:/var/run/rsyncd.pid
rsync啓動命令:rsync --daemon
rsync進程停止命令:pkill rsync
文中通過判斷rsync pid所在路徑和進程狀態來實現rsync的start|stop|restart
1)腳本演示
[root@jason scripts]# cat rsync.sh
#!/bin/sh
#This is the launch script for rsync.
#-------------------------------------
#Author:jason
#QQ:760966297
#mile:[email protected]
#-------------------------------------
[ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit 1
PID_PATH=/var/run/rsyncd.pid
fun_usage(){
echo "Usage:$0 {start|stop|restart}"
exit 2
}
fun_start(){
if [ ! -e $PID_PATH ]; then
rsync --daemon
PORT=`netstat -lntup |grep rsync|wc -l`
[ $PORT -eq 2 ]&& action "Rsync is startup successful." /bin/true ||action "Rsync start failed." /bin/false;
else
action "Rsync is running." /bin/false
fi
}
fun_stop(){
if [ ! -e $PID_PATH ];then
action "Rsync is not run." /bin/false
else
while true
do
pkill rsync
sleep 2
PORT=`netstat -lntup |grep rsync|wc -l`
[ $PORT -eq 0 ]&&action "Rsync is stop successful." /bin/true && break
done
fi
}
fun_restart(){
if [ ! -e $PID_PATH ];then
action "Rsync is not run." /bin/false
exit 2
else
fun_stop >/dev/null
sleep 2
fun_start >/dev/null
PORT=`netstat -lntup |grep rsync|wc -l`
[ $PORT -eq 2 ]&&action "Rsync is startup successful." /bin/true || action "Rsync is restart failed." /bin/false
fi
}
case $1 in
start)
fun_start
;;
stop)
fun_stop
;;
restart)
fun_restart
;;
*)
fun_usage
;;
esac
2)腳本測試
#測試fun_usage函數
[root@jason scripts]# sh rsync.sh #<==運行腳本,腳本後面沒有加參數的提示
Usage:rsync.sh {start|stop|restart}
#測試start
[root@jason scripts]# sh rsync.sh start #<==啓動rsync
Rsync is startup successful. [ OK ]
[root@jason scripts]# netstat -lntup |grep 873
tcp 0 0 0.0.0.0:873 0.0.0.0:* LISTEN 98926/rsync
tcp 0 0 :::873 :::* LISTEN 98926/rsync
#測試stop
[root@jason scripts]# sh rsync.sh stop #<==關閉rsync
^[[ARsync is stop successful. [ OK ]
[root@jason scripts]# netstat -lntup |grep 873
#測試restart
[root@jason scripts]# sh rsync.sh restart #<==重啓rsync,但是rsync進程未開啓,提示報錯
Rsync is not run. [FAILED]
[root@jason scripts]# sh rsync.sh start #<==先啓動rsync
Rsync is startup successful. [ OK ]
[root@jason scripts]# sh rsync.sh restart #<==然後再測試restart
Rsync is startup successful. [ OK ]