David 发表于 2017-4-16 10:11:45

自動(crontab+sftp)網站及資料庫遠端備份

【用戶端】
一、建立不用密碼即可登入的ssh連線,先在用戶端建立公鑰、私鑰:

#ssh-keygen -t rsa
https://lh4.googleusercontent.com/-fDPoVkqEbKg/T1XQgkgsr6I/AAAAAAAAFpo/6K9C8iHxZmc/s1600/rsa_.jpg


二、將公鑰檔案資料上傳到伺服器上:
#scp ~/.ssh/id_rsa.pub 要登入伺服器的帳號@伺服器IP:~

若出現以下訊息
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!   @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
####################################################
Please contact your system administrator.
Add correct host key in /home/####/.ssh/known_hosts to get rid of this message.
Offending RSA key in /home/#####/.ssh/known_hosts:1
RSA host key for A.B.C.D(IP) has changed and you have requested strict checking.
Host key verification failed.
lost connection

表示server被重灌了,這樣子新的server就和known_hosts裡的狀態不同。
在Client端以SSH連線到主機時,會要求產生認證資訊,儲存在client端的~/.ssh/known_ssh檔中。
只要以ssh-keygen -R將該host的認證資訊刪除。
#ssh-keygen -R IP位置
/home/####/.ssh/known_hosts updated.
Original contents retained as /home/####/.ssh/known_hosts.old


【伺服器端】
三、設定伺服器上的ssh
1.連上伺服器端,切換至使用者目錄檢查是否有.ssh目錄
#cd 使用者家目錄
#ls -ld .ssh
2.若沒有,建立此資料夾,並設定權限為700
#mkdir .ssh; chmod 700 .ssh
3.檢查是否有收到用戶端傳來的公鑰
#ls -l *pub
4.將公鑰檔案內的資料使用 cat 轉存到 authorized_keys 內
#cat id_rsa.pub >> .ssh/authorized_keys
#chmod 644 .ssh/authorized_keys
#ls -l .ssh

【用戶端】
四、將備份的指令寫成shell script,存檔至/使用者家目錄/backup/【web_autobackup.sh】
#cd /使用者家目錄
#mkdir backup
#cd backup
#vi web_autobackup.sh

五、在web_autobackup.sh中編修內容如下
# !/bin/sh
#
echo off
echo '本機備份'
    nowdate=`date +%Y%m%d`
    cd /使用者家目錄/backup
    tar zcf www_backup_"$nowdate" /var/www
    tar zcf mysql_backup_"$nowdate" /var/lib/mysql

#
echo off
echo '遠端備份'
cd 用戶端目錄
sftp IP <<EOC
cd 伺服器端目錄
put www_backup_$nowdate
put mysql_backup_$nowdate
bye
EOC



六、透過指令【sh -x 要執行的shell script檔案】測試指令檔案沒有寫錯
#sh -x web_autobackup.sh

七、透過工作排程管理工具新增指定的工作排程
1.列出目前的所有排程
#crontab -l
2.新增排程
#crontab -e
3.新增排程紀錄
格式:[分鐘] [小時] [日期] [月份] [星期] [要執行的命令]
範例:30 1 * * * hwclock -w
每天1:30分執行一次電腦硬體時間校正的動作,【*】表示不指定
※若要執行的命令有包含到目錄,必須要用絕對路徑

在此網頁備份希望在每天0:10執行備份指令,則排程設定如下
10 0 * * * /備份script目錄/web_autobackup.sh

八、重新啟動工作排程的服務
#/etc/init.d/cron restart


页: [1]
查看完整版本: 自動(crontab+sftp)網站及資料庫遠端備份