CentOS6.5 上crontab每天自動備份mysql資料庫

來源:互聯網
上載者:User

標籤:require   efault   sudo   bsp   mon   -name   erro   檔案中   修改   

步驟:

1. sudo vi /etc/crontab  #編輯crontab任務

2.輸入01 12 * * * root /usr/local/mysql/backup/backup.sh >> /usr/local/mysql/backup/error.log 2>&1  #表示每天12點01分以root使用者執行/usr/local/mysql/backup/backup.sh備份指令碼,錯誤記錄檔輸出到/usr/local/mysql/backup/error.log,方便尋找問題

3./etc/crontab 內容如下:

!/bin/sh
source /etc/profile
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# For details see man 4 crontabs


# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
01 12 * * * root /usr/local/mysql/backup/backup.sh >> /usr/local/mysql/backup/error.log 2>&1

 

4.sudo /usr/local/mysql/backup/backup.sh   #編輯指令碼內容

5.在指令碼中輸入以下內容

#!/bin/sh
time="$(date +"%Y%m%d%H%M")"  
sudo /usr/local/mysql/bin/mysqldump 資料庫名 | gzip > /usr/local/mysql/backup/adshare_$time.sql.gz   #備份並壓縮檔
find /usr/local/mysql/backup/ -name "adshare_*.sql.gz" -type f -mtime +7 -exec rm {} \; > /dev/null 2>&1  #刪除7天前的備份檔案

 

#註:這裡不用sudo /usr/local/mysql/bin/mysqldump -u 使用者名稱 -p密碼 資料庫名 | gzip 這種形式,不然會報Warning: Using a password on the command line interface can be insecure. 這裡我們將資料庫使用者名稱和密碼儲存在資料的conf設定檔中,例如我的設定檔是/etc/my.cnf,在my.cnf中加入

[mysqldump]

user=使用者名稱

password=密碼

6.sudo chmod 777 backup      #給backup檔案夾授權

sudo chmod 777 backup.sh    #給backup.sh 檔案授權

7.sudo /etc/rc.d/init.d/crond start 啟動指令碼,如果指令碼已經啟動則用sudo /etc/rc.d/init.d/crond restart 重啟指令碼

遇到的問題:

備份指令碼手動執行沒有任何問題,但是放在crontab定時任務中就出現備份的指令檔為空白,查資料後發現有的人說是因為mysqldump的路徑寫的是相對路徑,改成絕對路徑即可,但是我的路徑寫的是絕對路徑,後面查看error.log日誌發現報sudo: sorry, you must have a tty to run sudo 錯誤。執行 sudo vi /etc/sudoers 將Defaults    requiretty 修改為Defaults:nobody !requiretty,表示僅 nobody 使用者不需要控制終端。按esc輸入::wq!強制儲存,這樣檔案就能正常備份了。

CentOS6.5 上crontab每天自動備份mysql資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.