您的位置:首页 > 运维架构 > Shell

在shell脚本中使用expect实现scp传输问题

2016-11-09 21:41 746 查看

1.安装expect

expect用于shell脚本中自动交互,其是基于tcl编程语言的工具。所以安装expect首先安装tcl。本文中使用的是expect5.45tcl8.6.6

安装tcl

[root@tseg0 /]$ mkdir /tools
[root@tseg0 /]$ tar -zxvf tcl8.6.6-src.tar.gz
[root@tseg0 /]$ cd tcl8.6.6/unix/
[root@tseg0 /]$ ./configure
[root@tseg0 /]$ make
[root@tseg0 /]$ make install


安装expect

[root@tseg0 /]$ cd /tools
[root@tseg0 /]$ tar -zxvf expect5.45.tar.gz
[root@tseg0 /]$ cd expect5.45/
[root@tseg0 /]$ ./configure --with-tcl=/usr/local/lib/ --with-tcl include=/tools/tcl8.6.6/generic/
[root@tseg0 /]$ make
[root@tseg0 /]$ make install


shell脚本实现scp传输

命令解释

-c 表示可以在命令行下执行except脚本;

spawn 命令激活一个unix程序来交互,就是在之后要执行的命令;

expect “aaa” 表示程序在等待这个aaa的字符串;

send 向程序发送字符串,expect和send经常是成对出现的,比如当expect“aaa”的时候,send“bbb”。

执行脚本

#! /bin/sh
expect -c "
spawn scp -r /home/tseg/hello $name@10.103.240.33:/home/$name/
expect {
\"*assword\" {set timeout 300; send \"$pass\r\"; exp_continue;}
\"yes/no\" {send \"yes\r\";}
}
expect eof"


解释:

第二行: -c 表示可以不用与控制台交互;

第三行:spawn激活一个scp的unix程序;

第五行:expect期待含有“assword”的字符串,设置连接时间最大为300毫秒,如果出现这个字符串,就send 变量pass代表的密码字符串, exp_continue表示执行下面的匹配;

第六航:expect期待含有“assword”的字符串,设置连接时间最大为300毫秒,如果出现这个字符串,就send 变量pass代表的密码字符串;

第八行:表示结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell 脚本