Bash 远程拷贝文件的函数

需安装 expect 才能正常使用。

yum install -y expect;

#!/usr/bin/env bash
#远程拷贝文件
set -e;

#拷贝远程文件到本地
EXPECT_CP_R(){
  local EXUSR=${1}
  local EXHOST=${2}
  local EXPWD=${3}
  local R_FILE=${4}
  local L_FILE=${5}

  expect -c "
    set timeout 300
    spawn scp -qr ${EXUSR}@${EXHOST}:${R_FILE} ${L_FILE}
    expect {
      not known {send_user [exec echo -e Erro:Host not known\n];exit}
      Connection refused {send_user [exec echo -e Erro:Connection refused\n];exit}
      (yes/no)? {send yes\r;exp_continue}
      password: {send ${EXPWD}\r;exp_continue}
      Permission denied {send_user [exec echo -e Erro:Wrong passwd\n];exit}
      ]* {send \r}
      >* {send \r}
    }
  "
}

#拷贝本地文件到远程
EXPECT_CP_L(){
  local EXUSR=${1}
  local EXHOST=${2}
  local EXPWD=${3}
  local L_FILE=${4}
  local R_FILE=${5}

  expect -c "
    set timeout 300
    spawn scp -qr ${L_FILE} ${EXUSR}@${EXHOST}:${R_FILE}
    expect {
      not known {send_user [exec echo -e Erro:Host not known\n];exit}
      Connection refused {send_user [exec echo -e Erro:Connection refused\n];exit}
      (yes/no)? {send yes\r;exp_continue}
      password: {send ${EXPWD}\r;exp_continue}
      Permission denied {send_user [exec echo -e Erro:Wrong passwd\n];exit}
      ]* {send \r}
      >* {send \r}
    }
  "
}

发表评论

邮箱地址不会被公开。 必填项已用*标注

Captcha Code