def compress(self): try: finalData = {} finalData['status'] = 1 domainName = self.data['domainName'] website = Websites.objects.get(domain=domainName) if self.data['compressionType'] == 'zip': compressedFileName = self.returnPathEnclosed( self.data['basePath'] + '/' + self.data['compressedFileName'] + '.zip') command = 'zip -r ' + compressedFileName + ' ' else: compressedFileName = self.returnPathEnclosed( self.data['basePath'] + '/' + self.data['compressedFileName'] + '.tar.gz') command = 'tar -czvf ' + compressedFileName + ' ' for item in self.data['listOfFiles']: command = '%s%s ' % (command, self.returnPathEnclosed(item)) finalCommand = 'cd %s && %s' % (self.data['basePath'], command) ProcessUtilities.executioner(finalCommand, website.externalApp) self.changeOwner(self.data['compressedFileName']) json_data = json.dumps(finalData) return HttpResponse(json_data) except BaseException, msg: return self.ajaxPre(0, str(msg))
def submitRestore(self, data = None, userID = None): try: backupFile = data['backupFile'] originalFile = "/home/backup/" + backupFile if not os.path.exists(originalFile): dir = data['dir'] else: dir = "CyberPanelRestore" currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadErrorJson() execPath = "sudo nice -n 10 /usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" execPath = execPath + " submitRestore --backupFile " + backupFile + " --dir " + dir ProcessUtilities.popenExecutioner(execPath) time.sleep(4) final_dic = {'restoreStatus': 1, 'error_message': "None"} final_json = json.dumps(final_dic) return HttpResponse(final_json) except BaseException, msg: final_dic = {'restoreStatus': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json)
def rename(self): try: finalData = {} finalData['status'] = 1 domainName = self.data['domainName'] website = Websites.objects.get(domain=domainName) if self.data['newFileName'].find('..') > -1: return self.ajaxPre( 0, 'Not allowed to move in this path, please choose location inside home!' ) command = 'mv ' + self.returnPathEnclosed( self.data['basePath'] + '/' + self.data['existingName']) + ' ' + self.returnPathEnclosed( self.data['basePath'] + '/' + self.data['newFileName']) ProcessUtilities.executioner(command, website.externalApp) self.changeOwner(self.data['basePath'] + '/' + self.data['newFileName']) json_data = json.dumps(finalData) return HttpResponse(json_data) except BaseException, msg: return self.ajaxPre(0, str(msg))
def remoteBackupRestore(self, userID = None, data = None): try: currentACL = ACLManager.loadedACL(userID) if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: return ACLManager.loadErrorJson('remoteTransferStatus', 0) backupDir = data['backupDir'] backupDirComplete = "/home/backup/transfer-" + str(backupDir) # adminEmail = admin.email ## execPath = "/usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/remoteTransferUtilities.py" execPath = execPath + " remoteBackupRestore --backupDirComplete " + backupDirComplete + " --backupDir " + str( backupDir) ProcessUtilities.popenExecutioner(execPath) time.sleep(3) data = {'remoteRestoreStatus': 1, 'error_message': 'None'} json_data = json.dumps(data) return HttpResponse(json_data) except BaseException, msg: data = {'remoteRestoreStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data) return HttpResponse(json_data)
def deleteBackup(self, userID = None, data = None): try: backupID = data['backupID'] backup = Backups.objects.get(id=backupID) domainName = backup.website.domain currentACL = ACLManager.loadedACL(userID) admin = Administrator.objects.get(pk=userID) if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: pass else: return ACLManager.loadErrorJson() path = "/home/" + domainName + "/backup/" + backup.fileName + ".tar.gz" command = 'sudo rm -f ' + path ProcessUtilities.executioner(command) backup.delete() final_json = json.dumps({'status': 1, 'deleteStatus': 1, 'error_message': "None"}) return HttpResponse(final_json) except BaseException, msg: final_dic = {'status': 0, 'deleteStatus': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json)
def renderC(self): userID = self.request.session['userID'] currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadError() data = {} data['OLS'] = 0 data['notInstalled'] = 0 if ProcessUtilities.decideServer() == ProcessUtilities.OLS: data['OLS'] = 1 data['notInstalled'] = 0 return render(self.request, 'containerization/notAvailable.html', data) elif not ProcessUtilities.containerCheck(): data['OLS'] = 0 data['notInstalled'] = 1 return render(self.request, 'containerization/notAvailable.html', data) else: if self.data == None: self.data = {} self.data['OLS'] = 0 self.data['notInstalled'] = 0 return render(self.request, self.templateName, self.data)
def addTrafficController(self): command = 'sudo tc qdisc add dev eth0 root handle 10: htb default 1000' #logging.CyberCPLogFileWriter.writeToFile(command) ProcessUtilities.executioner(command) try: command = 'sudo tc class del dev eth0 classid 10:' + str(self.data['classID']) # logging.CyberCPLogFileWriter.writeToFile(command) ProcessUtilities.executioner(command) except: pass command = 'sudo tc class add dev eth0 parent 10: classid 10:1000 htb rate 100mbit' #logging.CyberCPLogFileWriter.writeToFile(command) ProcessUtilities.executioner(command) command = 'sudo tc class add dev eth0 parent 10: classid 10:' + str(self.data['classID']) + ' htb rate ' + str(self.data['rateLimit']) #logging.CyberCPLogFileWriter.writeToFile(command) ProcessUtilities.executioner(command) #if str(self.data['classID']) == '1': # command = 'sudo tc filter add dev eth0 parent 10: protocol ip prio 10 handle 1: cgroup' #else: # command = 'sudo tc filter add dev eth0 parent 10:' + str( # self.data['classID']) + ' protocol ip prio 10 handle 1: cgroup' command = 'sudo tc filter add dev eth0 parent 10: protocol ip prio 10 handle 1: cgroup' #logging.CyberCPLogFileWriter.writeToFile(command) ProcessUtilities.executioner(command) self.restartServices()
def getLogsFromFile(request): try: userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadErrorJson('logstatus', 0) data = json.loads(request.body) type = data['type'] if type == "access": fileName = installUtilities.Server_root_path + "/logs/access.log" elif type == "error": fileName = installUtilities.Server_root_path + "/logs/error.log" elif type == "email": if ProcessUtilities.decideDistro() == ProcessUtilities.centos: fileName = "/var/log/maillog" else: fileName = "/var/log/mail.log" elif type == "ftp": if ProcessUtilities.decideDistro() == ProcessUtilities.centos: fileName = "/var/log/messages" else: fileName = "/var/log/syslog" elif type == "modSec": fileName = "/usr/local/lsws/logs/auditmodsec.log" elif type == "cyberpanel": fileName = "/home/cyberpanel/error-logs.txt" try: command = "sudo tail -50 " + fileName fewLinesOfLogFile = ProcessUtilities.outputExecutioner(command) status = { "status": 1, "logstatus": 1, "logsdata": fewLinesOfLogFile } final_json = json.dumps(status) return HttpResponse(final_json) except: status = {"status": 1, "logstatus": 1, "logsdata": 'Emtpy File.'} final_json = json.dumps(status) return HttpResponse(final_json) except KeyError, msg: status = { "status": 0, "logstatus": 0, "error": "Could not fetch data from log file, please see CyberCP main log file through command line." } logging.CyberCPLogFileWriter.writeToFile( str(msg) + "[getLogsFromFile]") final_json = json.dumps(status) return HttpResponse(final_json)
def changePermissions(self): try: finalData = {} finalData['status'] = 1 domainName = self.data['domainName'] website = Websites.objects.get(domain=domainName) if self.data['recursive'] == 1: command = 'chmod -R ' + self.data[ 'newPermissions'] + ' ' + self.returnPathEnclosed( self.data['basePath'] + '/' + self.data['permissionsPath']) else: command = 'chmod ' + self.data[ 'newPermissions'] + ' ' + self.returnPathEnclosed( self.data['basePath'] + '/' + self.data['permissionsPath']) ProcessUtilities.executioner(command, website.externalApp) json_data = json.dumps(finalData) return HttpResponse(json_data) except BaseException, msg: return self.ajaxPre(0, str(msg))
def gitPull(self): try: domain = self.extraArgs['domain'] try: website = Websites.objects.get(domain=domain) finalPath = "/home/" + domain + "/public_html/" externalApp = website.externalApp except: childDomain = ChildDomains.objects.get(domain=domain) finalPath = childDomain.path externalApp = website.externalApp path = '/home/cyberpanel/' + domain + '.git' if not os.path.exists(path): logging.writeToFile('Git is not setup for this website.') return 0 command = 'sudo git --git-dir=' + finalPath + '.git --work-tree=' + finalPath + ' pull' ProcessUtilities.executioner(command, externalApp) ## website = Websites.objects.get(domain=domain) externalApp = website.externalApp command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath ProcessUtilities.executioner(command, externalApp) return 0 except BaseException, msg: logging.writeToFile(str(msg) + " [ApplicationInstaller.gitPull]") return 0
def checkIP(ipAddress): try: command = 'sudo csf -g ' + ipAddress ProcessUtilities.executioner(command) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[checkIP]")
def localFunction(self, backupPath, type, restore=None): if restore == None: command = 'restic -r %s backup %s --password-file %s --exclude %s' % ( self.repoPath, backupPath, self.passwordFile, self.repoPath) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1) snapShotid = result.split(' ')[-2] if type == 'database': newSnapshot = JobSnapshots( job=self.jobid, type='%s:%s' % (type, backupPath.split('/')[-1].strip('.sql')), snapshotid=snapShotid, destination=self.backupDestinations) else: newSnapshot = JobSnapshots(job=self.jobid, type='%s:%s' % (type, backupPath), snapshotid=snapShotid, destination=self.backupDestinations) newSnapshot.save() else: repoLocation = '/home/%s/incbackup' % (self.website) command = 'restic -r %s restore %s --target / --password-file %s' % ( repoLocation, self.jobid.snapshotid, self.passwordFile) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1)
def stopOrRestartLitespeed(request): try: userID = request.session['userID'] admin = Administrator.objects.get(pk=userID) if admin.type == 3: return HttpResponse("You don't have enough priviliges to access this page.") data = json.loads(request.body) reboot = data['reboot'] if reboot==1: if ProcessUtilities.restartLitespeed() == 1: status = {"reboot":1,"shutdown":0} else: status = {"reboot": 0, "shutdown": 0, "error_message":"Please see CyberCP main log file."} else: if ProcessUtilities.stopLitespeed() == 1: status = {"reboot":0,"shutdown":1} else: status = {"reboot": 0, "shutdown": 0, "error_message":"Please see CyberCP main log file."} final_json = json.dumps(status) return HttpResponse(final_json) except KeyError, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[stopOrRestartLitespeed]") return HttpResponse("Not Logged in as admin")
def initiateRepo(self): try: logging.statusWriter(self.statusPath, 'Will first initiate backup repo..', 1) if self.backupDestinations == 'local': command = 'restic init --repo %s --password-file %s' % ( self.repoPath, self.passwordFile) ProcessUtilities.executioner(command, self.website.externalApp) elif self.backupDestinations[:4] == 'sftp': remotePath = '/home/backup/%s' % (self.website.domain) command = 'export PATH=${PATH}:/usr/bin && restic init --repo %s:%s --password-file %s' % ( self.backupDestinations, remotePath, self.passwordFile) ProcessUtilities.executioner(command) logging.statusWriter( self.statusPath, 'Repo %s initiated for %s.' % (self.backupDestinations, self.website.domain), 1) return 1 except BaseException, msg: logging.statusWriter( self.statusPath, '%s. [IncJobs.initiateRepo.47][5009]' % str(msg), 1) return 0
def switchTOLSWS(request): try: userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadErrorJson('status', 0) data = json.loads(request.body) try: licenseKey = data['licenseKey'] except: licenseKey = 'trial' execPath = "sudo /usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/serverStatus/serverStatusUtil.py" execPath = execPath + " switchTOLSWS --licenseKey " + licenseKey ProcessUtilities.popenExecutioner(execPath) time.sleep(2) data_ret = { 'status': 1, 'error_message': "None", } json_data = json.dumps(data_ret) return HttpResponse(json_data) except BaseException, msg: data_ret = {'status': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data)
def deleteRule(proto, port, ipAddress): ruleFamily = 'rule family="ipv4"' sourceAddress = 'source address="' + ipAddress + '"' ruleProtocol = 'port protocol="' + proto + '"' rulePort = 'port="' + port + '"' command = "sudo firewall-cmd --permanent --zone=public --remove-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'" if ProcessUtilities.executioner(command) == 0: return 0 ruleFamily = 'rule family="ipv6"' sourceAddress = '' command = "sudo firewall-cmd --permanent --zone=public --remove-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'" if ProcessUtilities.executioner(command) == 0: return 0 command = 'sudo firewall-cmd --reload' if ProcessUtilities.executioner(command) == 0: return 0 return 1
def ExtractBackup(self): try: message = 'Extracting main cPanel archive file: %s' % ( self.backupFile) logging.statusWriter(self.logFile, message, 1) if not os.path.exists(cPanelImporter.mainBackupPath): os.mkdir(cPanelImporter.mainBackupPath) os.chdir(cPanelImporter.mainBackupPath) command = 'tar -xf %s --directory %s' % ( self.backupFile, cPanelImporter.mainBackupPath) ProcessUtilities.normalExecutioner(command) message = '%s successfully extracted.' % (self.backupFile) logging.statusWriter(self.logFile, message, 1) return 1 except BaseException, msg: message = 'Failed to extract backup for file %s, error message: %s. [ExtractBackup]' % ( self.backupFile, str(msg)) logging.statusWriter(self.logFile, message, 1) return 0
def changeBranch(self): try: domainName = self.extraArgs['domainName'] githubBranch = self.extraArgs['githubBranch'] admin = self.extraArgs['admin'] try: website = Websites.objects.get(domain=domainName) finalPath = "/home/" + domainName + "/public_html/" externalApp = website.externalApp except: childDomain = ChildDomains.objects.get(domain=domainName) finalPath = childDomain.path externalApp = childDomain.master.externalApp try: command = 'sudo git --git-dir=' + finalPath + '/.git checkout -b ' + githubBranch ProcessUtilities.executioner(command, externalApp) except: try: command = 'sudo git --git-dir=' + finalPath + '/.git checkout ' + githubBranch ProcessUtilities.executioner(command, externalApp) except subprocess.CalledProcessError, msg: logging.writeToFile('Failed to change branch: ' + str(msg)) return 0 return 0
def killProcess(request): try: userID = request.session['userID'] try: currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadErrorJson('status', 0) data = json.loads(request.body) pid = data['pid'] ProcessUtilities.executioner('sudo kill ' + pid) proc = httpProc(request, None) return proc.ajax(1, None) except BaseException, msg: final_dic = {'status': 0, 'erroMessage': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) except KeyError, msg: final_dic = {'status': 0, 'erroMessage': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json)
def licenseStatus(request): try: userID = request.session['userID'] try: currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadErrorJson('status', 0) command = 'sudo cat /usr/local/lsws/conf/serial.no' serial = ProcessUtilities.outputExecutioner(command) command = 'sudo /usr/local/lsws/bin/lshttpd -V' expiration = ProcessUtilities.outputExecutioner(command) final_dic = { 'status': 1, "erroMessage": 0, 'lsSerial': serial, 'lsexpiration': expiration } final_json = json.dumps(final_dic) return HttpResponse(final_json) except BaseException, msg: final_dic = {'status': 0, 'erroMessage': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) except KeyError, msg: final_dic = {'status': 0, 'erroMessage': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json)
def initiateRepo(self): try: logging.statusWriter(self.statusPath, 'Will first initiate backup repo..', 1) if self.backupDestinations == 'local': command = 'restic init --repo %s --password-file %s' % ( self.repoPath, self.passwordFile) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1) elif self.backupDestinations[:4] == 'sftp': remotePath = '/home/backup/%s' % (self.website.domain) command = 'export PATH=${PATH}:/usr/bin && restic init --repo %s:%s --password-file %s' % ( self.backupDestinations, remotePath, self.passwordFile) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1) else: key, secret = self.getAWSData() command = 'export AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s && restic -r s3:s3.amazonaws.com/%s init --password-file %s' % ( key, secret, self.website.domain, self.passwordFile) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1) return 1 logging.statusWriter( self.statusPath, 'Repo %s initiated for %s.' % (self.backupDestinations, self.website.domain), 1) return 1 except BaseException, msg: logging.statusWriter( self.statusPath, '%s. [IncJobs.initiateRepo.47][5009]' % str(msg), 1) return 0
def installSpamAssassin(request): try: userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadErrorJson() try: execPath = "/usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" execPath = execPath + " installSpamAssassin" ProcessUtilities.popenExecutioner(execPath) final_json = json.dumps({'status': 1, 'error_message': "None"}) return HttpResponse(final_json) except BaseException,msg: final_dic = {'status': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) except KeyError: final_dic = {'status': 0, 'error_message': "Not Logged In, please refresh the page or login again."} final_json = json.dumps(final_dic) return HttpResponse(final_json)
def remoteTransfer(request): try: if request.method == "POST": data = json.loads(request.body) username = data['username'] password = data['password'] admin = Administrator.objects.get(userName=username) if admin.api == 0: data_ret = { "transferStatus": 0, 'error_message': "API Access Disabled." } json_data = json.dumps(data_ret) return HttpResponse(json_data) ipAddress = data['ipAddress'] accountsToTransfer = data['accountsToTransfer'] if hashPassword.check_password(admin.password, password): dir = str(randint(1000, 9999)) ## mailUtilities.checkHome() path = "/home/cyberpanel/accounts-" + str(randint(1000, 9999)) writeToFile = open(path, 'w') for items in accountsToTransfer: writeToFile.writelines(items + "\n") writeToFile.close() ## Accounts to transfer is a path to file, containing accounts. execPath = "/usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/remoteTransferUtilities.py" execPath = execPath + " remoteTransfer --ipAddress " + ipAddress + " --dir " + dir + " --accountsToTransfer " + path ProcessUtilities.popenExecutioner(execPath) return HttpResponse( json.dumps({ "transferStatus": 1, "dir": dir })) ## else: data_ret = { 'transferStatus': 0, 'error_message': "Could not authorize access to API." } json_data = json.dumps(data_ret) return HttpResponse(json_data) except BaseException, msg: data = {'transferStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data) return HttpResponse(json_data)
def installStatusSpamAssassin(request): try: userID = request.session['userID'] try: if request.method == 'POST': command = "sudo cat " + mailUtilities.spamassassinInstallLogPath installStatus = ProcessUtilities.outputExecutioner(command) if installStatus.find("[200]")>-1: execPath = "/usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" execPath = execPath + " configureSpamAssassin" output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: pass else: final_json = json.dumps({ 'error_message': "Failed to install SpamAssassin configurations.", 'requestStatus': installStatus, 'abort': 1, 'installed': 0, }) return HttpResponse(final_json) final_json = json.dumps({ 'error_message': "None", 'requestStatus': installStatus, 'abort':1, 'installed': 1, }) return HttpResponse(final_json) elif installStatus.find("[404]") > -1: final_json = json.dumps({ 'abort':1, 'installed':0, 'error_message': "None", 'requestStatus': installStatus, }) return HttpResponse(final_json) else: final_json = json.dumps({ 'abort':0, 'error_message': "None", 'requestStatus': installStatus, }) return HttpResponse(final_json) except BaseException,msg: final_dic = {'abort':1,'installed':0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) except KeyError: final_dic = {'abort':1,'installed':0, 'error_message': "Not Logged In, please refresh the page or login again."} final_json = json.dumps(final_dic) return HttpResponse(final_json)
def servicesAction(request): try: userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadErrorJson('serviceAction', 0) try: if request.method == 'POST': data = json.loads(request.body) service = data['service'] action = data['action'] if action not in ["stop", "start", "restart"]: final_dic = { 'serviceAction': 0, "error_message": "Invalid Action" } final_json = json.dumps(final_dic) return HttpResponse(final_json) else: pass if service not in [ "lsws", "mysql", "pdns", "pure-ftpd", "docker" ]: final_dic = { 'serviceAction': 0, "error_message": "Invalid Service" } final_json = json.dumps(final_dic) return HttpResponse(final_json) else: if service == 'pure-ftpd': if os.path.exists("/etc/lsb-release"): service = 'pure-ftpd-mysql' else: service = 'pure-ftpd' command = 'sudo systemctl %s %s' % (action, service) ProcessUtilities.executioner(command) final_dic = {'serviceAction': 1, "error_message": 0} final_json = json.dumps(final_dic) return HttpResponse(final_json) except BaseException, msg: final_dic = {'serviceAction': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json) except KeyError, msg: final_dic = {'serviceAction': 0, 'error_message': str(msg)} final_json = json.dumps(final_dic) return HttpResponse(final_json)
def run(self): try: if self.function == 'submitInstallDocker': self.submitInstallDocker() elif self.function == 'restartGunicorn': command = 'sudo systemctl restart gunicorn.socket' ProcessUtilities.executioner(command) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile( str(msg) + ' [ContainerManager.run]')
def prepare(): try: backupLogPath = "/usr/local/lscp/logs/local_backup_log." + time.strftime( "%m.%d.%Y_%H-%M-%S") writeToFile = open(backupLogPath, "a") backupSchedule.remoteBackupLogging( backupLogPath, "#################################################") backupSchedule.remoteBackupLogging( backupLogPath, " Local Backup log for: " + time.strftime("%m.%d.%Y_%H-%M-%S")) backupSchedule.remoteBackupLogging( backupLogPath, "#################################################\n") backupSchedule.remoteBackupLogging(backupLogPath, "") backupSchedule.remoteBackupLogging(backupLogPath, "") for virtualHost in os.listdir("/home"): if match( r'([\da-z\.-]+\.[a-z\.]{2,12}|[\d\.]+)([\/:?=&#]{1}[\da-z\.-]+)*[\/\?]?', virtualHost, M | I): retValues = backupSchedule.createLocalBackup( virtualHost, backupLogPath) if os.path.exists(backupScheduleLocal.localBackupPath): backupPath = retValues[1] + ".tar.gz" localBackupPath = '%s/%s' % (open( backupScheduleLocal.localBackupPath, 'r').read().rstrip('/'), time.strftime("%b-%d-%Y")) command = 'mkdir -p %s' % (localBackupPath) ProcessUtilities.normalExecutioner(command) command = 'mv %s %s' % (backupPath, localBackupPath) ProcessUtilities.normalExecutioner(command) backupSchedule.remoteBackupLogging(backupLogPath, "") backupSchedule.remoteBackupLogging(backupLogPath, "") backupSchedule.remoteBackupLogging( backupLogPath, "#################################################") backupSchedule.remoteBackupLogging(backupLogPath, "") backupSchedule.remoteBackupLogging(backupLogPath, "") backupSchedule.remoteBackupLogging( backupLogPath, "Local backup job completed.\n") writeToFile.close() except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile( str(msg) + " [214:startBackup]")
def GenerateSelfSignedSSL(virtualHostName): if os.path.exists(ApacheVhost.sslBasePath): pass else: os.mkdir(ApacheVhost.sslBasePath) pathToStoreSSLPrivKey = ApacheVhost.sslBasePath + virtualHostName + ".privkey.pem" pathToStoreSSLFullChain = ApacheVhost.sslBasePath + virtualHostName + ".fullchain.pem" command = 'openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain ProcessUtilities.normalExecutioner(command)
def getRemoteBackups(self): if self.backupDestinations[:4] == 'sftp': path = '/home/backup/%s' % (self.website) command = 'export RESTIC_PASSWORD=%s PATH=${PATH}:/usr/bin && restic -r %s:%s snapshots' % ( self.passwordFile, self.backupDestinations, path) return ProcessUtilities.outputExecutioner(command).split('\n') else: key, secret = self.getAWSData() command = 'export RESTIC_PASSWORD=%s AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s && restic -r s3:s3.amazonaws.com/%s snapshots' % ( self.passwordFile, key, secret, self.website) return ProcessUtilities.outputExecutioner(command).split('\n')
def restartMySQL(): try: command = 'sudo systemctl restart mysql' ProcessUtilities.executioner(command) return 1, None except BaseException, msg: command = 'sudo mv /etc/my.cnf.bak /etc/my.cnf' subprocess.call(shlex.split(command)) logging.CyberCPLogFileWriter.writeToFile(str(msg)) return 0, str(msg)
def ftpFunctions(path, externalApp): try: command = 'mkdir %s' % (path) ProcessUtilities.executioner(command, externalApp) return 1, 'None' except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile( str(msg) + " [ftpFunctions]") return 0, str(msg)
def litespeedStatus(request): try: userID = request.session['userID'] admin = Administrator.objects.get(pk=userID) if admin.type == 3: return HttpResponse("You don't have enough priviliges to access this page.") processList = ProcessUtilities.getLitespeedProcessNumber() try: versionInformation = subprocess.check_output(["/usr/local/lsws/bin/lshttpd", "-v"]).split("\n") lsversion = versionInformation[0] modules = versionInformation[1] counter = 0 loadedModules = [] for items in versionInformation: if counter == 0 or counter == 1: counter = counter + 1 continue else: loadedModules.append(items) except subprocess.CalledProcessError,msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[litespeedStatus]") return render(request,"serverStatus/litespeedStatus.html",{"processList":processList,"liteSpeedVersionStatus":"For some reaons not able to load version details, see CyberCP main log file."}) if(processList!=0): dataForHtml = {"processList": processList, "lsversion": lsversion, "modules": modules, "loadedModules": loadedModules} return render(request,"serverStatus/litespeedStatus.html",dataForHtml) else: dataForHtml = {"lsversion": lsversion, "modules": modules, "loadedModules": loadedModules} return render(request, "serverStatus/litespeedStatus.html",dataForHtml)