MySQL 脚本备份相关

Shell 脚本定期备份

mysql_config_editor — MySQL Configuration Utility 需要配置下mysql_config_editor

  1. mysql_config_editor set --login-path=client
  2. --host=localhost --user=localuser --password

backup_parent_dir 是备份路径mysql_user="root" 备份用户,其实这里可以不用

  1. #!/bin/bash
  2. # Simple script to backup MySQL databases
  3. # Parent backup directory
  4. backup_parent_dir="./backup"
  5. # MySQL settings
  6. mysql_user="root"
  7. # Read MySQL password from stdin if empty
  8. # Check MySQL password
  9. #echo exit | mysql --login-path=client --host=localhost --user=${mysql_user} --password=${mysql_password} -B 2>/dev/null
  10. echo exit | mysql --login-path=client -B 2>/dev/null
  11. if [ "$?" -gt 0 ]; then
  12. echo "MySQL ${mysql_user} password incorrect"
  13. exit 1
  14. else
  15. echo "MySQL ${mysql_user} password correct."
  16. fi
  17. # Create backup directory and set permissions
  18. backup_date=`date +%Y_%m_%d_%H_%M`
  19. backup_dir="${backup_parent_dir}/${backup_date}"
  20. echo "Backup directory: ${backup_dir}"
  21. mkdir -p "${backup_dir}"
  22. chmod 700 "${backup_dir}"
  23. logfile="$backup_parent_dir/"backup_log_"$(date +'%Y_%m')".txt
  24. # Get MySQL databases
  25. mysql_databases=`echo 'show databases' | mysql --login-path=client | sed /^Database$/d`
  26. # Backup and compress each database
  27. for database in $mysql_databases
  28. do
  29. if [ "${database}" == "information_schema" ] || [ "${database}" == "performance_schema" ]; then
  30. additional_mysqldump_params="--skip-lock-tables"
  31. else
  32. additional_mysqldump_params=""
  33. fi
  34. echo "Creating backup of \"${database}\" database"
  35. mysqldump --login-path=client ${additional_mysqldump_params} -e | gzip > "${backup_dir}/${database}.gz"
  36. echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
  37. chmod 600 "${backup_dir}/${database}.gz"
  38. done
  39. echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"

再用crontab 来定制备份计划

python 备份脚本

  1. import os
  2. import time
  3. filestamp = time.strftime("%Y-%m-%d")
  4. database_list_command="mysql --login-path=client -e 'show databases'"
  5. for database in os.popen(database_list_command).readlines():
  6. database = database.strip()
  7. if database == 'information_schema':
  8. continue
  9. if database == 'performance_schema':
  10. continue
  11. filename = '/Users/xiaodian/mysql/backup/{0}_{1}.sql'.format(database, filestamp)
  12. os.popen("mysqldump --login-path=client -c {0}| gzip > {1}.gz".format(database, filename))
  13. os.popen("echo mysqldump finished at {0} >> backup_log_{1}.txt".format(filename, filestamp))

脚本参考https://blog.sleeplessbeastie.eu/2012/11/22/simple-shell-script-to-backup-mysql-databases/

原文: https://cxiaodian.gitbooks.io/mysql/content/script_back.html