1. 程式人生 > >SFTP上傳和下載檔案指令碼

SFTP上傳和下載檔案指令碼

運維工作中,遠端上傳或下載檔案很常用,我分享下我經常使用的sftp指令碼

#!/bin/bash

SCRIPT_NAME=`basename $0`
CURRENT_DIR=$(cd "$(dirname "$0")";pwd)

execute_sftp_cmd()
{
    local host_ip=$1
    local user_name=$2
    local user_password=$3
    local file_name=$4
    local file_dir=$5
    local cmd=$6
 
    local log_file=${CURRENT_DIR}
/execute_sftp_cmd.log # 如果密碼中包含$符號,需要轉義以下 user_password=`echo ${user_password} | sed 's/\\$/\\\\$/g'` /usr/bin/expect <<EOF > ${log_file} set timeout -1 spawn sftp ${user_name}@${host_ip}:${file_dir} expect { "
(yes/no)?" { send "yes\n" expect
"*password:" { send "${user_password}\n"} } "*assword:" { send "${user_password}\n" } } expect "Changing to:*" send "${cmd} ${file_name}\n" expect "100%" send "exit\n" expect eof EOF cat ${log_file} | grep -iE "denied|error|failed"
>/dev/null if [ $? -eq 0 ];then echo "Script execute failed!" return 1 fi return 0 } execute_sftp_cmd "[email protected]"

舉一個下載檔案的例子,上傳檔案也是支援的

[[email protected] opt]# ./execute_sftp_cmd.sh 192.168.233.134 root SDjefwfefw profile /etc get
[[email protected] opt]# ll
total 1728
-rw-r--r-- 1 root root     392 Sep 24 19:28 execute_sftp_cmd.log
-rwx------ 1 root root    1053 Sep 24 19:28 execute_sftp_cmd.sh
-rw-r--r-- 1 root root    9991 Sep 24 19:28 profile
[[email protected] opt]# cat execute_sftp_cmd.log 
spawn sftp [email protected]:/etc
Password: 
Connected to 192.168.233.134.
Changing to: /etc
get profile
sftp> get profile
Fetching /etc/profile to profile
/etc/profile                                                         100% 9991    11.1MB/s   00:00    
exit
sftp> exit