跨服务传输文件需要手动输入密码很麻烦,在使用定时任务时更头痛。下面介绍下使用spawn scp进行ssh跨服务器传输。
准备工作:需要安装tcl8.6.12-src.tar.gz、expect5.45.4.tar.gz两个包
例如:从A服务器向B服务器传文件,两个安装包安装在A服务器即可。
1、tcl命令安装
下载tcl安装包:https://sourceforge.net/projects/tcl/files/Tcl/8.6.12/tcl8.6.12-src.tar.gz/download
tar -zxf tcl8.6.12-src.tar.gz
cd tcl8.6.12/unix/
./configure --prefix=/usr/tcl --enable-shared
make
make install
# 目录tcl8.6.12/unix/下的tclUnixPort.h复制到generic中
cp tclUnixPort.h ../generic/
2、安装expect
# 下载expect地址:https://jaist.dl.sourceforge.net/project/expect/Expect/5.45.4/expect5.45.4.tar.gz
tar -zxf expect5.45.4.tar.gz
cd expect5.45.4
# 配置expect的安装路径,--with-tcl为告诉configure脚本tcl解释器位置,--with-tclinclude为告诉脚本tcl头文件位置(此处需要根据系统架构指定架构)
./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=../tcl8.6.12/generic
./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=../tcl8.6.12/generic --build=arm-linux (指定arm, 系统是arm的)
make
make install
ln -s /usr/tcl/bin/expect /usr/expect/bin/expect
3、写入环境变量
vi /etc/profile
# 写入下面内容内容
export PATH=$PATH:/usr/expect/bin/
# 更新配置文件
source /etc/profile
4、验证
输入expect回车,看是否进入形如expect1.1>这样的命令行。
5.shell脚本
1.centos使用的
#!/usr/expect/bin/expect
#设置连接时长
#set timeout 10
#将本机/data/upload/下的A,B,C 传输到B服务器的/data/uploaad目录下,不加{A,B,C} ,是将/data/upload/目录下所以文件传到B服务器
spawn scp -p -r /data/upload/{A,B,C} root@B服务IP:/data/uploaad
expect "*password:"
#设置B服务器访问密码
send "B服务器访问密码\r"
expect "100%"
expect eof
2.ubuntu系统使用
#!/usr/expect/bin/expect
#set timeout 10
spawn scp -p -r /data/maildata root@B服务IP:/data/uploaad
expect "*password:"
send "B服务器访问密码\r"
expect "100%"
expect eof