Ejemplo n.º 1
0
    def submitDBCreation(dbName, dbUsername, dbPassword, databaseWebsite):
        try:

            if len(dbName) > 16 or len(dbUsername) > 16:
                raise BaseException("Length of Database name or Database user should be 16 at max.")

            website = Websites.objects.get(domain=databaseWebsite)

            if website.package.dataBases == 0:
                pass
            elif website.package.dataBases > website.databases_set.all().count():
                pass
            else:
                raise BaseException("Maximum database limit reached for this website.")

            if Databases.objects.filter(dbName=dbName).exists() or Databases.objects.filter(dbUser=dbUsername).exists():
                raise BaseException("This database or user is already taken.")

            result = mysqlUtilities.createDatabase(dbName, dbUsername, dbPassword)

            if result == 1:
                pass
            else:
                raise BaseException(result)

            db = Databases(website=website, dbName=dbName, dbUser=dbUsername)
            db.save()

            return 1,'None'

        except BaseException, msg:
            logging.CyberCPLogFileWriter.writeToFile(str(msg))
            return 0,str(msg)
Ejemplo n.º 2
0
    def dbCreation(self, tempStatusPath, website):
        try:
            dbName = randomPassword.generate_pass()
            dbUser = dbName
            dbPassword = randomPassword.generate_pass()

            ## DB Creation

            if Databases.objects.filter(
                    dbName=dbName).exists() or Databases.objects.filter(
                        dbUser=dbUser).exists():
                statusFile = open(tempStatusPath, 'w')
                statusFile.writelines(
                    "This database or user is already taken." + " [404]")
                statusFile.close()
                return 0

            result = mysqlUtilities.createDatabase(dbName, dbUser, dbPassword)

            if result == 1:
                pass
            else:
                statusFile = open(tempStatusPath, 'w')
                statusFile.writelines("Not able to create database." +
                                      " [404]")
                statusFile.close()
                return 0

            db = Databases(website=website, dbName=dbName, dbUser=dbUser)
            db.save()

            return dbName, dbUser, dbPassword

        except BaseException, msg:
            logging.writeToFile(str(msg) + '[ApplicationInstallerdbCreation]')
Ejemplo n.º 3
0
    def createWebsiteFromBackup(backupFileOrig, dir):
        try:
            backupFile = backupFileOrig.strip(".tar.gz")
            originalFile = "/home/backup/" + backupFileOrig

            if os.path.exists(backupFileOrig):
                path = backupFile
            elif not os.path.exists(originalFile):
                dir = dir
                path = "/home/backup/transfer-" + str(dir) + "/" + backupFile
            else:
                path = "/home/backup/" + backupFile

            admin = Administrator.objects.get(pk=1)

            ## open meta file to read data

            ## Parsing XML Meta file!

            backupMetaData = ElementTree.parse(os.path.join(path, 'meta.xml'))

            domain = backupMetaData.find('masterDomain').text
            phpSelection = backupMetaData.find('phpSelection').text
            externalApp = backupMetaData.find('externalApp').text

            ## Pre-creation checks

            if Websites.objects.filter(domain=domain).count() > 0:
                raise BaseException('This website already exists.')


            if ChildDomains.objects.filter(domain=domain).count() > 0:
                raise BaseException("This website already exists as child domain.")


            ####### Pre-creation checks ends

            numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count()

            ## Create Configurations

            result = virtualHostUtilities.createVirtualHost(domain, admin.email, phpSelection, externalApp,
                                                            numberOfWebsites, 0, 'CyberPanel', 1, 0,
                                                            admin.userName, 'Default')

            if result[0] == 0:
                raise BaseException(result[1])

            ## Create Configurations ends here

            ## Create databases

            databases = backupMetaData.findall('Databases/database')
            website = Websites.objects.get(domain=domain)

            for database in databases:
                dbName = database.find('dbName').text
                dbUser = database.find('dbUser').text

                if mysqlUtilities.mysqlUtilities.createDatabase(dbName, dbUser, "cyberpanel") == 0:
                    raise BaseException("Failed to create Databases!")

                newDB = Databases(website=website, dbName=dbName, dbUser=dbUser)
                newDB.save()

            ## Create dns zone

            dnsrecords = backupMetaData.findall('dnsrecords/dnsrecord')

            DNS.createDNSZone(domain, admin)

            zone = DNS.getZoneObject(domain)

            for dnsrecord in dnsrecords:

                recordType = dnsrecord.find('type').text
                value = dnsrecord.find('name').text
                content = dnsrecord.find('content').text
                prio = int(dnsrecord.find('priority').text)

                DNS.createDNSRecord(zone, value, recordType, content, prio, 3600)


            return 1,'None'

        except BaseException, msg:
            return 0, str(msg)
