随笔-开发环境-bashrc_work-使用expect实现免密登录/上传文件/下载文件

免密上传文件 mup

利用shift支持多个文件

usage: mup file1 file2 ... 192.168.78.123 passwd(可选) ssh端口号(可选)

======
mup() {
    local file=()
    local ssh_opts="-o PasswordAuthentication=yes -o GSSAPIAuthentication=no -o PubkeyAuthentication=no -o PreferredAuthentications=password"
   
    echo $#
 
    [[ $# -lt 2 ]] && return

    while [[ $# -gt 0 ]]; do
        if [[ "$1" =~ ^([a-zA-Z0-9]+@[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) ]]; then
            break
        fi
        file+=("$1")
        shift
    done

    echo $#

    [[ $# -lt 1 ]] && return

    read host port pswd <<< $(awk -F'-' '{print $1, $2, $3}' <<< "$1")

    [[ -z "${file[@]}" || -z "$host" ]] && {
        echo "$0 [file] [host-port-password] (pswd port 可选) path"
        return
    }

    path=$2

    [[ "$host" =~ .*@.* ]] || host="root@"$host
    [[ -z "$port" ]] && port=22
    [[ -z "$pswd" ]] && pswd=Starnet@0592
    [[ -z "$path" ]] && path='~'

    expect -D 0 -c "set timeout 300; spawn scp -r -P $port $ssh_opts ${file[*]} $host:$path;
               expect {
                   "*yes/no*"  { send \"yes\r\"; exp_continue }
                   "*password:" { send \"$pswd\r\" }
               };
               expect eof;
               exit;
              "
}

免密下载文件 mxz

usage: mxz 192.168.78.123 file(仅支持一个文件) passwd(可选) ssh端口号(可选)

======
mxz() {
    
    local host=$1
    local file=$2
    local ssh_opts="-o PasswordAuthentication=yes -o GSSAPIAuthentication=no -o PubkeyAuthentication=no -o PreferredAuthentications=password"

    [[ $# -eq 0 ]] && return

    read host port pswd <<< $(awk -F'-' '{print $1, $2, $3}' <<< "$1")

    [[ -z "$file" || -z "$host" ]] && {
        echo "$0 [host-port-password] (pswd port 可选) [file]"
        return
    }

    [[ "$host" =~ .*@.* ]] || host="root@"$host
    [[ -z "$port" ]] && port=22
    [[ -z "$pswd" ]] && pswd=Starnet@0592
    [[ "$file" =~ ^/ ]] || file='~/'$file

    expect -D 0 -c "spawn scp -P $port $ssh_opts $host:$file .;
               expect {
                   "*yes/no*"  { send \"yes\r\"; exp_continue }
                   "*password:" { send \"$pswd\r\" }
               };
               expect eof;
               exit;
              "
}

免密登录服务器 mssh

usage: mssh 192.168.99.123

======
mssh() {
    local dest=$1
    local pswd=${2:-YOU_PASSWD}
    local port=${3:-22}

    [[ -z "$dest" || -z "$pswd" || -z "$port" ]] && {
        echo "$0 [dest] [pswd] [port]"
        return
    }

    [[ "$dest" =~ .*@.* ]] || dest="root@"$dest 

    expect -c "spawn ssh -o TCPKeepAlive=no -o ServerAliveInterval=30 -o GSSAPIAuthentication=no -o PubkeyAuthentication=no $dest -p $port;
               expect {
                   "*yes/no*"  { send \"yes\r\"; exp_continue }
                   "*password:" { send \"$pswd\r\" }
               };
               interact;
              "
}

posted @ 2024-04-12 17:09  LiYanbin  阅读(0)  评论(0编辑  收藏  举报