Linux expect 使用(免密登录跳板机)

时间:2023-03-08 20:29:57

登录公司的跳板机是挺麻烦的事,首先要ssh,然后输入密码,有的公司可能还要动态密码,前两步操作都是固定的,所以能免去前两步的操作就会方便很多(线上出问题也能尽快登上去,免得紧张密码一直输错,哈哈哈)。

脚本源码

 #!/usr/bin/expect set bridge_host "jumper.******.com"
set username "zhengbin"
set password "******"
set timeout spawn ssh "${username}@${bridge_host}"
expect {
"Password:" {
send "${password}\n"
expect {
"verification code:" {
send_user "\nEnter verification code:"
expect_user -re "(.*)\n"
set veri_code $expect_out(,string)
send "${veri_code}\n"
expect {
"${username}@Jumper" {
send "r \r"
}
}
}
}
}
}
interact

脚本解释

shell 脚本解释器

#!/usr/bin/expect

脚本中首先引入解释文件,表明使用哪种 shell 解释器

(shell 是系统的用户界面,提供了用户与内核进行交互操作的一种接口)

set

set timeout 

用来设置响应的时间,如果脚本执行或网络问题超过了这个时间,则将不再执行

set 主要用来设置变量,如:

set param_name1
set param_name2 "zhengbin"

spawn

开启会话,接下来通过 expect ... send 来执行交互操作

spawn 后跟上命令,表示开启一个操作会话

expect

期望输出的字符串

send

发送交互字符串,回车为 /n,注意空格

分支

类似于 java 中的 switch

 expect {
"case1" {
send "do something \n"
}
"case2" {
send "do something \n"
}
}

结束符

expect eof

等待结束执行,若没有该结束符,脚本可能没有执行完毕就提前退出了

interact

执行完成后,保持控制台的交互状态,可以继续手动输入信息

参考资料

[1] shell 解释器:https://blog.csdn.net/tzy5210/article/details/58603765

[2] Linux expect:https://blog.csdn.net/houmou/article/details/53102051

[3] Linux shell实现ssh自动登录:https://www.jianshu.com/p/b1e0f2242f89