rsync 使用ssh远程命令拉取 和 上传 远程服务器文件到本

2023-07-12  本文已影响0人  阿然学编程
yum install rsync

# sudo yum install rsync
yum install sshpass

# sudo yum install sshpass
#!/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
# --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/
image.png
上一篇 下一篇

猜你喜欢

热点阅读