expect使用小结

1)使用expect命令在shell脚本中实现的简单登陆

#!/bin/bash
#!/usr/bin/expect -f

if [ $# != 3 ];then
    echo "Usage: cmd [host] [user] [passwd]"
fi

host=$1
user=$2
password=$3

echo
echo $user@$host
echo

#eof {exit 0}
auto_ssh_copy_id ()
{
    expect -c "set timeout -1;
        spawn ssh $2;
        expect
        {
            "*yes/no" {send "yes\r"; exp_continue}
            "*password:" {send "$1\r"}
        };
        interact
    "
}

#auto_ssh_copy_id $password $user@$host

set ip [lindex $argv 0 ]
set password [lindex $argv 1 ]
set timeout 10
spawn ssh root@$ip
    expect {
        "*yes/no" { send "yes\r"; exp_continue}
        "*password:" { send "$password\r" }
    }
interact

exit 0

    2)expect脚本简单使用(*.exp 脚本)

    #!/usr/bin/expect -f
    
    set ip 192.168.2.101
    set password "321"
    
    spawn ssh root@$ip
    
    expect {
         "*yes/no" {send "yes\r"; exp_continue}
         "*password:" {send "$password\r" }
    }
    
    expect "#*"
    send "passwd\r"
    
    expect {
        "Enter*" { send "123\r"; exp_continue}
        "Retype*" { send "123\r"; exp_continue}
    }
    
    send "exit\r"
    expect eof
    
    exit


    3)自动登陆shell代码段

    ……
    
    auto_ssh_login ()
    {
        expect -c "
            set timeout 5
    
            spawn sshpass -p $2 ssh -o StrictHostKeyChecking=no -p 39000 root@$1
    
            send "passwd\\r"
            
            expect {
                Enter* {send -- $3\r; exp_continue}
                Retype* {send -- $3\r; exp_continue}
            }
    
            send "exit\\r"
            expect eof
        "
    }
    
    ……


    暂时更新到这里, 继续研究

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值