expect
功能:
- 在脚本中自动捕获一些信息人,然后自动输入内容
安装
- yum install expect -y
关键字
- spawn:执行一个命令
- expect:设置等待出现的字符
- send:发现等待的字符之后,执行的动作
例子:执行ssh 192.168.31.64 ip addr 命令,执行过程中出现 (yes/no)字符发送yes
写法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地址
#!/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代码
#!/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"
欢迎关注:
wwww.geekyunwei.com 极客运维