Automatically backup files from Linux to an SFTP server

Prepare authentication to the SFTP server Link to heading

Generate an SSH key on the client Link to heading

This will allow the client to authenticate to the server without a username and password.

Generate the SSH key.

ssh-keygen -t rsa -b 4096

Copy the SSH key.

cat ~/.ssh/id_rsa.pub

Add the SSH key to the SFTP server Link to heading

Open the authorized keys file and add the SSH key on a new line.

nano ~/.ssh/authorized_keys

Create scripts Link to heading

Create the backup script on the client Link to heading

Create script and backup directories, and create a new bash file.

mkdir ~/scripts
mkdir ~/backups
nano ~/scripts/backup.sh

backup.sh

#!/bin/bash

# Compress one or more files/directories. Replace with correct directory path (home/...).
tar -czvf /home/ubuntu/backups/backup_$(date +'%Y-%m-%d').tar.gz /home/ubuntu/file1.txt /home/ubuntu/file2.txt /home/ubuntu/dir1 /home/ubuntu/dir2

# Copy the compressed file to the SFTP server. Replace with correct username, server and target directory path. Also replace with correct source file path (/home/...).
sftp username@sftp.mydomain.com:target_dir <<EOF
put /home/ubuntu/backups/backup_*.tar.gz
exit
EOF

# Delete compressed file from the client after sending it to the server. Replace with correct file path (/home/...).
sudo rm /home/ubuntu/backups/backup_*.tar.gz

Make the script executable.

chmod +x ~/scripts/backup.sh

Add the script as a cron job.

crontab -e
# Backup files every day at midnight.
# m h dom mon dow command
0 0 * * * /home/ubuntu/scripts/backup.sh

Create a clean-up script on the SFTP server Link to heading

Use this bash script to clean up old backups on the server.

mkdir ~/scripts
nano ~/scripts/cleanup_backups.sh

cleanup_backups.sh

#!/bin/bash

# Remove files that are older than 30 days.
sudo find /home/ubuntu/backups -maxdepth 1 -type f -mtime +30 -name 'backup_*.tar.gz' -exec rm {} \;

Make the script executable.

chmod +x ~/scripts/cleanup_backups.sh

Add the script as a cron job.

crontab -e
# Clean up old backup files at 1.00 every Sunday.
# m h dom mon dow command
0 1 * * 0 /home/ubuntu/scripts/cleanup_backups.sh