First, install email send program
Copy Code code as follows:
Yum Install SendMail Mutt
Second, install the FTP client program
This script needs to use an FTP client program to upload files to the FTP space, so you must install the FTP client, otherwise the FTP command will not find an error.
Installation steps please refer to: "CentOS tip ftp:command not Found"
III. Create a new script file in the/root directory: autobackuptoftp.sh, which reads as follows:
Copy Code code as follows:
#!/bin/bash
#你要修改的地方从这里开始
Mysql_user=root #mysql用户名
mysql_pass=123456 #mysql密码
Mail_to=xxxxx@gmail.com #数据库发送到的邮箱
Ftp_user=ftpuser #ftp用户名
Ftp_pass=ftpuserpassword #ftp密码
Ftp_ip=xxx.xxx.xxx.xxx #ftp地址
Ftp_backup=backup #ftp上存放备份文件的目录, this should be built on its own FTP
Web_data=/home/wwwroot #要备份的网站数据, if you are using the LNMP installation package, this is the default for the site Directory
#你要修改的地方从这里结束
#定义数据库的名字和旧数据库的名字
databakname=data_$ (date + "%y%m%d"). tar.gz
webbakname=web_$ (date +%y%m%d). tar.gz
olddata=data_$ (date-d -5day + "%y%m%d"). tar.gz
oldweb=web_$ (date-d -5day + "%y%m%d"). tar.gz
#删除本地3天前的数据
rm-rf/home/backup/data_$ (date-d -3day + "%y%m%d"). tar.gz/home/backup/web_$ (date-d -3day + "%Y%m%d"). tar.gz
Cd/home/backup
#导出数据库, a database with a compressed file
For DB in '/usr/local/mysql/bin/mysql-u$mysql_user-p$mysql_pass-b-n-e ' show DATABASES | Xargs '; Todo
(/usr/local/mysql/bin/mysqldump-u$mysql_user-p$mysql_pass ${db} | gzip-9-> ${db}.sql.gz)
Done
#压缩数据库文件为一个文件
Tar zcf/home/backup/$DataBakName/home/backup/*.sql.gz
Rm-rf/home/backup/*.sql.gz
#发送数据库到Email, if the database is compressed too large, please comment this line
echo "content:this email is auto send by vps ..." | Mutt-a/home/backup/$DataBakName-S "Subject:vps Database backup" $MAIL _to
#压缩网站数据
Tar zcf/home/backup/$WebBakName $WEB _data
#上传到FTP空间, delete data from FTP space 5 days ago
FTP-V-N $FTP _ip << End
User $FTP _user $FTP _pass
Type binary
CD $FTP _backup
Delete $OldData
Delete $OldWeb
Put $DataBakName
Put $WebBakName
Bye
End
Four, configuration
To add execute permissions to a script:
Copy Code code as follows:
chmod 774/root/autobackuptoftp.sh
Use System crontab to achieve automatic daily operation:
Copy Code code as follows:
Enter the following content:
Copy Code code as follows:
* * * */root/autobackuptoftp.sh
Of these, 00 02 is the time division/hour, can be modified, for example: 30 12 * * *, is every day 12.30 run this script.