Linux使用expect实现远程拷贝文件

来源:互联网 发布:python中range 函数 编辑:程序博客网 时间:2024/06/05 03:12

1.背景

公司有个项目打算用Nginx集群的方式部署在三台服务器共 7个tomcat里,这样更新的时候如果一个一个去更新显然会很麻烦,现在打算用执行命令的方式把要需要更新的文件直接拷贝覆盖到那7个tomcat里去(不知道有没有比这种更简便的更新方式,如果有还望赐教)。一开始打算先把要更新的文件拷贝在其中一个主服务器的目录下,然后执行shell脚本用cp和scp的命令把文件拷贝到当前服务器和另外两个服务器的tomcat里,但是在执行到scp命令的时候会提示需要输入系统用户的密码,最后发现使用expect可以避免这个麻烦。

2.安装

安装的方式有很多,这里使用比较简便的rpm方式来安装,安装之前需要先检查一下系统是否已经安装过expect:

#查看是否有安装过tcl(expect需要依赖tcl)

rpm -qa | grep tcl

#查看是否有安装过expect

rpm -qa | grep expect

如果有输出显示已经安装过了,那就不用安装了。

安装需要准备的工具:

先安装tcl:

rpm -ivh tcl-*

再安装expect:

rpm -ivh expect-5.44.1.11-1.240.x86_64.rpm 

3.脚本

dealrsync.sh:把本机项目拷贝到本机的tomcat,循环执行远程拷贝的expect脚本

#/bin/sh#同步各服务器的项目#源文件src_file=testproject#把项目复制到本主机服务器的tomcatcp -pr $src_file /home/was/webtest/tom1cp -pr $src_file /home/was/webtest/tom2cp -pr $src_file /home/was/webtest/tom3#把项目复制到其他主机服务器的tomcat#格式:ip 用户名 密码 目标文件地址remoteserver_list="remoteserver_list.conf"cat $remoteserver_list | while read linedo  host_ip=`echo $line|awk '{print $1}'`  username=`echo $line|awk '{print $2}'`  password=`echo $line|awk '{print $3}'`  dest_file=`echo $line|awk '{print $4}'`  ./remotescp.sh $src_file $username $host_ip $dest_file $passworddone

rsyncfiles.sh:把本地文件拷贝到远程服务器

#!/usr/bin/expectif {$argc < 2} {    send_user "usage: $argv0 src_file username ip dest_file password\n"    exit}set src_file [lindex $argv 0]set username [lindex $argv 1]set host_ip [lindex $argv 2]set dest_file [lindex $argv 3]set password [lindex $argv 4]spawn scp -pr $src_file $username@$host_ip:$dest_fileexpect {        "(yes/no)?"        {                send "yes\n"                expect "*assword:" {send "$password\n"}        }        "*assword:"        {                send "$password\n"        }}expect "100%"expect eof

remoteserver_list.conf:远程主机服务器地址列表(如果密码里有特殊字符则需要转义)

192.168.1.11 root ****** /home/was/webtest/tom4192.168.1.11 root ****** /home/was/webtest/tom5192.168.1.12 root ****** /home/was/webtest/tom6192.168.1.12 root ****** /home/was/webtest/tom7

0 0