shell实战_Rsync服务启停的脚本开发

发布时间 2023-10-10 11:02:26作者: WeChat2834
Rsync服务启停实际案例
Rsync服务启停脚本开发

1.检测环境

2.检测文件

[root@localhost tmp]# rpm -qa rsync
rsync-3.1.2-12.el7_9.x86_64
[root@localhost tmp]# ls -l /etc/rsyncd.conf
-rw-r--r--. 1 root root 458 12月 16 2022 /etc/rsyncd.conf
[root@localhost tmp]# 
[root@localhost tmp]# ls -l /usr/lib/systemd/system/rsy*
-rw-r--r--. 1 root root 237 12月 16 2022 /usr/lib/systemd/system/rsyncd.service
-rw-r--r--. 1 root root 220 12月 16 2022 /usr/lib/systemd/system/rsyncd@.service
-rw-r--r--. 1 root root 138 12月 16 2022 /usr/lib/systemd/system/rsyncd.socket
-rw-r--r--. 1 root root 465 5月  31 2022 /usr/lib/systemd/system/rsyslog.service
[root@localhost tmp]# vim rsyncd.service  ####系统自带的一个rysnc启停服务文件。

Unit

3.检测是否有rsync服务

[root@localhost tmp]# netstat -tunlp|grep 873
[root@localhost tmp]# 
###没服务就启动服务
[root@localhost tmp]# /usr/bin/rsync --daemon  ###开启服务
[root@localhost tmp]# netstat -tunlp|grep 873
tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN      12334/rsync         
tcp6       0      0 :::873                  :::*                    LISTEN      12334/rsync         
[root@localhost tmp]# 
root@localhost tmp]# pkill rsync         ####用pkill 和killall都可以
[root@localhost tmp]# netstat -tunlp|grep 873
[root@localhost tmp]# 

4.参考系统自带的启停服务脚本,开发

/etc/init.d/network

5.脚本开发

[root@localhost tmp]# cat /etc/init.d/test_rsync.sh 
#!/bin/bash

#rsync启停脚本
#Auther:Mrxu


if [ "$#" -ne 1 ]; then

	echo "启停rsync脚本,你只能录入{start|stop|restart}"

	exit 1

fi


if [ "${1}" =  "start" ] ; then

	/usr/bin/rsync --daemon
	sleep 2
	if [ `netstat -tunlp|grep 873|wc -l ` -ge "1" ]; then
	echo "rsync服务启动成功"
	exit 0
	else 
	echo "rsync服务启动失败"
	exit 1
	fi

elif [ "${1}" = stop ] ; then
	if [ `netstat -tunlp |grep 873|wc -l` -ne 0 ] ; then
         killall rsync
	 sleep 2
		if [ `netstat -tunlp |grep 873 |wc -l` -eq "0" ]; then
		echo "rsync服务已停止"
		exit 0
		else
		echo "rsync 服务停止失败"
		exit 1
		fi
	else   
 		echo  "rsync未启动"
	fi


elif  [ "${1}" = "restart" ] ; then
	if [ `netstat -tunlp|grep 873|wc -l` -ne 0 ]; then
	killall rsync
	fi
	stopvar=`netstat -tunlp|grep 873|wc -l`
	sleep 1
	/usr/bin/rsync --daemon
	sleep 1
	startvar=`netstat -tunlp|grep 873|wc -l`
	echo stopvar:$stopvar--------------startvar :$startvar
	if [ $stopvar -eq "0" -a ${startvar} -ge "1"  ]; then
	echo "rsync服务已经重启成功"
	exit 0
	else
	echo "rsync服务重启失败"
	exit 1
	fi
else
	echo "启停rsync服务,只能录入{start|stop|restart}"
	exit 1
fi

[root@localhost tmp]# bash /etc/init.d/test_rsync.sh  start
rsync服务启动成功
[root@localhost tmp]# bash /etc/init.d/test_rsync.sh  stop
rsync服务已停止
[root@localhost tmp]# bash /etc/init.d/test_rsync.sh  restart
stopvar:0--------------startvar :2
rsync服务已经重启成功
[root@localhost tmp]# bash /etc/init.d/test_rsync.sh  stop
rsync服务已停止
[root@localhost tmp]# bash /etc/init.d/test_rsync.sh  stop
rsync未启动
[root@localhost tmp]# 

注意,条件判断,如果是字符比较用 =这类符号,如果是数字才用eq,gt,...这类