MySQL备份与恢复


1,MySQL备份
通过一个perl脚本实现DB备份: 原理很简单,利用mysqldump来导出DB,然后通过gzip进行压缩,文件目录按DB分;为避免文件过多,30天前的备份删除。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/perl
 
#对用户所指定的mysql 数据库进行全备份(注意这过程会锁数据库一会)
use warnings;
use strict;
use DBI;
#数据库用户,要有bak权限
my $db_user = "bak" ;
#密码
my $db_passwd = "password" ;
#日期
my $date = `date -d yesterday + %Y %m %d `;
#主机
my $db_host = "localhost" ;
#数据库服务器的地址
my $db_dir = "/data/soft/mysql/" ;
# mysql安装路径
my $backup_dir = "/data/app/db_bak" ;
#备份路径
my $backup_log = "$backup_dir/backup.log" ;
#数据库备份保留的天数
my $db_date = 30;
# 指定要备份的数据库
my @db_lists = ( "bbs" , "help" , "mall" , "mysql" );
 
open (LOGFILE, ">> $backup_log" );
print LOGFILE ( "--------------------------\n" );
print LOGFILE (`date + '%Y-%m-%d %H:%M:%S' `);
print LOGFILE ( "--------------------------\n" );
chomp ( $date ); # clear "\n"
 
foreach my $db ( @db_lists )
{
     if (! -e "$backup_dir/$db" )
     {
         mkdir ( "$backup_dir/$db" );
     }
     #使用mysqldump 进行数据库备份
     system "$db_dir/bin/mysqldump --database $db -u $db_user -h $db_host -p $db_passwd > $backup_dir/$db/${db}_${date}.sql" ;
     if ( -e "$backup_dir/$db/${db}_${date}.sql" )
     {
         #使用gzip压缩
         system "gzip $backup_dir/$db/${db}_${date}.sql" ;
     }
     else
     {
         print LOGFILE  "$date $db is fail!,\n" ;
     }
     if (!$?)
     {
         print LOGFILE "$date $db is success!\n" ;
         my @db_file = < $backup_dir / $db /*.*>;
         foreach my $db_file ( @db_file )
         {
             my @f_info = stat ( $db_file ); #数组,下标9 是创建时间
             if ( time () - $f_info [9] > (60*60*24* $db_date ))
             {
                 unlink $db_file ; #删除文件
                 print LOGFILE ( "Delete OldFile $db_file successfully!\n" ); #将删除操作写入日志
             }
         }
     }
     else
     {
         print LOGFILE  "$date $db is gzip fail!,\n" ;
     }
}
close LOGFILE;

最后把脚本配置到 /etc/crontab

1
01 4 * * * root /data/shell/dbbackup .pl &> /tmp/dbbackup . cron .log

你可能感兴趣的:(mysql)