Ejemplo n.º 4
0
    def RestoreDatabases(self):
        try:

            message = 'Restoring databases from %s.' % (self.backupFile)
            logging.statusWriter(self.logFile, message, 1)

            ##
            passFile = "/etc/cyberpanel/mysqlPassword"

            f = open(passFile)
            data = f.read()
            password = data.split('\n', 1)[0]
            ##

            connection, cursor = self.setupConnection()

            CompletPathToExtractedArchive = cPanelImporter.mainBackupPath + self.fileName

            DatabasesPath = '%s/mysql' % (CompletPathToExtractedArchive)

            for items in os.listdir(DatabasesPath):
                if items.find('roundcube') > -1:
                    continue
                if items.endswith('.sql'):
                    message = 'Restoring MySQL dump for %s.' % (items.replace(
                        '.sql', ''))
                    logging.statusWriter(self.logFile, message, 1)

                    try:
                        cursor.execute("CREATE DATABASE `%s`" %
                                       (items.replace('.sql', '')))
                    except BaseException, msg:
                        message = 'Failed while restoring database %s from backup file %s, error message: %s' % (
                            items.replace('.sql',
                                          ''), self.backupFile, str(msg))
                        logging.statusWriter(self.logFile, message, 1)

                    command = 'sudo mysql -u root -p' + password + ' ' + items.replace(
                        '.sql', '')

                    cmd = shlex.split(command)

                    DBPath = "%s/%s" % (DatabasesPath, items)

                    with open(DBPath, 'r') as f:
                        res = subprocess.call(cmd, stdin=f)

                    website = Websites.objects.get(domain=self.mainDomain)

                    ## Trying to figure out dbname

                    CommandsPath = '%s/mysql.sql' % (
                        CompletPathToExtractedArchive)

                    data = open(CommandsPath, 'r').readlines()

                    for inItems in data:
                        if inItems.find(
                                'GRANT ALL PRIVILEGES') > -1 and inItems.find(
                                    'localhost') > -1 and inItems.find(
                                        '_test') == -1:
                            cDBName = inItems.split('`')[1].replace('\\', '')
                            logging.statusWriter(self.logFile, inItems, 1)
                            if cDBName == items.replace('.sql', ''):
                                cDBUser = inItems.split("'")[1]
                                message = 'Database user for %s is %s.' % (
                                    cDBName, cDBUser)
                                logging.statusWriter(self.logFile, message, 1)
                                if Databases.objects.filter(
                                        dbUser=cDBUser).count() > 0:
                                    continue
                                break

                    db = Databases(website=website,
                                   dbName=items.replace('.sql', ''),
                                   dbUser=cDBUser)
                    db.save()

                    message = 'MySQL dump successfully restored for %s.' % (
                        items.replace('.sql', ''))
                    logging.statusWriter(self.logFile, message, 1)

            message = 'Creating Database users from backup file %s.' % (
                self.backupFile)
            logging.statusWriter(self.logFile, message, 1)

            CommandsPath = '%s/mysql.sql' % (CompletPathToExtractedArchive)

            data = open(CommandsPath, 'r').readlines()

            for items in data:
                if items.find("--") > -1 or items.find("'cyberpanel'@") > -1:
                    continue
                try:
                    cursor.execute(items)
                except BaseException, msg:
                    message = 'Failed while restoring database %s from backup file %s, error message: %s' % (
                        items.replace('.sql', ''), self.backupFile, str(msg))
                    logging.statusWriter(self.logFile, message, 1)
