- 安装rsync (一般服务器上应该自带的有rsync ,可使用
rsync
查看)
yum install rsync
# sudo yum install rsync
- 安装sshpass (这个要安装可以实现自动输入ssh密码,无需手动输入)
yum install sshpass
# sudo yum install sshpass
- 在
/www/wwwroot/test
新建r_test.sh
脚本文件
#!/bin/bash
# 设置SSH远程服务器的相关信息
REMOTE_SERVER="localhost"
REMOTE_PORT=22 #SSH端口
REMOTE_USERNAME="ssh用户名"
REMOTE_PASSWORD="ssh密码"
# 远程服务器文件夹
REMOTE_DIRECTORY="/www/wwwroot/test"
# 设置本地目标文件夹
LOCAL_FOLDER="/www/wwwroot/backup"
# 拉取下载:true,上传远程:false
IS_DW=true # 默认:拉取
# 设置要跳过的文件和文件夹
SKIP_DIRS=("log" "cache") # 要跳过的文件夹名称列表
SKIP_EXT=(".log" ".tmp") # 要跳过的文件扩展名列表
EXCLUDE_DIRS=""
for dir in "${SKIP_DIRS[@]}"; do
EXCLUDE_DIRS+="--exclude=${dir}/ "
done
EXCLUDE_EXT=""
for ext in "${SKIP_EXT[@]}"; do
EXCLUDE_EXT+="--exclude=*${ext} "
done
mkdir -p ${LOCAL_FOLDER}
echo $EXCLUDE_DIRS
echo $EXCLUDE_EXT
# rsync命令
# 判断是拉取下载还是上传
if [[ ${IS_DW} == true ]]; then
# 从远程服务器下载文件到本地
sshpass -p ${REMOTE_PASSWORD} rsync -avzP --delete --ignore-existing ${EXCLUDE_DIRS} ${EXCLUDE_EXT} -e "ssh -p ${REMOTE_PORT}" "${REMOTE_USERNAME}@${REMOTE_SERVER}:${REMOTE_DIRECTORY}/" ${LOCAL_FOLDER}
RES="下载完成!";
else
# 将本地文件上传至远程服务器
sshpass -p ${REMOTE_PASSWORD} rsync -avzP --delete --ignore-existing ${EXCLUDE_DIRS} ${EXCLUDE_EXT} -e "ssh -p ${REMOTE_PORT}" "$LOCAL_FOLDER/" "${REMOTE_USERNAME}@${REMOTE_SERVER}:${REMOTE_DIRECTORY}"
RES="上传完成!";
fi
echo ${RES}
exit
- 命令行执行脚本
cd /www/wwwroot/test
./r_test.sh
-
查看本地拉取下载的结果
image.png
image.png
- 2、直接使用命令行,不写脚本
# --ignore-existing 参数表示跳过目标文件夹中已经存在的文件,不进行传输。
rsync -avzP --ignore-existing -e 'ssh -p 22' /www/wwwroot/record.com root@远程服务器IP:/data/www/wwwroot/
# --exclude 参数表示要排除的文件夹或文件
rsync -avzP --ignore-existing --exclude='tmp/' --exclude='log/' -e 'ssh -p 22' /www/wwwroot root@远程服务器IP:/www/wwwroot/

网友评论