Código de Python - Clase para copiar una base de datos de un servidor MySQL a otro servidor

Requerimientos

Python 2 o 3

1
estrellaestrellaestrellaestrellaestrella(1)

Publicado el 16 de Diciembre del 2018gráfica de visualizaciones de la versión: 1
4.164 visualizaciones desde el 16 de Diciembre del 2018
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#!/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)

Imágen de perfil
27 de Diciembre del 2018
estrellaestrellaestrellaestrellaestrella
No ha dejado ningún comentario
Responder

Comentar la versión: 1

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s4971