Пример #1
0
    def doit(self, tarball):
        """ really restore data """

        # create full path
        fullpath = re.sub('\.tar\.bzip2', '', tarball)  # noqa
        topath = Path(fullpath).absolute()
        # untar Backup
        print("\nExtracting tarball ... in progress ...")

        if os.path.isdir(fullpath) is False:
            #tar -xf $HOME/etc.backup.tar -C /tmp/data
            #-C extract to Dir
            os.system("mkdir -p %s" % fullpath)

            cmd = "tar xfj %s -C %s" % (tarball, topath)
            os.system(cmd)
            print("done ...")
        else:
            print("Tarball is already extracted ... skipping ...")

        files = self.search_files(fullpath, "*.sql")

        if self.debug is False:
            for f in files:
                print("Importing %s ..." % os.path.basename(f))
                filename, file_extension = os.path.splitext(
                    os.path.basename(f))  # noqa
                dbname = filename

                # first drop DB
                self.doMySQL("DROP DATABASE IF EXISTS %s;" % dbname)

                # create DB new
                self.doMySQL("CREATE DATABASE %s;" % dbname)

                sleep(0.5)
                # now import new one
                cmd = "mysql --defaults-extra-file=%s %s < %s" % (
                    self.extrafile, dbname, f)
                os.system(cmd)

        # change to InnoDB
        #self.doMySQL("ALTER TABLE mysql.db ENGINE=InnoDB;")
        #self.doMySQL("ALTER TABLE mysql.columns_priv ENGINE=InnoDB;")

        # restoring User Privileges
        # read yaml File
        path = os.path.join(fullpath, 'users.yaml')
        with open(path, 'rt') as f:
            users = yaml.safe_load(f.read())

        self.Users = []
        for block in users.values():
            u = User()

            for k, v in block.items():
                if k in "username":
                    u.set_username(v)
                if k in "hosts":
                    u.set_hosts(v)
                if k in "pwd":
                    u.set_pwd(v)

                if k in "privs":
                    u.set_privileges(v)
            self.Users.append(u)

        for u in self.Users:
            print("Creating User: %s" % u.get_username())

            # delete user if exists
            self.doMySQL("DROP USER IF EXISTS \"%s\"@\"%s\";" %
                         (u.get_username(), u.get_hosts()))

            self.doMySQL("CREATE USER \"%s\"@\"%s\" IDENTIFIED BY \"%s\";" %
                         (u.get_username(), u.get_hosts(), u.get_pwd()))
            self.doMySQL(
                "ALTER USER \"%s\"@\"%s\" IDENTIFIED WITH mysql_native_password BY \"%s\";"
                % (u.get_username(), u.get_hosts(), u.get_pwd()))

            for p in u.get_privileges():
                # replace ' with "
                p = re.sub('\'', '"', p)  # noqa
                self.doMySQL(p)

            self.doMySQL("FLUSH PRIVILEGES;")
Пример #2
0
    def backupUsers(self):
        """ backup Users and Privileges to a yaml file """
        self.Users = []

        runner = CmdRunner()
        cmd = "mysql --defaults-extra-file=%s -e 'SELECT host,user,authentication_string FROM mysql.user;'" % self.extrafile
        runner.runCmd(cmd)
        errors = runner.getStderr()
        if errors:
            print(errors)
        userdata = runner.getLines()
        # remove first line
        userdata.pop(0)

        for line in userdata:
            if line:
                parts = line.split()
                username = parts[1]
                if username not in [
                        "root", "debian-sys-maint", "mysql.sys",
                        "mysql.session"
                ]:
                    u = User()
                    u.set_hosts(parts[0])
                    u.set_username(parts[1])
                    u.set_pwd(parts[2])

                    self.Users.append(u)

        # now get Privileges
        for u in self.Users:
            # all hosts
            cmd = "mysql --defaults-extra-file=%s -e \"SHOW GRANTS FOR '%s'@'%s';\"" % (
                self.extrafile, u.get_username(), "%")
            runner.runCmd(cmd)
            errors = runner.getStderr()
            userdata = runner.getLines()
            # remove first element, only info
            userdata.pop(0)

            for line in userdata:
                if "error" not in line.lower():
                    if len(line) > 0:
                        u.add_privilege(line)

            # localhost
            cmd = "mysql --defaults-extra-file=%s -e \"SHOW GRANTS FOR '%s'@'localhost';\"" % (
                self.extrafile, u.get_username())
            runner.runCmd(cmd)
            errors = runner.getStderr()
            userdata = runner.getLines()
            # remove first element, only info
            userdata.pop(0)

            for line in userdata:
                if "error" not in line.lower():
                    if len(line) > 0:
                        u.add_privilege(line)

        # create yAMl File
        dict_file = {}
        for u in self.Users:
            data = {}
            data['privs'] = u.get_privileges()
            data['username'] = u.get_username()
            data['hosts'] = u.get_hosts()
            data['pwd'] = u.get_pwd()

            dict_file[u.get_username()] = data

        path = os.path.join(self.backup_path, self.thisbackup_path,
                            'users.yaml')
        with open(path, 'w') as file:
            documents = yaml.dump(dict_file, file)  # noqa