首页 > 其他 > 详细

expect的使用

时间:2020-07-21 12:35:59      阅读:67      评论:0      收藏:0      [点我收藏+]

**expect**

**功能:**

- 在脚本中自动捕获一些信息人,然后自动输入内容

**安装**

- yum install expect -y

**关键字**

- spawn:执行一个命令
- expect:设置等待出现的字符
- send:发现等待的字符之后,执行的动作

**例子:执行ssh 192.168.31.64 ip addr 命令,执行过程中出现 (yes/no)字符发送yes**

```shell
写法1
spawn ssh 192.168.31.64 ip addr
expect "(yes/no)" {send "yes\r"}

写法2
spawn ssh 192.168.31.64 ip addr
expect "(yes/no)"
send "yes\r"
```

 

**案例:编写expect脚本,实现获取远程主机的IP地址**

```shell
#!/usr/bin/expect

set timeout 10
spawn ssh 192.168.31.64 ip addr
expect "(yes/no)" {send "yes\r"}
expect "password:" {send "123456\r"}
expect eof

```

**符号**

- \r:回车
- \n:换行

 

**定义变量**

- sent 变量名 变量值

 

**引用变量**

- puts $变量名

 

**shell和expect结合有两种方式**

- 在shell脚本中写expect代码
- 在shell脚本中调用expect脚本

 

**在shell脚本中写expect代码**

```shell
#!/bin/bash

ip=192.168.31.64

/usr/bin/expect<<eof
spawn scp /etc/passwd root@$ip:/tmp
set timeout 10
expect {
"(yes/no)" {send "yes\r"; exp_continue}
"password:" {send "123456\r"}
}
expect eof
exit
eof

echo "send file complate"
```

 

**在shell脚本中调用expect脚本**

expect脚本内容

```
#!/usr/bin/expect

set timeout 10
set ip 192.168.31.64
spawn scp /etc/passwd root@$ip:/tmp
expect "(yes/no)" {send "yes\r"}
expect "password:" {send "123456\r"}
expect eof
exit
```

shell脚本内容

```
#!/bin/bash

echo "start "
expect 1.exp
echo "complate"
```

 

expect的使用

原文:https://www.cnblogs.com/fatzi/p/13353634.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!