Linux expect ssh自动登录

安装expect命令:

yum install expect -y

创建exp脚本,注意首行为 #!/usr/bin/expect,并修改权限为750

touch ssh.exp
chmod 750 ssh.exp

拷贝以下内容到ssh.exp文件

#!/usr/bin/expect

#参数校验
if { $argc != 3 } {
    send_user "usage: ./ssh.exp <host> <user> <password> \n"
    exit
}

#变量设置
#log_file login.log
set host [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set newpassword "mikepeng"
set timeout 30

#过滤关键字
set key_password "*password: "
set key_yesorno "*(yes/no)? "

#函数定义
proc func_login {password newpassword} {
    expect {
        "*(yes/no)? " {
            send "yes\r";
            exp_continue
        }
        "*password: " {
            send "$password\r";
            exp_continue
        }
        "*]\$ " {
            #send_log "\r>>>>>>>>>> Login in SUCCESS <<<<<<<<<<<<\r";
            puts "\r>>>>>>>>>> Login in SUCCESS <<<<<<<<<<<<\r"
        }
        "Permission denied*" {
            send_error "\r>>>>>>>>>> Login in FAILED <<<<<<<<<<<<\r";
            close;
            exit
        }
        "*UNIX password: " {
            send "$password\r";
        }
        "New password: " {
            send "$newpassword\r";
        }
        "Retype new password: " {
            send "$newpassword\r";
        }
    }
}

####################开始执行#####################
spawn ssh $user@$host
func_login $password $newpassword

#todo
send "touch test.txt\r"


#结束退出
send "exit\r"
expect eof

执行ssh.exp文件

./ssh.exp 192.168.31.101 thinker 123456
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值