CentOS 服务器备份工具
本文制作三个命令
- bak – 依次调用 tst 和 tdb
- tdb – 打包数据库
- tst – 打包程序代码
- fz – 显示包大小
- bc – yum install bc
备份入口脚本(bak)
#!/bin/bash echo -e "现在开始备份\e[0;32m所有的网站\e[0m和\e[0;31m业务数据库\e[0m吗?" echo -n "指定的数据库见文件:~/bin/tdb [y/N]:" read ANS case $ANS in y|Y|yes|Yes|YES) echo "正在备份网站..." tst echo "正在备份数据库..." tdb ;; *) echo -e "\e[0;33m已取消操作\e[0m" ;; esac exit 0
导出所有数据库到指定目录(tdb)
#!/bin/bash DB_USER=root DB_PASSWORD=123456 DATE=$(date +%Y%m%d) EX_DBS=( information_schema performance_schema ) mysql -u$DB_USER -p$DB_PASSWORD -NBe "show databases;" | while read -a row; do DB=${row[0]} IS_EX_DB="NO" for i in ${EX_DBS[@]}; do if [ "$DB" = "$i" ]; then IS_EX_DB="YES" break fi done if [ "$IS_EX_DB" = "YES" ]; then continue fi echo -n $(date +%T) "/data/backup/"$DB"_"$DATE".sql.gz"... $(which mysqldump) -u$DB_USER --password=$DB_PASSWORD $DB | gzip > "/data/backup/"$DB"_"$DATE".sql.gz" echo " "`fz "/data/backup/"$DB"_"$DATE".sql.gz"` done
将指定目录中的项目,分别打包压缩后放到另一个目录(tst)
#!/bin/bash DATE=$(date +%Y%m%d) FOLDER="/data/www" for dt in `ls -l $FOLDER|grep ^d |awk '{printf $9" "}'`; do echo -n $(date +%T) /data/backup/$dt"_"$DATE.tgz... tar -czf /data/backup/$dt"_"$DATE.tgz -C $FOLDER $dt echo " "`fz /data/backup/$dt"_"$DATE.tgz` done
显示文件大小(fz)
#!/bin/bash # 显示帮助 if [ -z "$1" ]; then echo " Usage: `basename $0` path/file" exit fi if [ ! -e $0 ]; then echo "File not found: "$0 exit 1 else size=`stat -c "%s" $1` kb=1024 # Kilobyte mb=$[1024*$kb] # Megabyte gb=$[1024*$mb] # Gigabyte tb=$[1024*$gb] # Terabyte value=0 if [ $size -lt $kb ]; then value="\e[0;32m"$size"\e[0;31m""B""\e[0m" elif [ $size -lt $mb ]; then value="\e[0;32m"`echo "scale=2;$size/$kb"|bc`"\e[0m""KB" elif [ $size -lt $gb ]; then value="\e[0;32m"`echo "scale=2;$size/$mb"|bc`"\e[0m""MB" elif [ $size -lt $tb ]; then value="\e[0;32m"`echo "scale=2;$size/$gb"|bc`"\e[0m""GB" else value="\e[0;32m"`echo "scale=2;$size/$tb"|bc`"\e[0m""TB" fi echo -e $value exit 0 fi
其它命令
chmod u+x ~/bin/ttd chmod u+x ~/bin/tdb chmod u+x ~/bin/fz cd /www/ ./ttd ./tdb mv *.tgz /backup/
打包当前目录中的所有文件夹到当前目录
#!/bin/bash for f in ./*;do if [ -d $f ]; then tar -zcvf $f-`date '+%Y%m%d'`.tgz $f; fi ; done
<完>