For a system administrator, we need to delete the old backup files or upload files. We can finish this task manually if you only have a few server backup, but as the number of server grows, we will need automate this.
In this example, the backup for server (named monitoring, a virtual machine sitting in Hyper-v) is backuped on weekly basis on Saturday and named as the the date format “YEARMonthDay.zip” under the machines/monitoring folder in FTP server. we only keep the most recent 3 copies,
The script is like this:
HOST='ftp_server_hostname' USER='xxxxx' PASSWD='xxxxx' YEAR="$(date +"%Y")" MONTH="$(date +"%m")" ###Use GNU date, we can get the date of 21 days ago by following command DAY="$(date +"%d" -d "21 days ago")" FILE="$YEAR$MONTH$DAY.zip" names='monitoring logging db' for name in $names do ftp -n $HOST << END_SCRIPT quote user $USER quote PASS $PASSWD mdelete machines/monitoring/$FILE quit END_SCRIPT done exit 0
- We save the hostname, username, password into variables.
- store year, month, and day in variables.
- FTP log on from script:Getting the password to the ftp server without having the ftp client program read the password from /dev/tty requires two tricks:
- Using the -n option on the ftp client program to prevent the ftp client from trying to log in immediately. That way, the ftp client does not ask for a user ID and password. No use of /dev/tty.
- Use the ftp client program command quote to send user ID and password to the ftp server.
- ftp -n $HOST << END_SCRIP means, from next line until the line “END_SCRIPT” are FTP commands.
- mdelete will delete the files.
Then add the script to crontab, and make it work on Saturday after the backup, therefore, we keep 3 backups.
To be improved
This script only delete the file which is 3 weeks old, does not delete the older files, hence we need to delete the older ones manually, but luckily only onece.
Tried to list the file names in the backup folder on FTP server by ls command, but was getting a line of file info ( permission, created date,etc) , needs to figure out how to only grab the files names and then we can loop through those files and delete the older ones.
Bash – Get Time: https://www.cyberciti.biz/faq/unix-linux-bash-get-time/