Skip to content

Instantly share code, notes, and snippets.

@robertsky

robertsky/remotebackup.sh Secret

Last active Apr 22, 2018
Embed
What would you like to do?
Remote Backup for WordPress
#!/bin/bash
# remotebackup.sh
# usage: remotebackup.sh client_domain
# this assumes that we have already placed ssh keys on the remote server
# default variable values
isRoot=false
backup_recency_days=30
case $1 in
robertsky.com)
user=root
isRoot=true
site_dir=/home/admin/web/robertsky.com/public_html
backup_dir=/home/admin/web/robertsky.com/backup
exclude=wp-content/cache,wp-content/updraft
host=$1
;;
esac
exclude_expanded=' '
if [ ! -z "$exclude" ]
then
# https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash
IFS=',' read -ra excludee <<< "$exclude"
for i in "${excludee[@]}"; do
exclude_expanded="${exclude_expanded}--exclude=${i} "
done
fi
exclude_expanded=`echo $exclude_expanded`
wp_root_user_check=' '
if [ "$isRoot" = true ]
then
wp_root_user_check='--allow-root'
fi
wp_root_user_check=`echo $wp_root_user_check`
# https://zaiste.net/posts/a_few_ways_to_execute_commands_remotely_using_ssh/
# Multi-line command using Heredoc
ssh -T $user@$host << EOSSH
cd $site_dir
# https://www.guyrutenberg.com/2010/02/28/improved-ftp-backup-for-wordpress/
# always check that there is wp-cli installed.
# to-do: download wp-cli.phar if don't have and then erase it.
db_name=\$(wp config get DB_NAME $wp_root_user_check)
db_user=\$(wp config get DB_USER $wp_root_user_check)
db_pass=\$(wp config get DB_PASSWORD $wp_root_user_check)
db_host=\$(wp config get DB_HOST $wp_root_user_check)
site_dir=`dirname "$site_dir"`/`basename "$site_dir"`
backup_dir=`dirname "$backup_dir"`/`basename "$backup_dir"`
dump_name=\${db_name}-\$(date +%Y%m%d).sql.bz2
mysqldump --user=\${db_user} --password=\${db_pass} --host=\${db_host} \
--databases \${db_name} \
| bzip2 -c > \${backup_dir}/\${dump_name}
if [ "$?" -ne "0" ]; then
echo "mysqldump failed!"
exit 1
fi
tar_name=\${site_dir##*/}-\$(date +%Y%m%d).tar.bz2
tar -cjf \${backup_dir}/\${site_dir##*/}-\$(date +%Y%m%d).tar.bz2 $exclude_expanded \${site_dir}
if [ "$?" -ne "0" ]; then
echo "tar failed!"
exit 2
fi
EOSSH
# second command: rsync to fastbackup folder
rsync -avP $user@$host:$backup_dir/* /mnt/SkyFastBackups/clients/$host/
# third command: delete content in remote backup folder
ssh -T $user@$host "rm $backup_dir/*"
# forth set of commands:
# transfer the content from fastbackup folder to the RAID.
# delete excess backup materials
mv /mnt/SkyFastBackups/clients/$host/* /mnt/ProBox/SkyBackups/clients/$host/
find /mnt/ProBox/SkyBackups/clients/$host -type f -mtime +$backup_recency_days -exec rm {} \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.