Ejemplo n.º 5
0
class restoreMeta():
    @staticmethod
    def startRestore(metaPath, statusPath):
        try:

            ## extracting master domain for later use
            backupMetaData = ElementTree.parse(metaPath)
            masterDomain = backupMetaData.find('masterDomain').text

            ########### Creating child/sub/addon/parked domains

            logging.statusWriter(statusPath, "Creating Child Domains!", 1)

            ### Restoring Child Domains if any.

            childDomains = backupMetaData.findall('ChildDomains/domain')

            try:
                for childDomain in childDomains:

                    domain = childDomain.find('domain').text
                    phpSelection = childDomain.find('phpSelection').text
                    path = childDomain.find('path').text

                    virtualHostUtilities.createDomain(masterDomain, domain,
                                                      phpSelection, path, 0, 0,
                                                      0, 'admin', 0)
            except BaseException, msg:
                logging.writeToFile(str(msg) + " [startRestore]")
                return 0

            ## Restore Aliases

            logging.statusWriter(statusPath, "Restoring Domain Aliases!", 1)

            aliases = backupMetaData.findall('Aliases/alias')

            for items in aliases:
                virtualHostUtilities.createAlias(masterDomain, items.text, 0,
                                                 "", "", "admin")

            ## Restoring email accounts

            logging.statusWriter(statusPath, "Restoring email accounts!", 1)

            emailAccounts = backupMetaData.findall('emails/emailAccount')

            try:
                for emailAccount in emailAccounts:

                    email = emailAccount.find('email').text
                    username = email.split("@")[0]
                    password = emailAccount.find('password').text

                    result = mailUtilities.createEmailAccount(
                        masterDomain, username, password)
                    if result[0] == 0:
                        logging.statusWriter(
                            statusPath,
                            'Email existed, updating password according to last snapshot. %s'
                            % (email))
                        if mailUtilities.changeEmailPassword(
                                email, password, 1)[0] == 0:
                            logging.statusWriter(
                                statusPath,
                                'Failed changing password for: %s' % (email))
                        else:
                            logging.statusWriter(
                                statusPath,
                                'Password changed for: %s' % (email))

                    else:
                        logging.statusWriter(statusPath,
                                             'Email created: %s' % (email))

            except BaseException, msg:
                logging.writeToFile(str(msg) + " [startRestore]")
                return 0

            ## Emails restored

            ## restoring databases

            logging.statusWriter(statusPath, "Restoring Databases!", 1)

            ## Create databases

            databases = backupMetaData.findall('Databases/database')
            website = Websites.objects.get(domain=masterDomain)

            for database in databases:
                dbName = database.find('dbName').text
                dbUser = database.find('dbUser').text
                dbPassword = database.find('password').text

                try:
                    dbExist = Databases.objects.get(dbName=dbName)
                    logging.statusWriter(
                        statusPath,
                        'Database exists, changing Database password.. %s' %
                        (dbName))
                    mysqlUtilities.mysqlUtilities.changePassword(
                        dbUser, dbPassword, 1)
                    if mysqlUtilities.mysqlUtilities.changePassword(
                            dbUser, dbPassword, 1) == 0:
                        logging.statusWriter(
                            statusPath,
                            'Failed changing password for database: %s' %
                            (dbName))
                    else:
                        logging.statusWriter(
                            statusPath,
                            'Password successfully changed for database: %s.' %
                            (dbName))
                except:
                    logging.statusWriter(
                        statusPath,
                        'Database did not exist, creating new.. %s' % (dbName))
                    if mysqlUtilities.mysqlUtilities.createDatabase(
                            dbName, dbUser, "cyberpanel") == 0:
                        logging.statusWriter(
                            statusPath,
                            'Failed the creation of database: %s' % (dbName))
                    else:
                        logging.statusWriter(
                            statusPath,
                            'Database: %s successfully created.' % (dbName))

                    mysqlUtilities.mysqlUtilities.changePassword(
                        dbUser, dbPassword, 1)
                    if mysqlUtilities.mysqlUtilities.changePassword(
                            dbUser, dbPassword, 1) == 0:
                        logging.statusWriter(
                            statusPath,
                            'Failed changing password for database: %s' %
                            (dbName))
                    else:
                        logging.statusWriter(
                            statusPath,
                            'Password successfully changed for database: %s.' %
                            (dbName))

                    try:
                        newDB = Databases(website=website,
                                          dbName=dbName,
                                          dbUser=dbUser)
                        newDB.save()
                    except:
                        pass

            ## Databases restored

            try:
                os.remove(metaPath)
            except:
                pass
