实现服务器之间文件同步功能

使用scp同步服务器之间的文件,之前有介绍一个方法实现怎么在SHELL 中使用SCP不输入密码

这边在介绍个方法,借助expect

expect是建立在tcl基础上的一个工具,它用来让一些需要交互的任务自动化地完成。

安装

yum install -y expect

使用

vi expect_scp.exp

#!/usr/bin/expect -f
set timeout -1  # -1表示时间不限,  10  表示10秒,以秒为单位
set host [lindex $argv 0] # 接收参数
set port [lindex $argv 1]
set username [lindex $argv 2]
set password [lindex $argv 3]
set src_file [lindex $argv 4]
set dest_file [lindex $argv 5]
spawn scp -P $port $username@$host:$src_file $dest_file # scp命令
expect "*password:"
send "$password\n" # 输入密码
expect eof # 结束

vi bak.sh

host=111.111.111.111 # ip
port=10000 # 端口
username=test123  # 用户名
password=test123 # 密码
src_file=/data/backup/data.sql  # 远程服务器文件目录
dest_dir=/data/backup/  # 本地文件存储位置
./ex_scp.exp $host $port $username $password $src_file $dest_dir

执行

sh bak.sh