Python--备份数据库

# mysqldump -uroot -p123456 -A > nhy123.sql
import os
import datetime


class BakDb(object):
def __init__(self, ip, username, password, port=3306, path='/tmp/db_bak'):
self.ip = ip
self.username = username
self.password = password
self.port = port
self.path = path
self.path_exist()

def path_exist(self):
if not os.path.isdir(self.path): # 不存在的话就创建!
os.mkdir(self.path)

# mysqldump -u%s(username) -p%s(password) -P%s(port) -h%s(host) -A > nhy123.sql

def bak_db(self):
filename = str(datetime.date.today()) + '.sql'
abs_file = os.path.join(self.path, filename)
command = '''
mysqldump -u{username} -p{password} -P{port} -h{ip} -A > {filename}
'''.format(username=self.username,
password=self.password,
port=self.port,
ip=self.ip,
filename=abs_file)
os.system(command)
print('数据库备份完成!')
db1 = BakDb('192.168.3.1', 'root', '123456')
db1.bak_db()
posted @ 2018-03-07 15:09  王思磊  阅读(273)  评论(0编辑  收藏  举报