Ejemplo n.º 6
0
    def installWordPress(self):
        try:

            admin = self.extraArgs['admin']
            domainName = self.extraArgs['domainName']
            home = self.extraArgs['home']
            tempStatusPath = self.extraArgs['tempStatusPath']
            blogTitle = self.extraArgs['blogTitle']
            adminUser = self.extraArgs['adminUser']
            adminPassword = self.extraArgs['adminPassword']
            adminEmail = self.extraArgs['adminEmail']

            ### Check WP CLI

            try:
                command = 'sudo wp --info'
                res = subprocess.call(shlex.split(command))

                if res == 1:
                    self.installWPCLI()
            except subprocess.CalledProcessError:
                self.installWPCLI()

            ## Open Status File

            statusFile = open(tempStatusPath, 'w')
            statusFile.writelines('Setting up paths,0')
            statusFile.close()

            try:
                website = ChildDomains.objects.get(domain=domainName)
                externalApp = website.master.externalApp

                if admin.type != 1:
                    if website.master.admin != admin:
                        statusFile = open(tempStatusPath, 'w')
                        statusFile.writelines("You do not own this website." +
                                              " [404]")
                        statusFile.close()
                        return 0

            except:
                website = Websites.objects.get(domain=domainName)
                externalApp = website.externalApp

                if admin.type != 1:
                    if website.admin != admin:
                        statusFile = open(tempStatusPath, 'w')
                        statusFile.writelines("You do not own this website." +
                                              " [404]")
                        statusFile.close()
                        return 0

            finalPath = ""

            if home == '0':
                path = self.extraArgs['path']
                finalPath = "/home/" + domainName + "/public_html/" + path + "/"
            else:
                finalPath = "/home/" + domainName + "/public_html/"

            ## Security Check

            if finalPath.find("..") > -1:
                statusFile = open(tempStatusPath, 'w')
                statusFile.writelines(
                    "Specified path must be inside virtual host home." +
                    " [404]")
                statusFile.close()
                return 0

            FNULL = open(os.devnull, 'w')

            if not os.path.exists(finalPath):
                command = 'sudo mkdir -p ' + finalPath
                subprocess.call(shlex.split(command))

            ## checking for directories/files

            dirFiles = os.listdir(finalPath)

            if len(dirFiles) == 1:
                if dirFiles[0] == ".well-known":
                    pass
                else:
                    statusFile = open(tempStatusPath, 'w')
                    statusFile.writelines(
                        "Target directory should be empty before installation, otherwise data loss could occur."
                        + " [404]")
                    statusFile.close()
                    return 0
            elif len(dirFiles) == 0:
                pass
            else:
                statusFile = open(tempStatusPath, 'w')
                statusFile.writelines(
                    "Target directory should be empty before installation, otherwise data loss could occur."
                    + " [404]")
                statusFile.close()
                return 0

            ## DB Creation

            statusFile = open(tempStatusPath, 'w')
            statusFile.writelines('Setting up Database,20')
            statusFile.close()

            dbName = randomPassword.generate_pass()
            dbUser = dbName
            dbPassword = randomPassword.generate_pass()

            ## DB Creation

            if website.package.dataBases > website.databases_set.all().count():
                pass
            else:
                statusFile = open(tempStatusPath, 'w')
                statusFile.writelines(
                    "Maximum database limit reached for this website." +
                    " [404]")
                statusFile.close()
                return 0

            if Databases.objects.filter(
                    dbName=dbName).exists() or Databases.objects.filter(
                        dbUser=dbUser).exists():
                statusFile = open(tempStatusPath, 'w')
                statusFile.writelines(
                    "This database or user is already taken." + " [404]")
                statusFile.close()
                return 0

            result = mysqlUtilities.createDatabase(dbName, dbUser, dbPassword)

            if result == 1:
                pass
            else:
                statusFile = open(tempStatusPath, 'w')
                statusFile.writelines("Not able to create database." +
                                      " [404]")
                statusFile.close()
                return 0

            db = Databases(website=website, dbName=dbName, dbUser=dbUser)
            db.save()

            ####

            statusFile = open(tempStatusPath, 'w')
            statusFile.writelines('Downloading WordPress Core,30')
            statusFile.close()

            command = "sudo wp core download --allow-root --path=" + finalPath
            subprocess.call(shlex.split(command))

            ##

            statusFile = open(tempStatusPath, 'w')
            statusFile.writelines('Configuring the installation,40')
            statusFile.close()

            command = "sudo wp core config --dbname=" + dbName + " --dbuser="******" --dbpass="******" --dbhost=localhost --dbprefix=wp_ --allow-root --path=" + finalPath
            subprocess.call(shlex.split(command))

            if home == '0':
                path = self.extraArgs['path']
                finalURL = domainName + '/' + path
            else:
                finalURL = domainName

            command = 'sudo wp core install --url="http://' + finalURL + '" --title="' + blogTitle + '" --admin_user="******" --admin_password="******" --admin_email="' + adminEmail + '" --allow-root --path=' + finalPath
            subprocess.call(shlex.split(command))

            ##

            statusFile = open(tempStatusPath, 'w')
            statusFile.writelines('Installing LSCache Plugin,80')
            statusFile.close()

            command = "sudo wp plugin install litespeed-cache --allow-root --path=" + finalPath
            subprocess.call(shlex.split(command))

            statusFile = open(tempStatusPath, 'w')
            statusFile.writelines('Activating LSCache Plugin,90')
            statusFile.close()

            command = "sudo wp plugin activate litespeed-cache --allow-root --path=" + finalPath
            subprocess.call(shlex.split(command))

            ##

            command = "sudo chown -R " + externalApp + ":" + externalApp + " " + "/home/" + domainName + "/public_html/"
            cmd = shlex.split(command)
            res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT)

            vhost.addRewriteRules(domainName)
            installUtilities.reStartLiteSpeed()

            statusFile = open(tempStatusPath, 'w')
            statusFile.writelines("Successfully Installed. [200]")
            statusFile.close()
            return 0

        except BaseException, msg:
            # remove the downloaded files
            try:

                command = "sudo rm -rf " + finalPath
                cmd = shlex.split(command)
                res = subprocess.call(cmd,
                                      stdout=FNULL,
                                      stderr=subprocess.STDOUT)

            except BaseException, msg:
                logging.writeToFile(str(msg) + " [installWordPress]")