Linux操作-shell数据分发脚本

脚本主体内容

#!/bin/env bash

### 打印日志
function printInfo(){
	echo "[$(date +'%F %T')] [INFO]: $1"
}

### 打印失败日志
function printError(){
	echo "[$(date +'%F %T')] [ERROR]: $1"
	exit 1
}

# 获取输入参数个数,如果没有参数,直接退出
pocunt=$#
if [[ ${pocunt} -lt 1 ]]; then
	printError "not enough arguement!"
fi

# 可以将服务器统一用户名提取出来
server_name=root

# 需要遍历的所有服务器ip或映射名称
hosts="
node2
node3
"

while read host; do
	# 判断传入内容是否为空,为空返回循环判断
	if [[ -z ${host} ]]; then
		continue
	fi
	# 开始遍历传入的目录
	for file in $@; do
		# 判断文件是否存在
		if [[ -e ${file} ]]; then
			# 获取父目录
			pdir=$(cd -P $(dirname ${file}); pwd)
			printInfo "pdir=${pdir}"
			# 获取当前文件的名称
			fname=$(basename ${file})
			printInfo "fname=${fname}"
			# 通过ssh执行命令: 在${host}主机上递归创建文件夹(如果存在该文件夹)
			ssh ${host} "mkdir -p ${pdir}"
			# 远程同步文件至$host主机的目录下
			scp -r ${pdir}/${fname} ${server_name}@${host}:${pdir}
		else
			printError "${file} does not exists!"
		fi
	done
done <<< "${hosts}"

建议脚本存放位置: /export/onekey
脚本名称为: xsync
配置环境变量

echo "export ONEKEY=/export/oneKey" >> /etc/profile
export "export PATH=$PATH:$ONEKEY" >> /etc/profile
# 刷新环境变量
source /etc/profile
# 使用方法
xsync 要分发的数据目录或文件
posted @ 2024-01-07 19:42  OnePandas  阅读(20)  评论(0)    收藏  举报