使用expect去除交付过程,达到能够实现服务器同步备份
第一:安装expect
检查是否已安装expect
rpm -qa | grep tcl
tclx-8.4.0-5.fc6
tcl-8.4.13-4.el5
第二:安装expect
下载地址:
http://dl.oschina.net/soft/expect
检查tcl的安装位置
rpm -qa|grep tcl
需要安装tcl-devel
rpm -ivh tcl-devel-8.4.13-4.el5.x86_64.rpm
解压expect源码包
tar xzvf expect-5.45-1374045102000.tar.gz
cd expect5.45/
编译:需要查找/usr/lib64/tclConfig.sh所在的路径
./configure —with-tcl=/usr/lib64/
make
make install
运行expect
[root@localhost expect5.45]# expect
expect: error while loading shared libraries: libexpect5.45.so: cannot open shared object file: No such file or directory
find / -name libexpect5.45.so
ln -sf /usr/lib/expect5.45/libexpect5.45.so /usr/lib64/libexpect5.45.so
再运行expect
expect1.1> [root@localhost /]#
就好了

加密,解密工具
下会进行expect 脚本的书写:
[ruby] view plain copy 在CODE上查看代码片派生到我的代码片
#!/usr/bin/expect -f
##########################################################

1.service ip

2.User

3.userPassword

4.localPath [本地路径]

5.serverPath [server端路径]

返回值:

0 成功

1 参数个数不正确

#

proc usage {} {
regsub “.*/“ $::argv0 “” name
send_user “Usage:\n”
send_user “$name serviceip User userPassword localPath serverPath\n”
exit 1
}

判断参数个数

if {[llength $argv] != 5} {
usage
}

设置变量值
set severip [lindex $argv 0]
set User [lindex $argv 1]
set userPassword [lindex $argv 2]
set localPath [lindex $argv 3]
set serverPath [lindex $argv 4]

定义变量标记rsync连接时是否输入yes确认
set inputYes 0

rsync -avz /etc/ 192.168.15.234:/home/7_8
spawn rsync -avz ${localPath} ${User}@${severip}😒{serverPath}
expect {
-nocase -re “yes/no” {
send — “yes\r”
set inputYes 1
}
-nocase -re “assword: “ {
send — “${userPassword}\r”
interact
}
-nocase -re “Connection refused” {
send_error “Sftp services at ${ftpServerIp} is not active.\n”
exit 2
}
timeout {
send_error “Connect to sftp server ${ftpUser}@${ftpServerIp} timeout(10s).\n”
exit 8
}
}

如果输入了yes确认,输入密码
if {$inputYes==1} {
expect {
-nocase -re “assword: “ {
send — “${userPassword}\r”
interact
}
}
}

Rsync(remote synchronize) 是一个远程数据同步工具,可以使用”Rsync算法”同步本地和远程主机之间的文件。
rsync的好处是只同步两个文件不同的部分,相同的部分不在传递。类似于增量备份,
这使的在服务器传递备份文件或者同步文件,比起scp工具要省好多时间。
具体的用法:
1.在本地机器上对两个目录同步
$ rsync -zvr filename1 filename2
上述代码是将filename1中的文件与filename2中的文件同步,如果将filename2中的文件同步到filename1中,修改代码为:
$ rsync -zvr filename2 filename1
参数说明:
-z 开启压缩
-v 详情输出
-r 表示递归
2.使用rsync -a 同步保留时间按标记
$ rsync -azv filename1 filename2
使用上述命令,将filename2中新同步的文件的时间与filename1中的创建的时间相同,
它保留符号链接、权限、时间标记、用户名及组名相同。
3.从本地同步文件到远程服务器
$rsync -avz filename1 root@192.168.0.1:/home/redhat/filename2
上述命令是将本地的filename1同步到远程192.168.0.1的主机上。
注意:如果远程主机的端口不是默认的22端口,假如是3000端口,上述的命令修改为,
$ rsync -avz ‘-e ssh -p 4000’ filename1 root@192.168.0.1:/home/redhat/filename2
4.将远程服务器的文件同步到本地
与步骤3类似,只是将filename1与远程服务器的位置对换一下,
$rsync -avz root@192.168.0.1:/home/redhat/filename2 filename1
同理如果端口不是22,使用以下命令
$ rsync -avz ‘-e ssh -p 4000’ root@192.168.0.1:/home/redhat/filename2 filename1