SFTP上传和下载文件脚本

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36485376/article/details/82831483

运维工作中,远程上传或下载文件很常用,我分享下我经常使用的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 "$@"

举一个下载文件的例子,上传文件也是支持的

[root@localhost opt]# ./execute_sftp_cmd.sh 192.168.233.134 root SDjefwfefw profile /etc get
[root@localhost 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
[root@localhost 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

猜你喜欢

转载自blog.csdn.net/weixin_36485376/article/details/82831483