backup.sh 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. #!/usr/bin/env bash
  2. PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
  3. #==============================================================#
  4. # Description: backup script #
  5. # Author: Teddysun <[email protected]> #
  6. # Visit: https://teddysun.com #
  7. #==============================================================#
  8. [[ $EUID -ne 0 ]] && echo 'Error: This script must be run as root!' && exit 1
  9. ### START OF CONFIG ###
  10. # Encrypt flag(true:encrypt, false:not encrypt)
  11. ENCRYPTFLG=true
  12. # KEEP THE PASSWORD SAFE.
  13. # The password used to encrypt the backup
  14. # To decrypt backups made by this script, run the following command:
  15. # openssl enc -aes256 -in [encrypted backup] -out decrypted_backup.tgz -pass pass:[backup password] -d -md sha1
  16. BACKUPPASS="mypassword"
  17. # Directory to store backups
  18. LOCALDIR="/root/backups/"
  19. # Temporary directory used during backup creation
  20. TEMPDIR="/root/backups/temp/"
  21. # File to log the outcome of backups
  22. LOGFILE="/root/backups/backup.log"
  23. # OPTIONAL: If you want MySQL to be backed up, enter the root password below
  24. MYSQL_ROOT_PASSWORD=""
  25. # Below is a list of MySQL database name that will be backed up
  26. # if you want backup all databases, leave it blank.
  27. MYSQL_DATABASE_NAME[0]=""
  28. # Below is a list of files and directories that will be backed up in the tar backup
  29. # For example:
  30. # File: /data/www/default/test.tgz
  31. # Directory: /data/www/default/test/
  32. # if you want not to be backed up, leave it blank.
  33. BACKUP[0]=""
  34. # Date & Time
  35. BACKUPDATE=$(date +%Y%m%d%H%M%S)
  36. # Backup file name
  37. TARFILE="${LOCALDIR}""$(hostname)"_"${BACKUPDATE}".tgz
  38. # Backup MySQL dump file name
  39. SQLFILE="${TEMPDIR}mysql_${BACKUPDATE}.sql"
  40. # Number of days to store daily local backups
  41. LOCALAGEDAILIES="7"
  42. ### END OF CONFIG ###
  43. log() {
  44. echo "$(date "+%Y-%m-%d %H:%M:%S")" "$1"
  45. echo -e "$(date "+%Y-%m-%d %H:%M:%S")" "$1" >> ${LOGFILE}
  46. }
  47. ### START OF CHECKS ###
  48. # Check if the backup folders exist and are writeable
  49. if [ ! -d "${LOCALDIR}" ]; then
  50. mkdir -p ${LOCALDIR}
  51. fi
  52. if [ ! -d "${TEMPDIR}" ]; then
  53. mkdir -p ${TEMPDIR}
  54. fi
  55. # This section checks for all of the binaries used in the backup
  56. BINARIES=( cat cd du date dirname echo openssl mysql mysqldump pwd rm tar )
  57. # Iterate over the list of binaries, and if one isn't found, abort
  58. for BINARY in "${BINARIES[@]}"; do
  59. if [ ! "$(command -v "$BINARY")" ]; then
  60. log "$BINARY is not installed. Install it and try again"
  61. exit 1
  62. fi
  63. done
  64. ### END OF CHECKS ###
  65. STARTTIME=$(date +%s)
  66. cd ${LOCALDIR} || exit
  67. log "Backup progress start"
  68. ### START OF MYSQL BACKUP ###
  69. if [ -z ${MYSQL_ROOT_PASSWORD} ]; then
  70. log "MySQL root password not set, MySQL back up skip"
  71. else
  72. log "MySQL dump start"
  73. mysql -u root -p"${MYSQL_ROOT_PASSWORD}" 2>/dev/null <<EOF
  74. exit
  75. EOF
  76. if [ $? -ne 0 ]; then
  77. log "MySQL root password is incorrect. Please check it and try again"
  78. exit 1
  79. fi
  80. if [ "${MYSQL_DATABASE_NAME[*]}" == "" ]; then
  81. mysqldump -u root -p"${MYSQL_ROOT_PASSWORD}" --all-databases > "${SQLFILE}" 2>/dev/null
  82. if [ $? -ne 0 ]; then
  83. log "MySQL all databases backup failed"
  84. exit 1
  85. fi
  86. log "MySQL all databases dump file name: ${SQLFILE}"
  87. #Add MySQL backup dump file to BACKUP list
  88. BACKUP=(${BACKUP[*]} ${SQLFILE})
  89. else
  90. for db in ${MYSQL_DATABASE_NAME[*]}
  91. do
  92. unset DBFILE
  93. DBFILE="${TEMPDIR}${db}_${BACKUPDATE}.sql"
  94. mysqldump -u root -p"${MYSQL_ROOT_PASSWORD}" ${db} > "${DBFILE}" 2>/dev/null
  95. if [ $? -ne 0 ]; then
  96. log "MySQL database name [${db}] backup failed, please check database name is correct and try again"
  97. exit 1
  98. fi
  99. log "MySQL database name [${db}] dump file name: ${DBFILE}"
  100. #Add MySQL backup dump file to BACKUP list
  101. BACKUP=(${BACKUP[*]} ${DBFILE})
  102. done
  103. fi
  104. log "MySQL dump completed"
  105. fi
  106. ### END OF MYSQL BACKUP ###
  107. ### START OF TAR BACKUP ###
  108. log "Tar backup file start"
  109. tar -zcPf ${TARFILE} ${BACKUP[*]}
  110. if [ $? -ne 0 ]; then
  111. log "Tar backup file failed"
  112. exit 1
  113. fi
  114. log "Tar backup file completed"
  115. # Encrypt tar file
  116. if ${ENCRYPTFLG}; then
  117. log "Encrypt backup file start"
  118. openssl enc -aes256 -in "${TARFILE}" -out "${TARFILE}.enc" -pass pass:"${BACKUPPASS}" -md sha1
  119. log "Encrypt backup file completed"
  120. # Delete unencrypted tar
  121. log "Delete unencrypted tar file"
  122. rm -f ${TARFILE}
  123. fi
  124. # Delete MySQL temporary dump file
  125. log "Delete MySQL temporary dump file"
  126. rm -f ${TEMPDIR}*.sql
  127. log "Backup progress complete"
  128. if ${ENCRYPTFLG}; then
  129. BACKUPSIZE=$(du -h ${TARFILE}.enc | cut -f1)
  130. log "File name: ${TARFILE}.enc, File size: ${BACKUPSIZE}"
  131. else
  132. BACKUPSIZE=$(du -h ${TARFILE} | cut -f1)
  133. log "File name: ${TARFILE}, File size: ${BACKUPSIZE}"
  134. fi
  135. # Transfer backup file to Google Drive
  136. # If you want to install gdrive command, please visit website:
  137. # https://github.com/prasmussen/gdrive
  138. # of cause, you can use below command to install it
  139. # For x86_64: wget -O /usr/bin/gdrive http://dl.teddysun.com/files/gdrive-linux-x64; chmod +x /usr/bin/gdrive
  140. # For i386: wget -O /usr/bin/gdrive http://dl.teddysun.com/files/gdrive-linux-386; chmod +x /usr/bin/gdrive
  141. if [ ! "$(command -v "gdrive")" ]; then
  142. log "gdrive is not installed"
  143. log "File transfer skipped. please install it and try again"
  144. else
  145. log "Tranferring backup file to Google Drive"
  146. if ${ENCRYPTFLG}; then
  147. gdrive upload --no-progress ${TARFILE}.enc >> ${LOGFILE}
  148. else
  149. gdrive upload --no-progress ${TARFILE} >> ${LOGFILE}
  150. fi
  151. log "Tranfer completed"
  152. fi
  153. ### END OF TAR BACKUP ###
  154. ### START OF DELETE OLD BACKUP FILE###
  155. getFileDate() {
  156. unset FILEYEAR FILEMONTH FILEDAY FILETIME FILEDAYS FILEAGE
  157. FILEYEAR=$(echo "$1" | cut -d_ -f2 | cut -c 1-4)
  158. FILEMONTH=$(echo "$1" | cut -d_ -f2 | cut -c 5-6)
  159. FILEDAY=$(echo "$1" | cut -d_ -f2 | cut -c 7-8)
  160. FILETIME=$(echo "$1" | cut -d_ -f2 | cut -c 9-14)
  161. if [[ "${FILEYEAR}" && "${FILEMONTH}" && "${FILEDAY}" && "${FILETIME}" ]]; then
  162. #Approximate a 30-day month and 365-day year
  163. FILEDAYS=$(( $((10#${FILEYEAR}*365)) + $((10#${FILEMONTH}*30)) + $((10#${FILEDAY})) ))
  164. FILEAGE=$(( 10#${DAYS} - 10#${FILEDAYS} ))
  165. return 0
  166. fi
  167. return 1
  168. }
  169. AGEDAILIES=${LOCALAGEDAILIES}
  170. DAY=$(date +%d)
  171. MONTH=$(date +%m)
  172. YEAR=$(date +%C%y)
  173. #Approximate a 30-day month and 365-day year
  174. DAYS=$(( $((10#${YEAR}*365)) + $((10#${MONTH}*30)) + $((10#${DAY})) ))
  175. cd ${LOCALDIR} || exit
  176. if ${ENCRYPTFLG}; then
  177. LS=($(ls *.enc))
  178. else
  179. LS=($(ls *.tgz))
  180. fi
  181. for f in ${LS[*]}
  182. do
  183. getFileDate ${f}
  184. if [ $? == 0 ]; then
  185. if [[ ${FILEAGE} -gt ${AGEDAILIES} ]]; then
  186. rm -f ${f}
  187. log "Old backup file name:${f} has been deleted"
  188. fi
  189. fi
  190. done
  191. ### END OF DELETE OLD BACKUP FILE###
  192. ENDTIME=$(date +%s)
  193. DURATION=$((ENDTIME - STARTTIME))
  194. log "All done"
  195. log "Backup and transfer completed in ${DURATION} seconds"