expect可以让一些交互的任务自动完成,我们可以将一些交互过程写入脚本,ssh登录就是一个简单的实现,下面将介绍expect的用法。

1 安装

yum install -y expect

2 语法介绍

expect - send

这两个指令会配合使用,当expect接收到一个和预期字符串相匹配的输入,会执行send指令,send会发出字符串或者对应的指令。

执行如下脚本

expect "yes\n"
send "What you type in is  $expect_out(buffer)"
send "The correct input is  $expect_out(0,string)"
#note:$expect_out(buffer)储存了所有对expect的输入,$expect_out(0,string)储存了所有相匹配值的输入

当你输入为yes时,输出结果为

yes
What you type in is  yes
The correct input is  yes

当你输入第一次不为所预期的字符串时,进程会继续等待,直到你输入为yes:

dd
yes
What you type in is  dd
yes
The correct input is  yes

expect也可像switch的语句一样:

expect {
    "1\n" {send "one\n"}
    "2\n" {send "two\n"}
    "3\n" {send "three\n"}
}

spawn

spawn后面会加上一个命令,打开一个新的进程。

spawn ssh@root 192.168.1.1

interact

执行完成后保持交互状态,把控制权交给控制台,这个时候就可以手工操作了。如果没有这一句登录完成后会退出,而不是留在远程终端上。

3 自动登录脚本示例

#!/usr/bin/expect
set timeout -1             #设置超时时间,-1为用不超时
set ip "192.168.100.1"
set passwd "root"
set user "root"
spawn ssh $user@$ip
expect {
"*yes/no" {send "yes\r";exp_continue}     #exp_continue可以继续执行下面的匹配
"*password" {send "$passwd\r"}
}
expect "login"
send "pwd\r"               #登录成功执行pwd命令
interact

posted on 2018-08-06 09:29  想要早睡的彼得潘  阅读(821)  评论(0编辑  收藏  举报