#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys,os
import subprocess
import time
class copyDatabase():
originHost="localhost"
originUser=""
originPass=""
originDatabase="originDatabase"
destHost="localhost"
destUser=""
destPass=""
destDatabase="destDatabase"
def __init__(self,**keys):
"""
This function receive the values with a key=value...
setValues(originHost="localhost", originUser="",...)
"""
for k,v in keys.items():
setattr(self,k,v)
def start(self):
"""
Return True if ok
"""
print("Copy database %s from %s to %s in %s\n\n" % (self.originDatabase, self.originHost, self.destDatabase, self.destHost))
startTime=time.time()
if self.copyDatabase():
result=self.restoreDatabase()
if result:
print("Time: %s seconds" % int(time.time()-startTime))
self.removeFile()
return True
self.removeFile()
print("Error Time: %s seconds" % int(time.time()-startTime))
return False
def copyDatabase(self):
"""
return True if ok
"""
f = open("%s.sql" % self.destDatabase, 'w')
args=[
"/usr/bin/mysqldump",
"--no-defaults",
"-h", self.originHost,
"-u", self.originUser,
"-p%s" % self.originPass,
self.originDatabase
]
p=subprocess.Popen(args, stdout=f)
f.close()
## creando el archivo comprimido
#args=["/usr/bin/mysqldump", "-h", self.originHost, "-u", self.originUser, "-p%s" % self.originPass, self.originDatabase]
#with open("%s.sql" % self.destDatabase, 'wb', 0) as f:
#p1 = subprocess.Popen(args, stdout=subprocess.PIPE)
#p2 = subprocess.Popen('gzip', stdin=p1.stdout, stdout=f)
#p1.stdout.close() # force write error (/SIGPIPE) if p2 dies
#p2.wait()
#p1.wait()
try:
proc=subprocess.check_output(args, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
print("Copy database: False")
return False
print("Copy database: True")
return True
def restoreDatabase(self):
"""
return True if ok
"""
args="/usr/bin/mysql -h %s -u %s -p%s %s" % (self.destHost, self.destUser, self.destPass, self.destDatabase)
p=subprocess.Popen(args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True, stderr=subprocess.PIPE)
try:
with open("%s.sql" % self.destDatabase,"r") as f:
p.stdin.write(f.read())
out,err=p.communicate()
p.stdin.close()
if err:
print("Restore database: False1")
return False
except:
print("Restore database: False2")
return False
print("Restore database: True")
return True
def removeFile(self):
"""
return True if ok
"""
try:
fileToRemove="%s.sql" % self.destDatabase
if os.path.exists(fileToRemove):
os.remove(fileToRemove)
print("Remove file: True")
return True
except:
print("Remove file: False")
return False
if __name__=="__main__":
obj=copyDatabase(
originHost="192.168.1.100",
originUser="root",
originPass="root",
originDatabase="test",
destHost="localhost",
destUser="root",
destPass="root",
destDatabase="test"
)
obj.start()
del obj
Comentarios sobre la versión: 1 (1)