Information Center

FTP automatic backup script under Linux

  

Before using this script, create the/home/backup directory on the machine to be backed up and install the ftp command

 yum install ftp -y #centos
apt-get install ftp -y #debian ubuntu
mkdir /home/backup

To create a directory for storing backup files on the backup machine, you must create it on ftp in advance. It can cooperate with cron to automatically perform the backup, for example (automatically execute the backup script at one o'clock in the morning every day):

 00 1 * * * bash /root/backup.sh
#!/ bin/bash
#The place you want to modify starts from here
MYSQL_USER=root # mysql user name
MYSQL_PASS=eqblog. com # mysql password # Email to which the database is sent
FTP_USER=yan # ftp User Name
FTP_PASS=eqblog. com # ftp Password
FTP_IP=ftp. eqblog. com # ftp address
FTP_backup=sql # ftp directory where backup files are stored. This must be built on ftp
WEB_DATA=/data/wwwroot # Website data to be backed up
#The place you want to modify ends here

#Define the name of the database and the name of the old database
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
#Delete local data 3 days ago
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
#Export database, one compressed file for each database
for db in `/usr/local/mysql/bin/mysql -u$MYSQL_USER -p$MYSQL_PASS -B -N -e 'SHOW DATABASES' | xargs`; do
(/usr/local/mysql/bin/mysqldump -u$MYSQL_USER -p$MYSQL_PASS ${db} | gzip -9 - > ${db}.sql.gz)
done
#Compress the database file into one file
tar zcf /home/backup/$DataBakName /home/backup/*.sql.gz
rm -rf /home/backup/*.sql.gz

#Compress website data
tar zcf /home/backup/$WebBakName $WEB_DATA
#Upload to the FTP space and delete the data 5 days ago in the FTP space
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