Chinaunix首页 | 论坛 | 博客

OPS

  • 博客访问: 508070
  • 博文数量: 117
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1210
  • 用 户 组: 普通用户
  • 注册时间: 2015-05-05 14:50
个人简介

hellow 运维

文章分类

全部博文(117)

文章存档

2019年(1)

2018年(1)

2017年(45)

2016年(38)

2015年(32)

我的朋友

分类: 系统运维

2016-03-05 11:12:01

[root@test3 ~]# cat mysql.py
#!/usr/bin/env python
# Filename: mysqlbackup.py
# version 0.01
# author:Robert Lin
# email:linlianpengit@sina.com
# date:2013-08-09
import    os
import    time
import    sys
import    datetime
from stat import *

# mysql user
User = 'root'

# mysql password
Passwd = 'hanye131'

# mysqldump command
Mysqlcommand = '/usr/bin/mysqldump'

# gzip command
Gzipcommand = '/bin/gzip'

# you want backup mysql database
Mysqldata  = ['mysql', 'qqny123']

# you want    backup to dir
Tobackup = '/dbbak/'
SOCK = '/tmp/mysql1.sock'
for DB in Mysqldata:
# backup file name
    Backfile = Tobackup + DB + '_' + time.strftime('%Y-%m-%d') + '.sql'
# gzip file name
Gzfile = Backfile +'.gz'
if os.path.isfile(Gzfile):
        print Gzfile + " is already backup"
else:
# backup  command
        Back_command = Mysqlcommand + ' -u' + User + ' -p' + Passwd + ' -P3306 ' + DB +  ' -S' + SOCK   + ' > ' + Backfile
if os.system(Back_command) == 0:
        print 'Successful backup to', DB + ' to ' + Backfile
else:
        print 'Backup FAILED'
# gzip command
        Gzip_command = Gzipcommand + ' ' + Backfile
if os.system(Gzip_command) == 0:
        print 'Successful Gzip to',Gzfile
else:
        print 'Gzip FAILED'
# Delete back file
# show file list
filelist=[]
filelist=os.listdir(Tobackup)
# delete Gzfile 5 days ago
for i in range(len(filelist)):
        ft=time.gmtime(os.stat(Tobackup+filelist[i])[ST_MTIME])
        ftl=time.strftime('%Y-%m-%d',ft)
        year,month,day=ftl.split('-')
        ftll=datetime.datetime(int(year),int(month),int(day))
        localt=time.gmtime()
        localtl=time.strftime('%Y-%m-%d',localt)
        year,month,day=localtl.split('-')
        localtll=datetime.datetime(int(year),int(month),int(day))
        days=(localtll-ftll).days
if days >5:
        try:
                os.remove(Tobackup+filelist[i])
                print 'delete is ok'
        except:
                log=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+" remove "+Tobackup+filelist[i]+" fail \n"
                print log

阅读(1351) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~