1.建立ssh的信任關系
1.1 進入A服務器的root文件夾里面的.ssh目錄
cd /root/.ssh
1.2 生成公鑰和私鑰,命令行如下,並且一直回車即可
ssh-keygen -t rsa
1.3 把公鑰內容添加到臨時文件authorized_keys_server1中
cat id_rsa.pub >authorized_keys_server1
1.4 把臨時文件發送到服務器B下的root下的.ssh文件夾下
scp /root/.ssh/authorized_keys_server1 root@服務器B的ip:/root/.ssh/
1.5 打開服務器B,進入到.ssh目錄下,把臨時文件添加到該目錄下的authorized_keys文件中
cat authorized_keys_server1 >>authorized_keys
之后服務器A通過scp傳輸文件到服務器B,就不需要密碼了。
2.通過TCL, expect結合scp傳輸文件
2.1
借助expect這個軟件,expect是在tcl的基礎上建立的,所以在安裝expect之前需要安裝tcl。為了防止裝的東西過於散亂,在root下新建一個文件夾tools
安裝TCL:
下載地址:http://www.tcl.tk/software/tcltk/download.html
[root@test ~]# cd /tools/
[root@test tools]# wget http://prdownloads.sourceforge.net/tcl/tcl8.5.19-src.tar.gz
[root@test tools]# tar xf tcl8.5.19-src.tar.gz
[root@test tools]# cd tcl8.5.19/unix/
[root@test unix]#./configure
#這一步可能會報錯,需要安裝gcc庫,所以先:yum install -y gcc
#安裝完了再:./configure
[root@test unix]# make
[root@test unix]# makeinstall
[root@test unix]# cd
#安裝expect
#官網:http://expect.sourceforge.net/
[root@test ~]# cd /tools/
[root@test tools]# wget http://nchc.dl.sourceforge.net/project/expect/Expect/5.45/expect5.45.tar.gz
[root@test tools]# tar xf expect5.45.tar.gz
[root@test tools]# cd expect5.45
[root@test expect5.45]#./configure --with-tcl=/usr/local/lib/ --with-tclinclude=/root/
tools/tcl8.5.19/generic/
[root@test expect5.45]# make
[root@test expect5.45]# make install
[root@test expect5.45]# cd
[root@mysql-master ~]# which expect
/usr/local/bin/expect
#到這里,expect則安裝完畢。
安裝完了之后,先測試自動備份命令,目的是先把一對一公鑰保存下來,以免在定時任務出現異常:
我是進入到home下,執行的以下命令:
scp test.txt root@測試服務器的ip:/home/test.txt
出現yes/no,選擇yes,輸入密碼,回車。這樣順利的話就是已經把數據庫備份到別的服務器上面了。
#在/usr/sbin下新建一個scp.exp文件,里面加上代碼: #! /usr/local/bin/expect # FileName:scp.exp set timeout 60 if { [llength $argv] < 2} { puts "Usage:" puts "$argv0 local_file remote_path" exit 1 } set local_file [lindex $argv 0] set remote_path [lindex $argv 1] set passwd "password" #這里的內容主要是備注,在正式文件中要記得刪掉,這 個password是備份服務器的服務器密碼 set passwderror 0 spawn scp $local_file $remote_path expect { "*assword:*" { if { $passwderror == 1 } { puts "passwd is error" exit 2 } set timeout 1000 set passwderror 1 send "$passwd\r" exp_continue } "*es/no)?*" { send "yes\r" exp_continue } timeout { puts "connect is timeout" exit 3 } } #文件的格式要是unix
最后再編寫一個.sh腳本,結合cron即可實現從A服務器傳文件到B服務器