sufehmi

Wordpress Auto-Backup via SSH

Feb 18th, 2018 (edited)
1,167
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2.  
  3. # wordpress-auto-backup.sh
  4.  
  5. ### THIS SCRIPT ASSUMES THE FOLLOWING
  6. # 1/ You can do SSH password-less login to the server
  7. #   How : https://easyengine.io/tutorials/linux/passwordless-authentication-ssh/
  8. # 2/ You have created a correct ~/.my.cnf file
  9. #   How : https://easyengine.io/tutorials/mysql/mycnf-preference/
  10.  
  11. ### RUNTIME PARAMETERS
  12. # wordpress-auto-backup.sh  <server address> <home directory> <backup directory>
  13.  
  14. ### HOW IT WORKS
  15. # 1/ SSH to server
  16. # 2/ read wp-config file & get details
  17. # 3/ create backup_dir/web
  18. # 4/ rsync home_dir backup_dir/web
  19. # 5/ backup database to backup_dir/web/today.mysql
  20. # 6/ compress backup_dir/web to backup_dir/backup_today.bz2
  21.  
  22. ### choose backup retention
  23. # backup retention: weekly
  24. today=`date +%A`
  25. # backup retention: monthly
  26. #today=`date +%d`
  27.  
  28. compressor1='gzip'
  29. compressor2='pbzip2'
  30.  
  31. #============= START BACKUP =======================
  32.  
  33. # to help making this code more readable
  34. server=$1
  35. home_dir=$2
  36. backup_dir=$3
  37.  
  38. # get the variables
  39. ssh $server "cat $home_dir/wp-config.php" > /tmp/$server$today.txt
  40.  
  41. db_name=`cat /tmp/$server$today.txt | grep DB_NAME | cut -d"'" -f 4`
  42. db_user=`cat /tmp/$server$today.txt | grep DB_USER | cut -d"'" -f 4`
  43. db_pass=`cat /tmp/$server$today.txt | grep DB_PASSWORD | cut -d"'" -f 4`
  44. db_host=`cat /tmp/$server$today.txt | grep DB_HOST | cut -d"'" -f 4`
  45. table_prefix=''
  46. table_prefix=`cat /tmp/$server$today.txt | grep table_prefix | cut -d"'" -f 2`
  47. # debug
  48. #echo $db_name $db_user $db_pass $db_host $table_prefix
  49.  
  50.  
  51. # delete temporary file
  52. rm /tmp/$server$today.txt
  53.  
  54. # backup database
  55. ssh  $server "mysqldump -h $db_host  -u $db_user --password=\"$db_pass\"  $db_name \$(mysql -h $db_host -u $db_user --password=\"$db_pass\" -D $db_name  -Bse \"show tables like '$table_prefix%'\") > $home_dir/db-$today.mysql"
  56.  
  57. # compress database dump
  58. ssh  $server "$compressor1 -f $home_dir/db-$today.mysql"
  59.  
  60. # download everything
  61. mkdir $backup_dir/web/
  62. rsync -avuz $server:$home_dir/* $backup_dir/web/
  63.  
  64. # make backup file
  65. tar cvf $backup_dir/$server-$today.tar $backup_dir/web/
  66. # remote clean up
  67. ssh $server "rm $home_dir/db-$today.mysql.gz" &
  68. # compress backup
  69. $compressor2 -f $backup_dir/$server-$today.tar
  70. # local clean up
  71. rm $backup_dir/web/db-$today.mysql.gz
  72.  
  73. # done !
  74.  
  75.  
RAW Paste Data Copied