用expect写ssh交互式脚本

脚本内容如下:

#!/usr/local/expect

set timeout 60

set host 192.168.56.130

set user root

set pass 111111

spawn ssh $user@$host

expect {

“(yes/no)?” {

send "yes\n"


expect "password:"


  send "$pass\n"

}

“password” {

send "$pass\n"

}

}

expect “#”

send “id\n”

expect “root”

send_user “you are root”

interact
第一次执行:

expect ssh.exp

注意:脚本为expect脚本,请使用expect执行文件名。

结果如下:

大家看到:yes已经输入成功,但是“password”没有出来。为什么呢?我们通过ssh –v 192.168.56.130来查看一下。

结果如下:

大家看到:ssh在gss认证时不动了。

解决办法:

登陆到192.168.56.130机器上,编辑/etc/ssh/sshd_config,修改如下内容:

GSSAPIAuthentication no

GSSAPICleanupCredentials no

UseDNS no

保存退出,重启ssh服务。

service sshd restart

 

重新执行脚本

expect ssh.exp

结果如下: