在使用一些Linux命令的时候经常需要根据提示输入一些信息,如yes,才能继续执行。如使用scp 复制一个文件到远程地址时需要输入"yes"以及“用户的账号密码”等信息。如下图:
当在调试某些功能时这个命令可能会多次输入,很繁琐。如何减少步骤呢?答案使用:expect命令。
expect需要在linux中额外安装(需要tcl和expect),如下:
http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz/download
http://nchc.dl.sourceforge.net/sourceforge/tcl/tcl8.4.11-src.tar.gz
cd tcl8.4.11/unix/
./configure --prefix=/usr/tcl --enable-shared
make
make install
cd expect5.45
./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=../tcl8.4.11/generic/
make
make install
ln -s /usr/tcl/bin/expect /usr/expect/bin/expect
然后编写shell脚本实现仅输入一次的拷贝:
name:expect_test.sh
--------------------------------------------------
#!/usr/local/bin/expect
spawn scp 1.txt 192.168.131.124:/tmp
###############################################
# expect 这个本身并不支持if语法,如果哪位会实现这样的方式,烦请分享一下
#if [ `expect "The authenticity"` ];then
# send "yes\r"
#fi
#if [ `expect "password:"` ];then
# send "Ĝë\r"
#fi
expect "The authenticity"
send "yes\r"
#发送yes
expect "password:"
send "Ĝë\r"
#发送密码
expect eof
最后执行这个脚本就能实现直接拷贝了。