Fork me on GitHub

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

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

脚本源码

 1 #!/usr/bin/expect 2 set bridge_host "jumper.******.com" 
 3 set username "zhengbin" 
 4 set password "******" 
 5 set timeout 20
 6 
 7 spawn ssh "${username}@${bridge_host}" 
 8 expect { 
 9     "Password:" { 
10         send "${password}\n" 
11         expect { 
12             "verification code:" { 
13                 send_user "\nEnter verification code:" 
14                expect_user -re "(.*)\n" 
15                set veri_code $expect_out(1,string) 
16                send "${veri_code}\n" 
17                 expect { 
18                     "${username}@Jumper" { 
19                         send "r \r" 
20                     } 
21                 } 
22             } 
23         } 
24     } 
25 } 
26 interact

脚本解释

shell 脚本解释器

#!/usr/bin/expect

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

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

set

set timeout 20

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

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

set param_name1 1
set param_name2 "zhengbin"

spawn

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

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

expect

期望输出的字符串

send

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

分支

类似于 java 中的 switch

1 expect {
2     "case1" {
3         send "do something \n"
4     }
5     "case2" {
6         send "do something \n"
7     }
8 }

结束符

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

 

posted @ 2018-04-18 11:02  郑斌blog  阅读(1096)  评论(0编辑  收藏  举报