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 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 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 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 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 configservercsfiframe(request): userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadError() if request.method == 'GET': qs = request.GET.urlencode() elif request.method == 'POST': qs = request.POST.urlencode() try: tmp = tempfile.NamedTemporaryFile(mode="w", delete=False) tmp.write(qs) tmp.close() command = "/usr/local/csf/bin/cyberpanel.pl '" + tmp.name + "'" try: output = ProcessUtilities.outputExecutioner(command) except: output = "Output Error from csf UI script" os.unlink(tmp.name) except: output = "Unable to create csf UI temp file" return HttpResponse(output)
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 setupPHPMYAdminSession(request): try: userID = request.session['userID'] admin = Administrator.objects.get(id = userID) execPath = "/usr/local/CyberCP/bin/python2 /usr/local/CyberCP/databases/databaseManager.py" execPath = execPath + " generatePHPMYAdminData --userID " + str(userID) output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,") > -1: request.session['PMA_single_signon_user'] = admin.userName request.session['PMA_single_signon_password'] = output.split(',')[1] data_ret = {'status': 1} json_data = json.dumps(data_ret) return HttpResponse(json_data) else: data_ret = {'status': 1} json_data = json.dumps(data_ret) return HttpResponse(json_data) except BaseException, msg: data_ret = {'status': 0, 'createDBStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data)
def scheduleDelete(self, userID = None, data = None): try: currentACL = ACLManager.loadedACL(userID) if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: return ACLManager.loadErrorJson('scheduleStatus', 0) backupDest = data['destLoc'] backupFreq = data['frequency'] findTxt = "" if backupDest == "Home" and backupFreq == "Daily": findTxt = "0 3" elif backupDest == "Home" and backupFreq == "Weekly": findTxt = "0 0" elif backupDest != "Home" and backupFreq == "Daily": findTxt = "0 3" elif backupDest != "Home" and backupFreq == "Weekly": findTxt = "0 0" ### logging.CyberCPLogFileWriter.writeToFile(findTxt) logging.CyberCPLogFileWriter.writeToFile(backupFreq) path = "/etc/crontab" command = "cat " + path output = ProcessUtilities.outputExecutioner(command).split('\n') tempCronPath = "/home/cyberpanel/" + str(randint(1000, 9999)) writeToFile = open(tempCronPath, 'w') for items in output: if (items.find(findTxt) > -1 and items.find("backupScheduleLocal.py") > -1) or (items.find(findTxt) > -1 and items.find('backupSchedule.py')): continue else: writeToFile.writelines(items + '\n') writeToFile.close() command = "sudo mv " + tempCronPath + " " + path ProcessUtilities.executioner(command) command = 'chown root:root %s' % (path) ProcessUtilities.executioner(command) command = "sudo systemctl restart crond" ProcessUtilities.executioner(command) destination = dest.objects.get(destLoc=backupDest) newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) newSchedule.delete() final_json = json.dumps({'delStatus': 1, 'error_message': "None"}) return HttpResponse(final_json) except BaseException, msg: final_json = json.dumps({'delStatus': 0, 'error_message': str(msg)}) return HttpResponse(final_json)
def findWebsitesJson(self, currentACL, userID, pageNumber): finalPageNumber = ((pageNumber * 10)) - 10 endPageNumber = finalPageNumber + 10 websites = ACLManager.findWebsiteObjects( currentACL, userID)[finalPageNumber:endPageNumber] json_data = "[" checker = 0 command = '/usr/sbin/cagefsctl --list-enabled' Enabled = ProcessUtilities.outputExecutioner(command) for items in websites: if Enabled.find(items.externalApp) > -1: status = 1 else: status = 0 dic = { 'domain': items.domain, 'externalApp': items.externalApp, 'status': status } if checker == 0: json_data = json_data + json.dumps(dic) checker = 1 else: json_data = json_data + ',' + json.dumps(dic) json_data = json_data + ']' return json_data
def reconstructWithMeta(self): try: if self.reconstruct == 'remote': if self.backupDestinations[:4] == 'sftp': self.sftpFunction('none', 'none', 1) else: self.awsFunction('restore', '', self.jobid) else: if self.jobid.destination == 'local': self.localFunction('none', 'none', 1) elif self.jobid.destination[:4] == 'sftp': self.sftpFunction('none', 'none', 1) else: self.awsFunction('restore', '', self.jobid.snapshotid) metaPathNew = '/home/%s/meta.xml' % (self.website) execPath = "nice -n 10 /usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/IncBackups/restoreMeta.py" execPath = execPath + " submitRestore --metaPath %s --statusFile %s" % ( metaPathNew, self.statusPath) result = ProcessUtilities.outputExecutioner(execPath) logging.statusWriter(self.statusPath, result, 1) try: os.remove(metaPathNew) except: pass except BaseException, msg: logging.statusWriter(self.statusPath, "%s [46][5009]" % (str(msg)), 1) return 0
def awsFunction(self, fType, backupPath=None, snapshotID=None, bType=None): try: if fType == 'backup': key, secret = self.getAWSData() command = 'export AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s && restic -r s3:s3.amazonaws.com/%s backup %s --password-file %s' % ( key, secret, self.website.domain, backupPath, self.passwordFile) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1) snapShotid = result.split(' ')[-2] if bType == 'database': newSnapshot = JobSnapshots( job=self.jobid, type='%s:%s' % (bType, backupPath.split('/')[-1].strip('.sql')), snapshotid=snapShotid, destination=self.backupDestinations) else: newSnapshot = JobSnapshots( job=self.jobid, type='%s:%s' % (bType, backupPath), snapshotid=snapShotid, destination=self.backupDestinations) newSnapshot.save() else: if self.reconstruct == 'remote': self.backupDestinations = self.backupDestinations 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 restore %s --target /' % ( self.passwordFile, key, secret, self.website, snapshotID) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1) else: self.backupDestinations = self.jobid.destination key, secret = self.getAWSData() command = 'export AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s && restic -r s3:s3.amazonaws.com/%s restore %s --password-file %s --target /' % ( key, secret, self.website, snapshotID, self.passwordFile) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1) except BaseException, msg: logging.statusWriter(self.statusPath, "%s [88][5009]" % (str(msg)), 1) return 0
def fetchPHPSettingsAdvance(phpVersion): command = "sudo cat " + PHPManager.FindPHPFPMPath(phpVersion) data = ProcessUtilities.outputExecutioner(command) final_dic = {'fetchStatus': 1, 'configData': data, 'status': 1} final_json = json.dumps(final_dic) return HttpResponse(final_json)
def emailBackup(self): try: logging.statusWriter(self.statusPath, 'Backing up emails..', 1) backupPath = '/home/vmail/%s' % (self.website.domain) if os.path.exists(backupPath): if self.backupDestinations == 'local': logging.statusWriter(self.statusPath, 'hello world', 1) command = 'restic -r %s backup %s --password-file %s' % ( self.repoPath, backupPath, self.passwordFile) snapShotid = ProcessUtilities.outputExecutioner( command).split(' ')[-2] newSnapshot = JobSnapshots( job=self.jobid, type='email:%s' % (backupPath), snapshotid=snapShotid, destination=self.backupDestinations) newSnapshot.save() logging.statusWriter(self.statusPath, 'hello world 2', 1) elif self.backupDestinations[:4] == 'sftp': remotePath = '/home/backup/%s' % (self.website.domain) command = 'export PATH=${PATH}:/usr/bin && restic -r %s:%s backup %s --password-file %s --exclude %s' % ( self.backupDestinations, remotePath, backupPath, self.passwordFile, self.repoPath) snapShotid = ProcessUtilities.outputExecutioner( command).split(' ')[-2] newSnapshot = JobSnapshots( job=self.jobid, type='email:%s' % (backupPath), snapshotid=snapShotid, destination=self.backupDestinations) newSnapshot.save() logging.statusWriter( self.statusPath, 'Emails for %s backed to %s.' % (self.website.domain, self.backupDestinations), 1) return 1 except BaseException, msg: logging.statusWriter( self.statusPath, '%s. [IncJobs.backupDatabases.269][5009]' % str(msg), 1) return 0
def backupDatabases(self): try: logging.statusWriter(self.statusPath, 'Backing up databases..', 1) databases = self.website.databases_set.all() for items in databases: if mysqlUtilities.mysqlUtilities.createDatabaseBackup( items.dbName, '/home/cyberpanel') == 0: return 0 dbPath = '/home/cyberpanel/%s.sql' % (items.dbName) if self.backupDestinations == 'local': command = 'restic -r %s backup %s --password-file %s' % ( self.repoPath, dbPath, self.passwordFile) snapShotid = ProcessUtilities.outputExecutioner( command).split(' ')[-2] newSnapshot = JobSnapshots( job=self.jobid, type='database:%s' % (items.dbName), snapshotid=snapShotid, destination=self.backupDestinations) newSnapshot.save() elif self.backupDestinations[:4] == 'sftp': remotePath = '/home/backup/%s' % (self.website.domain) command = 'export PATH=${PATH}:/usr/bin && restic -r %s:%s backup %s --password-file %s --exclude %s' % ( self.backupDestinations, remotePath, dbPath, self.passwordFile, self.repoPath) snapShotid = ProcessUtilities.outputExecutioner( command).split(' ')[-2] newSnapshot = JobSnapshots( job=self.jobid, type='database:%s' % (items.dbName), snapshotid=snapShotid, destination=self.backupDestinations) newSnapshot.save() return 1 except BaseException, msg: logging.statusWriter( self.statusPath, '%s. [IncJobs.backupDatabases.269][5009]' % str(msg), 1) return 0
def submitContainerInstall(self): try: userID = self.request.session['userID'] currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, 'Not authorized to install container packages. [404].', 1) return 0 execPath = "/usr/local/CyberCP/bin/python2 /usr/local/CyberCP/containerization/container.py" execPath = execPath + " --function submitContainerInstall" ProcessUtilities.outputExecutioner(execPath) except BaseException, msg: logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1)
def getCurrentPHPConfig(phpVersion): allow_url_fopen = "0" display_errors = "0" file_uploads = "0" allow_url_include = "0" memory_limit = "" max_execution_time = "" upload_max_filesize = "" max_input_time = "" command = "sudo cat " + PHPManager.FindPHPFPMPath(phpVersion) data = ProcessUtilities.outputExecutioner(command).split('\n') for items in data: if items.find("allow_url_fopen") > -1 and items.find("=") > -1: if items.find("On") > -1: allow_url_fopen = "1" if items.find("display_errors") > -1 and items.find("=") > -1: if items.find("On") > -1: display_errors = "1" if items.find("file_uploads") > -1 and items.find("=") > -1: if items.find("On") > -1: file_uploads = "1" if items.find("allow_url_include") > -1 and items.find("=") > -1: if items.find("On") > -1: allow_url_include = "1" if items.find("memory_limit") > -1 and items.find("=") > -1: memory_limit = re.findall(r"[A-Za-z0-9_]+", items)[1] if items.find("max_execution_time") > -1 and items.find("=") > -1: max_execution_time = re.findall(r"[A-Za-z0-9_]+", items)[1] if items.find("upload_max_filesize") > -1 and items.find("=") > -1: upload_max_filesize = re.findall(r"[A-Za-z0-9_]+", items)[1] if items.find("max_input_time") > -1 and items.find("=") > -1: max_input_time = re.findall(r"[A-Za-z0-9_]+", items)[1] if items.find("post_max_size") > -1 and items.find("=") > -1: post_max_size = re.findall(r"[A-Za-z0-9_]+", items)[1] final_dic = { 'fetchStatus': 1, 'allow_url_fopen': allow_url_fopen, 'display_errors': display_errors, 'file_uploads': file_uploads, 'allow_url_include': allow_url_include, 'memory_limit': memory_limit, 'max_execution_time': max_execution_time, 'upload_max_filesize': upload_max_filesize, 'max_input_time': max_input_time, 'post_max_size': post_max_size, 'status': 1 } final_json = json.dumps(final_dic) return HttpResponse(final_json)
def fetchCSFSettings(): try: currentSettings = {} command = 'sudo cat /etc/csf/csf.conf' output = ProcessUtilities.outputExecutioner(command).splitlines() for items in output: if items.find('TESTING') > -1 and items.find('=') > -1 and (items[0] != '#') and items.find( 'TESTING_INTERVAL') == -1: if items.find('0') > -1: currentSettings['TESTING'] = 0 else: currentSettings['TESTING'] = 1 elif items.find('TCP_IN') > -1 and items.find('=') > -1 and (items[0] != '#'): tcpIN = items[items.find('"'):] currentSettings['tcpIN'] = tcpIN.strip('"') elif items.find('TCP_OUT') > -1 and items.find('=') > -1 and (items[0] != '#'): tcpOUT = items[items.find('"'):] currentSettings['tcpOUT'] = tcpOUT.strip('"') elif items.find('UDP_IN') > -1 and items.find('=') > -1 and (items[0] != '#'): udpIN = items[items.find('"'):] currentSettings['udpIN'] = udpIN.strip('"') elif items.find('UDP_OUT') > -1 and items.find('=') > -1 and (items[0] != '#'): udpOUT = items[items.find('"'):] currentSettings['udpOUT'] = udpOUT.strip('"') ### Check if rules are applied currentSettings['firewallStatus'] = 0 command = 'sudo iptables -nv -L' output = ProcessUtilities.outputExecutioner(command) if output.find('0.0.0.0/0') > -1: currentSettings['firewallStatus'] = 1 return currentSettings except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [fetchCSFSettings]")
def obtainHostNameSSL(request): try: userID = request.session['userID'] try: if request.method == 'POST': currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass elif currentACL['hostnameSSL'] == 1: pass else: return ACLManager.loadErrorJson('SSL', 0) data = json.loads(request.body) virtualHost = data['virtualHost'] path = "/home/" + virtualHost + "/public_html" data = json.loads(request.body) virtualHost = data['virtualHost'] admin = Administrator.objects.get(pk=userID) if ACLManager.checkOwnership(virtualHost, admin, currentACL) == 1: pass else: return ACLManager.loadErrorJson() ## ssl issue execPath = "/usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" execPath = execPath + " issueSSLForHostName --virtualHostName " + virtualHost + " --path " + path output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {"status": 1, "SSL": 1, 'error_message': "None"} json_data = json.dumps(data_ret) return HttpResponse(json_data) else: data_ret = {"status": 0, "SSL": 0, 'error_message': output} json_data = json.dumps(data_ret) return HttpResponse(json_data) ## ssl issue ends except BaseException, msg: data_ret = {"status": 0, "SSL": 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data) except KeyError: data_ret = {"status": 0, "SSL": 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data)
def listDomains(request): try: userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadError() try: websites = DomainLimits.objects.all() ## Check if Policy Server is installed. command = 'sudo cat /etc/postfix/main.cf' output = ProcessUtilities.outputExecutioner(command).split('\n') installCheck = 0 for items in output: if items.find('check_policy_service unix:/var/log/policyServerSocket') > -1: installCheck = 1 break if installCheck == 0: return render(request, 'emailPremium/listDomains.html', {"installCheck": installCheck}) ### pages = float(len(websites)) / float(10) pagination = [] if pages <= 1.0: pages = 1 pagination.append('<li><a href="\#"></a></li>') else: pages = ceil(pages) finalPages = int(pages) + 1 for i in range(1, finalPages): pagination.append('<li><a href="\#">' + str(i) + '</a></li>') return render(request,'emailPremium/listDomains.html',{"pagination":pagination, "installCheck": installCheck}) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) return HttpResponse("See CyberCP main log file.") except KeyError: return redirect(loadLoginPage)
def installStatusOpenDKIM(self): try: command = "sudo cat " + mailUtilities.installLogPath installStatus = subprocess.check_output(shlex.split(command)) if installStatus.find("[200]") > -1: execPath = "/usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" execPath = execPath + " configureOpenDKIM" output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: pass else: final_json = json.dumps({ 'error_message': "Failed to install OpenDKIM 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)
def sftpFunction(self, backupPath, type, restore=None): if restore == None: remotePath = '/home/backup/%s' % (self.website.domain) command = 'export PATH=${PATH}:/usr/bin && restic -r %s:%s backup %s --password-file %s --exclude %s' % ( self.backupDestinations, remotePath, 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: if self.reconstruct == 'remote': repoLocation = '/home/backup/%s' % (self.website) command = 'export RESTIC_PASSWORD=%s PATH=${PATH}:/usr/bin && restic -r %s:%s restore %s --target /' % ( self.passwordFile, self.backupDestinations, repoLocation, self.jobid) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1) else: repoLocation = '/home/backup/%s' % (self.website) command = 'export PATH=${PATH}:/usr/bin && restic -r %s:%s restore %s --target / --password-file %s' % ( self.jobid.destination, repoLocation, self.jobid.snapshotid, self.passwordFile) result = ProcessUtilities.outputExecutioner(command) logging.statusWriter(self.statusPath, result, 1)
def fetchDKIMKeys(self): try: userID = self.request.session['userID'] currentACL = ACLManager.loadedACL(userID) if ACLManager.currentContextPermission(currentACL, 'dkimManager') == 0: return ACLManager.loadErrorJson('fetchStatus', 0) data = json.loads(self.request.body) domainName = data['domainName'] admin = Administrator.objects.get(pk=userID) if ACLManager.checkOwnership(domainName, admin, currentACL) == 1: pass else: return ACLManager.loadError() try: path = "/etc/opendkim/keys/" + domainName + "/default.txt" command = "sudo cat " + path output = ProcessUtilities.outputExecutioner(command, 'opendkim') leftIndex = output.index('(') + 2 rightIndex = output.rindex(')') - 1 path = "/etc/opendkim/keys/" + domainName + "/default.private" command = "sudo cat " + path privateKey = ProcessUtilities.outputExecutioner(command, 'opendkim') data_ret = {'status': 1, 'fetchStatus': 1, 'keysAvailable': 1, 'publicKey': output[leftIndex:rightIndex], 'privateKey': privateKey, 'dkimSuccessMessage': 'Keys successfully fetched!', 'error_message': "None"} json_data = json.dumps(data_ret) return HttpResponse(json_data) except BaseException, msg: data_ret = {'status': 1, 'fetchStatus': 1, 'keysAvailable': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data)
def restoreStatus(self, data = None): try: backupFile = data['backupFile'].strip(".tar.gz") path = os.path.join("/home", "backup", data['backupFile']) if os.path.exists(path): path = os.path.join("/home", "backup", backupFile) elif os.path.exists(data['backupFile']): path = data['backupFile'].strip(".tar.gz") else: dir = data['dir'] path = "/home/backup/transfer-" + str(dir) + "/" + backupFile if os.path.exists(path): try: execPath = "sudo cat " + path + "/status" status = ProcessUtilities.outputExecutioner(execPath) if status.find("Done") > -1: command = "sudo rm -rf " + path ProcessUtilities.executioner(command) final_json = json.dumps( {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 1, 'running': 'Completed'}) return HttpResponse(final_json) elif status.find("[5009]") > -1: ## removing temporarily generated files while restoring command = "sudo rm -rf " + path ProcessUtilities.executioner(command) final_json = json.dumps({'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 1, 'alreadyRunning': 0, 'running': 'Error'}) return HttpResponse(final_json) else: final_json = json.dumps( {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 0, 'running': 'Running..'}) return HttpResponse(final_json) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) status = "Just Started" final_json = json.dumps( {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 0, 'running': 'Running..'}) return HttpResponse(final_json) else:
def FetchRemoteTransferStatus(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 = { "fetchStatus": 0, 'error_message': "API Access Disabled." } json_data = json.dumps(data_ret) return HttpResponse(json_data) dir = "/home/backup/transfer-" + str(data['dir']) + "/backup_log" try: command = "cat " + dir status = ProcessUtilities.outputExecutioner(command) if hashPassword.check_password(admin.password, password): final_json = json.dumps({ 'fetchStatus': 1, 'error_message': "None", "status": status }) return HttpResponse(final_json) else: data_ret = { 'fetchStatus': 0, 'error_message': "Invalid Credentials" } json_data = json.dumps(data_ret) return HttpResponse(json_data) except: final_json = json.dumps({ 'fetchStatus': 1, 'error_message': "None", "status": "Just started.." }) return HttpResponse(final_json) except BaseException, msg: data = {'fetchStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data) return HttpResponse(json_data)
def switchTOLSWSStatus(request): try: command = 'sudo cat ' + serverStatusUtil.ServerStatusUtil.lswsInstallStatusPath output = ProcessUtilities.outputExecutioner(command) if output.find('[404]') > -1: command = "sudo rm -f " + serverStatusUtil.ServerStatusUtil.lswsInstallStatusPath ProcessUtilities.popenExecutioner(command) data_ret = { 'status': 1, 'abort': 1, 'requestStatus': output, 'installed': 0 } json_data = json.dumps(data_ret) return HttpResponse(json_data) elif output.find('[200]') > -1: command = "sudo rm -f " + serverStatusUtil.ServerStatusUtil.lswsInstallStatusPath ProcessUtilities.popenExecutioner(command) data_ret = { 'status': 1, 'abort': 1, 'requestStatus': output, 'installed': 1 } json_data = json.dumps(data_ret) return HttpResponse(json_data) else: data_ret = { 'status': 1, 'abort': 0, 'requestStatus': output, 'installed': 0 } json_data = json.dumps(data_ret) return HttpResponse(json_data) except BaseException, msg: command = "sudo rm -f " + serverStatusUtil.ServerStatusUtil.lswsInstallStatusPath ProcessUtilities.popenExecutioner(command) data_ret = { 'status': 0, 'abort': 1, 'requestStatus': str(msg), 'installed': 0 } json_data = json.dumps(data_ret) return HttpResponse(json_data)
def listForTable(self): try: finalData = {} finalData['status'] = 1 domainName = self.data['domainName'] website = Websites.objects.get(domain=domainName) if not self.data['completeStartingPath'].find( self.data['home']) > -1: return self.ajaxPre( 0, 'Not allowed to browse this path, going back home!') command = "ls -la --group-directories-first " + self.returnPathEnclosed( self.data['completeStartingPath']) output = ProcessUtilities.outputExecutioner( command, website.externalApp).splitlines() counter = 0 for items in output: try: currentFile = items.split(' ') currentFile = filter(lambda a: a != '', currentFile) if currentFile[-1] == '.' or currentFile[ -1] == '..' or currentFile[0] == 'total': continue if len(currentFile) > 9: fileName = currentFile[8:] currentFile[-1] = " ".join(fileName) dirCheck = 0 if currentFile[0][0] == 'd': dirCheck = 1 size = str(int(int(currentFile[4]) / float(1024))) lastModified = currentFile[5] + ' ' + currentFile[ 6] + ' ' + currentFile[7] finalData[str(counter)] = [ currentFile[-1], currentFile[-1], lastModified, size, currentFile[0], dirCheck ] counter = counter + 1 except BaseException, msg: logging.writeToFile(str(msg)) json_data = json.dumps(finalData) return HttpResponse(json_data)
def cancelRemoteTransfer(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 = { "cancelStatus": 0, 'error_message': "API Access Disabled." } json_data = json.dumps(data_ret) return HttpResponse(json_data) dir = "/home/backup/transfer-" + str(data['dir']) if hashPassword.check_password(admin.password, password): path = dir + "/pid" command = "cat " + path pid = ProcessUtilities.outputExecutioner(command) command = "kill -KILL " + pid ProcessUtilities.executioner(command) command = "rm -rf " + dir ProcessUtilities.executioner(command) data = {'cancelStatus': 1, 'error_message': "None"} json_data = json.dumps(data) return HttpResponse(json_data) else: data_ret = { 'cancelStatus': 0, 'error_message': "Invalid Credentials" } json_data = json.dumps(data_ret) return HttpResponse(json_data) except BaseException, msg: data = {'cancelStatus': 1, 'error_message': str(msg)} json_data = json.dumps(data) return HttpResponse(json_data)
def savePolicyServerStatus(request): try: userID = request.session['userID'] currentACL = ACLManager.loadedACL(userID) if currentACL['admin'] == 1: pass else: return ACLManager.loadErrorJson() try: if request.method == 'POST': data = json.loads(request.body) policServerStatus = data['policServerStatus'] install = '0' if policServerStatus == True: install = "1" ## save configuration data execPath = "/usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" execPath = execPath + " savePolicyServerStatus --install " + install output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'status': 1, 'error_message': "None"} json_data = json.dumps(data_ret) return HttpResponse(json_data) else: data_ret = {'status': 0, 'error_message': output} 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) except KeyError,msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) data_ret = {'status': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) return HttpResponse(json_data)
def readFileContents(self): try: finalData = {} finalData['status'] = 1 domainName = self.data['domainName'] website = Websites.objects.get(domain=domainName) command = 'cat ' + self.returnPathEnclosed(self.data['fileName']) finalData['fileContents'] = ProcessUtilities.outputExecutioner( command, website.externalApp) json_data = json.dumps(finalData) return HttpResponse(json_data) except BaseException, msg: return self.ajaxPre(0, str(msg))