**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
"}
写法2
spawn ssh 192.168.31.64 ip addr
expect "(yes/no)"
send "yes
"
```
**案例:编写expect脚本,实现获取远程主机的IP地址**
```shell
#!/usr/bin/expect
set timeout 10
spawn ssh 192.168.31.64 ip addr
expect "(yes/no)" {send "yes
"}
expect "password:" {send "123456
"}
expect eof
```
**符号**
-
:回车
-
:换行
**定义变量**
- 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
"; exp_continue}
"password:" {send "123456
"}
}
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
"}
expect "password:" {send "123456
"}
expect eof
exit
```
shell脚本内容
```
#!/bin/bash
echo "start "
expect 1.exp
echo "complate"
```