expect是一个自动交互功能的工具。expect是开了一个子进程,通过spawn来执行shell脚本,监测到脚本的返回结果,通过expect判断要进行的交互输入内容(send)。
1.安装expect
(1)使用apt-get安装
需要先安装tcl:
apt-get install tcl
apt-get install expect
(2)使用deb包安装
登录网站搜索tcl和expect的deb包;
https://www.debian.org/distrib/packages
上述网站涉及到三个deb包:libtcl, tcl-expect,expect,都是armhf类型的。
安装过程如下:
dpkg -i /expect_tcl/libtcl8.6_8.6.6+dfsg-1+b1_armhf.deb
dpkg -i /expect_tcl/tcl-expect_5.45-7+deb9u1_armhf.deb
dpkg -i /expect_tcl/expect_5.45-7+deb9u1_armhf.deb
(3)使用wget安装
使用源码安装的方法:
Expect工具是依赖tcl的。首先下载并安装tcl,这里安装8.4.19版本。
# wget https://sourceforge.net/projects/tcl/files/Tcl/8.4.19/tcl8.4.19-src.tar.gz
# tar zxvf tcl8.4.19-src.tar.gz
# cd tcl8.4.19/unix && ./configure
# make
# make install
然后下载expect并安装。
# wget http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz
# tar zxvf expect5.45.tar.gz
# cd expect5.45
# ./configure --with-tcl=/usr/local/lib --with-tclinclude=../tcl8.4.19/generic
# make
# make install
# ln -s /usr/local/bin/expect /usr/bin/expect
注意这里的configure命令需要使用–with-tclinclude选项传入tcl安装包中的generic文件夹路径。
---------------------
原文:https://blog.csdn.net/wangtaoking1/article/details/78268574?utm_source=copy
2.使用expect
2.1一个简单的输入密码操作
#!/usr/bin/expect
set timeout 100
set password "123456"
spawn sudo rm -rf zzlogic
expect "password:"
send "$password\n"
interact
说明:
第一行#!/usr/bin/expect表示使用expect的shell交互模式
set是对变量password赋值
set timeout 100:设置超时时间为100秒,如果要执行的shell命令很长可以设置超时时间长一些。expect超过超时时间没有监测到要找的字符串,则不执行,默认timeout为10秒
spawn在expect下执行shell脚本
expect对通过spawn执行的shell脚本的返回进行判断,是否包含“”中的字段
send:如果expect监测到了包含的字符串,将输入send中的内容,\n相当于回车
interact:退出expect返回终端,可以继续输入,否则将一直在expect不能退出到终端
2.2:项目中使用expect完成自动输入密码
(1)创建自动输入密码的expect脚本
#!/usr/bin/expect -f
##########################################
#时间:2018年10月12日16:23:43 ldq
#功能;从服务器拷贝镜像程序,自动输入密码
###########################################
set cp_type [lindex $argv 0 ]
set route_user [lindex $argv 1 ]
set route_ip [lindex $argv 2 ]
set route_dir [lindex $argv 3 ]
set host_dir [lindex $argv 4 ]
set password [lindex $argv 5 ]
set timeout 80
if { $cp_type == "rsync" } {
spawn /usr/bin/rsync -av $route_user@$route_ip:$route_dir $host_dir
} else {
if { $cp_type == "scp" } {
spawn /usr/bin/scp -r $route_user@$route_ip:$route_dir $host_dir
}
}
expect {
"(yes/no)" { send "yes\n"; exp_continue }
"password:" { send "$password\n" }
}
expect eof
exit
(2)shell脚本中调用expect脚本
expect /usr/bin/getfw_exp rsync $ROUTE_USER $ROUTE_IP $ROUTE_FPGA_B_DIR $HOST_DIR $ROUTE_PWD