ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

expect的使用

2020-07-21 10:33:13  阅读:261  来源: 互联网

标签:shell ip 192.168 send expect 使用 yes


**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"
```

 

标签:shell,ip,192.168,send,expect,使用,yes
来源: https://www.cnblogs.com/fatzi/p/13353634.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有