expect详解及自动登录脚本的实现

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

转载于:https://www.cnblogs.com/panyouming/p/9415158.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值