diff --git a/CyberCP/settings.py b/CyberCP/settings.py index 4412d01a1..6892a9d23 100644 --- a/CyberCP/settings.py +++ b/CyberCP/settings.py @@ -28,9 +28,6 @@ DEBUG = False ALLOWED_HOSTS = ['*'] - - - # Application definition INSTALLED_APPS = [ diff --git a/api/views.py b/api/views.py index ac7357a90..74bef9a0a 100644 --- a/api/views.py +++ b/api/views.py @@ -12,8 +12,6 @@ from random import randint from websiteFunctions.models import Websites import os from baseTemplate.models import version -import subprocess -import shlex from plogical.mailUtilities import mailUtilities from plogical.website import WebsiteManager from loginSystem.models import ACL @@ -121,6 +119,8 @@ def changeUserPassAPI(request): websiteOwn.password = hashPassword.hash_password(ownerPassword) websiteOwn.save() + + data_ret = {'changeStatus': 1, 'error_message': "None"} json_data = json.dumps(data_ret) return HttpResponse(json_data) @@ -380,8 +380,8 @@ def FetchRemoteTransferStatus(request): dir = "/home/backup/transfer-"+str(data['dir'])+"/backup_log" try: - execPath = "sudo cat "+ dir - status = ProcessUtilities.outputExecutioner(execPath) + command = "sudo cat "+ dir + status = ProcessUtilities.outputExecutioner(command) admin = Administrator.objects.get(userName=username) if hashPassword.check_password(admin.password, password): @@ -417,14 +417,14 @@ def cancelRemoteTransfer(request): path = dir + "/pid" - execPath = "sudo cat " + path - pid = ProcessUtilities.outputExecutioner(execPath) + command = "sudo cat " + path + pid = ProcessUtilities.outputExecutioner(command) - execPath = "sudo kill -KILL " + pid - ProcessUtilities.executioner(execPath) + command = "sudo kill -KILL " + pid + ProcessUtilities.executioner(command) - execPath = "sudo rm -rf " + dir - ProcessUtilities.executioner(execPath) + command = "sudo rm -rf " + dir + ProcessUtilities.executioner(command) data = {'cancelStatus': 1, 'error_message': "None"} json_data = json.dumps(data) @@ -524,8 +524,8 @@ def putSSHkey(request): ## - execPath = "sudo chmod g-w /home/cyberpanel" - ProcessUtilities.executioner(execPath) + command = "sudo chmod g-w /home/cyberpanel" + ProcessUtilities.executioner(command) os.chmod(keyPath,0700) os.chmod(authorized_keys, 0600) @@ -588,6 +588,30 @@ def changeAdminPassword(request): newFWRule = FirewallRules(name="ftp", proto="tcp", port="21") newFWRule.save() + newFWRule = FirewallRules(name="smtp", proto="tcp", port="25") + newFWRule.save() + + newFWRule = FirewallRules(name="smtps", proto="tcp", port="587") + newFWRule.save() + + newFWRule = FirewallRules(name="ssmtp", proto="tcp", port="465") + newFWRule.save() + + newFWRule = FirewallRules(name="pop3", proto="tcp", port="110") + newFWRule.save() + + newFWRule = FirewallRules(name="imap", proto="tcp", port="143") + newFWRule.save() + + newFWRule = FirewallRules(name="simap", proto="tcp", port="993") + newFWRule.save() + + newFWRule = FirewallRules(name="dns", proto="udp", port="53") + newFWRule.save() + + newFWRule = FirewallRules(name="dnstcp", proto="tcp", port="53") + newFWRule.save() + newFWRule = FirewallRules(name="ftptls", proto="tcp", port="40110-40210") newFWRule.save() diff --git a/backup/backupManager.py b/backup/backupManager.py index 31b515c42..54a6f32dc 100644 --- a/backup/backupManager.py +++ b/backup/backupManager.py @@ -62,7 +62,7 @@ class BackupManager: ext = ".tar.gz" command = 'sudo chown -R cyberpanel:cyberpanel ' + path - ProcessUtilities.executioner(command) + ACLManager.executeCall(command) files = os.listdir(path) for filename in files: @@ -169,16 +169,16 @@ class BackupManager: ## read file name try: - execPath = "sudo cat " + backupFileNamePath - fileName = ProcessUtilities.outputExecutioner(execPath) + command = "sudo cat " + backupFileNamePath + fileName = subprocess.check_output(shlex.split(command)) except: fileName = "Fetching.." ## file name read ends if os.path.exists(status): - execPath = "sudo cat " + status - status = ProcessUtilities.outputExecutioner(execPath) + command = "sudo cat " + status + status = subprocess.check_output(shlex.split(command)) if status.find("Completed") > -1: @@ -202,14 +202,14 @@ class BackupManager: ### Removing Files - execPath = 'sudo rm -f ' + status - ProcessUtilities.executioner(execPath) + command = 'sudo rm -f ' + status + subprocess.call(shlex.split(command)) - execPath = 'sudo rm -f ' + backupFileNamePath - ProcessUtilities.executioner(execPath) + command = 'sudo rm -f ' + backupFileNamePath + subprocess.call(shlex.split(command)) - execPath = 'sudo rm -f ' + pid - ProcessUtilities.executioner(execPath) + command = 'sudo rm -f ' + pid + subprocess.call(shlex.split(command)) final_json = json.dumps( {'backupStatus': 1, 'error_message': "None", "status": status, "abort": 1, @@ -219,14 +219,14 @@ class BackupManager: elif status.find("[5009]") > -1: ## removing status file, so that backup can re-run try: - execPath = 'sudo rm -f ' + status - ProcessUtilities.executioner(execPath) + command = 'sudo rm -f ' + status + subprocess.call(shlex.split(command)) - execPath = 'sudo rm -f ' + backupFileNamePath - ProcessUtilities.executioner(execPath) + command = 'sudo rm -f ' + backupFileNamePath + subprocess.call(shlex.split(command)) - execPath = 'sudo rm -f ' + pid - ProcessUtilities.executioner(execPath) + command = 'sudo rm -f ' + pid + subprocess.call(shlex.split(command)) backupObs = Backups.objects.filter(fileName=fileName) for items in backupObs: @@ -261,9 +261,10 @@ class BackupManager: fileName = data['fileName'] execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" + execPath = execPath + " cancelBackupCreation --backupCancellationDomain " + backupCancellationDomain + " --fileName " + fileName - ProcessUtilities.executioner(execPath) + subprocess.call(shlex.split(execPath)) try: backupOb = Backups.objects.get(fileName=fileName) @@ -287,8 +288,8 @@ class BackupManager: domainName = backup.website.domain path = "/home/" + domainName + "/backup/" + backup.fileName + ".tar.gz" - execPath = 'sudo rm -f ' + path - ProcessUtilities.executioner(execPath) + command = 'sudo rm -f ' + path + ACLManager.executeCall(command) backup.delete() @@ -340,12 +341,12 @@ class BackupManager: if os.path.exists(path): try: execPath = "sudo cat " + path + "/status" - status = ProcessUtilities.outputExecutioner(execPath) + status = subprocess.check_output(shlex.split(execPath)) if status.find("Done") > -1: - execPath = "sudo rm -rf " + path - ProcessUtilities.executioner(execPath) + command = "sudo rm -rf " + path + subprocess.call(shlex.split(command)) final_json = json.dumps( {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 1, @@ -353,8 +354,8 @@ class BackupManager: return HttpResponse(final_json) elif status.find("[5009]") > -1: ## removing temporarily generated files while restoring - execPath = "sudo rm -rf " + path - ProcessUtilities.executioner(execPath) + command = "sudo rm -rf " + path + subprocess.call(shlex.split(command)) final_json = json.dumps({'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 1, 'alreadyRunning': 0, 'running': 'Error'}) @@ -506,7 +507,7 @@ class BackupManager: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" execPath = execPath + " getConnectionStatus --ipAddress " + ipAddress - output = ProcessUtilities.outputExecutioner(execPath) + output = subprocess.check_output(shlex.split(execPath)) if output.find('1,') > -1: final_dic = {'connStatus': 1, 'error_message': "None"} @@ -648,6 +649,7 @@ class BackupManager: ## check if already exists try: schedule = backupSchedules.objects.get(frequency=backupFreq) + if schedule.dest.destLoc == backupDest: final_json = json.dumps( {'scheduleStatus': 0, 'error_message': "This schedule already exists"}) @@ -655,175 +657,68 @@ class BackupManager: else: if backupDest == "Home" and backupFreq == "Daily": cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py" - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - execPath = "sudo systemctl restart crond" - ProcessUtilities.executioner(execPath) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - elif backupDest == "Home" and backupFreq == "Weekly": cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py " - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - execPath = "sudo systemctl restart crond" - - ProcessUtilities.executioner(execPath) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - elif backupDest != "Home" and backupFreq == "Daily": cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py" - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - execPath = "sudo systemctl restart crond" - - ProcessUtilities.executioner(execPath) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - elif backupDest != "Home" and backupFreq == "Weekly": cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupSchedule.py " - virtualHostUtilities.permissionControl(path) + command = "cat " + path + output = ProcessUtilities.outputExecutioner(command) - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() + finalCronJob = output + cronJob + tempCronPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - virtualHostUtilities.leaveControl(path) + writeToFile = open(tempCronPath, 'a') + writeToFile.writelines(finalCronJob + "\n") + writeToFile.close() - execPath = "sudo systemctl restart crond" - ProcessUtilities.executioner(execPath) + command = "sudo mv " + tempCronPath + " " + path + ProcessUtilities.executioner(command) - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() + command = "sudo systemctl restart crond" + ProcessUtilities.executioner(command) - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() + + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) except: if backupDest == "Home" and backupFreq == "Daily": cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py" - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - execPath = "sudo systemctl restart crond" - ProcessUtilities.executioner(execPath) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - elif backupDest == "Home" and backupFreq == "Weekly": - cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py " - - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - execPath = "sudo systemctl restart crond" - ProcessUtilities.executioner(execPath) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - + cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py" elif backupDest != "Home" and backupFreq == "Daily": cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py" - virtualHostUtilities.permissionControl(path) - - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - execPath = "sudo systemctl restart crond" - - ProcessUtilities.executioner(execPath) - - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() - - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) - elif backupDest != "Home" and backupFreq == "Weekly": - cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupSchedule.py " + cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupSchedule.py" - virtualHostUtilities.permissionControl(path) + command = "cat " + path + output = ProcessUtilities.outputExecutioner(command) - writeToFile = open(path, 'a') - writeToFile.writelines(cronJob + "\n") - writeToFile.close() + finalCronJob = output + cronJob + tempCronPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - virtualHostUtilities.leaveControl(path) + writeToFile = open(tempCronPath, 'a') + writeToFile.writelines(finalCronJob + "\n") + writeToFile.close() - execPath = "sudo systemctl restart crond" + command = "sudo mv " + tempCronPath + " " + path + ProcessUtilities.executioner(command) - ProcessUtilities.executioner(execPath) + command = "sudo systemctl restart crond" + ProcessUtilities.executioner(command) - destination = dest.objects.get(destLoc=backupDest) - newSchedule = backupSchedules(dest=destination, frequency=backupFreq) - newSchedule.save() + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() - final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) - return HttpResponse(final_json) + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) except BaseException, msg: final_json = json.dumps({'scheduleStatus': 0, 'error_message': str(msg)}) @@ -838,120 +733,48 @@ class BackupManager: backupDest = data['destLoc'] backupFreq = data['frequency'] + findTxt = "" + + if backupDest == "Home" and backupFreq == "Daily": + findTxt = "0-6" + elif backupDest == "Home" and backupFreq == "Weekly": + findTxt = "* 3" + elif backupDest != "Home" and backupFreq == "Daily": + findTxt = "0-6" + elif backupDest != "Home" and backupFreq == "Weekly": + findTxt = "* 3" + + ### path = "/etc/crontab" - if backupDest == "Home" and backupFreq == "Daily": + command = "cat " + path + output = ProcessUtilities.outputExecutioner(command).split('\n') + tempCronPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - virtualHostUtilities.permissionControl(path) + writeToFile = open(tempCronPath, 'w') - data = open(path, "r").readlines() - writeToFile = open(path, 'w') + for items in output: + if items.find(findTxt) > -1 and items.find("backupScheduleLocal.py") > -1: + continue + else: + writeToFile.writelines(items + '\n') - for items in data: - if items.find("0-6") > -1 and items.find("backupScheduleLocal.py") > -1: - continue - else: - writeToFile.writelines(items) + writeToFile.close() - writeToFile.close() + command = "sudo mv " + tempCronPath + " " + path + ProcessUtilities.executioner(command) - virtualHostUtilities.leaveControl(path) + command = "sudo systemctl restart crond" - execPath = "sudo systemctl restart crond" + subprocess.call(shlex.split(command)) - ProcessUtilities.executioner(execPath) + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) + newSchedule.delete() - 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) - - elif backupDest == "Home" and backupFreq == "Weekly": - - virtualHostUtilities.permissionControl(path) - - data = open(path, "r").readlines() - writeToFile = open(path, 'w') - - for items in data: - if items.find("* 3") > -1 and items.find("backupScheduleLocal.py") > -1: - continue - else: - writeToFile.writelines(items) - - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - execPath = "sudo systemctl restart crond" - - ProcessUtilities.executioner(execPath) - - 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) - - elif backupDest != "Home" and backupFreq == "Daily": - - virtualHostUtilities.permissionControl(path) - - data = open(path, "r").readlines() - writeToFile = open(path, 'w') - - for items in data: - if items.find("0-6") > -1 and items.find("backupSchedule.py") > -1: - continue - else: - writeToFile.writelines(items) - - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - execPath = "sudo systemctl restart crond" - - ProcessUtilities.executioner(execPath) - - 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) - - elif backupDest != "Home" and backupFreq == "Weekly": - - virtualHostUtilities.permissionControl(path) - - data = open(path, "r").readlines() - writeToFile = open(path, 'w') - - for items in data: - if items.find("* 3") > -1 and items.find("backupSchedule.py") > -1: - continue - else: - writeToFile.writelines(items) - - writeToFile.close() - - virtualHostUtilities.leaveControl(path) - - execPath = "sudo systemctl restart crond" - - ProcessUtilities.executioner(execPath) - - 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) + 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)}) @@ -1125,8 +948,8 @@ class BackupManager: localBackupDir = os.path.join("/home", "backup") if not os.path.exists(localBackupDir): - execPath = "sudo mkdir " + localBackupDir - ProcessUtilities.executioner(execPath) + command = "sudo mkdir " + localBackupDir + subprocess.call(shlex.split(command)) ## create local directory that will host backups @@ -1134,8 +957,8 @@ class BackupManager: ## making local storage directory for backups - execPath = "sudo mkdir " + localStoragePath - ProcessUtilities.executioner(execPath) + command = "sudo mkdir " + localStoragePath + subprocess.call(shlex.split(command)) final_json = json.dumps( {'remoteTransferStatus': 1, 'error_message': "None", "dir": data['dir']}) @@ -1249,18 +1072,18 @@ class BackupManager: time.sleep(3) if os.path.isfile(backupLogPath): - execPath = "sudo cat " + backupLogPath - status = ProcessUtilities.outputExecutioner(execPath) + command = "sudo cat " + backupLogPath + status = ProcessUtilities.outputExecutioner(command) if status.find("completed[success]") > -1: command = "sudo rm -rf " + removalPath - # ProcessUtilities.executioner(shlex.split(command)) + # subprocess.call(shlex.split(command)) data_ret = {'remoteTransferStatus': 1, 'error_message': "None", "status": status, "complete": 1} json_data = json.dumps(data_ret) return HttpResponse(json_data) elif status.find("[5010]") > -1: command = "sudo rm -rf " + removalPath - # ProcessUtilities.executioner(shlex.split(command)) + # subprocess.call(shlex.split(command)) data = {'remoteTransferStatus': 0, 'error_message': status, "status": "None", "complete": 0} json_data = json.dumps(data) @@ -1307,14 +1130,14 @@ class BackupManager: path = "/home/backup/transfer-" + str(dir) pathpid = path + "/pid" - execPath = "sudo cat " + pathpid - pid = ProcessUtilities.outputExecutioner(execPath) + command = "sudo cat " + pathpid + pid = ProcessUtilities.outputExecutioner(command) - execPath = "sudo kill -KILL " + pid - ProcessUtilities.executioner(execPath) + command = "sudo kill -KILL " + pid + ProcessUtilities.executioner(command) - execPath = "sudo rm -rf " + path - ProcessUtilities.executioner(execPath) + command = "sudo rm -rf " + path + ProcessUtilities.executioner(command) data = {'cancelStatus': 1, 'error_message': "None"} json_data = json.dumps(data) diff --git a/baseTemplate/views.py b/baseTemplate/views.py index 17ca6412f..94731496c 100644 --- a/baseTemplate/views.py +++ b/baseTemplate/views.py @@ -15,7 +15,6 @@ import shlex import os import plogical.CyberCPLogFileWriter as logging from plogical.acl import ACLManager -from plogical.processUtilities import ProcessUtilities # Create your views here. @@ -111,7 +110,7 @@ def upgrade(request): cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) vers = version.objects.get(pk=1) diff --git a/cli/cliLogger.py b/cli/cliLogger.py index 8011853c4..878f5527a 100644 --- a/cli/cliLogger.py +++ b/cli/cliLogger.py @@ -1,6 +1,6 @@ import subprocess import time -from plogical.processUtilities import ProcessUtilities + class cliLogger: fileName = "/home/cyberpanel/error-logs.txt" @@ -20,7 +20,7 @@ class cliLogger: def readLastNFiles(numberOfLines,fileName): try: - lastFewLines = ProcessUtilities.outputExecutioner(["tail", "-n",str(numberOfLines),fileName]) + lastFewLines = subprocess.check_output(["tail", "-n",str(numberOfLines),fileName]) return lastFewLines diff --git a/cloudAPI/cloudManager.py b/cloudAPI/cloudManager.py index 94349d58d..bfc5ebdb0 100644 --- a/cloudAPI/cloudManager.py +++ b/cloudAPI/cloudManager.py @@ -1,7 +1,5 @@ import json import os -import shlex -import subprocess from random import randint from django.shortcuts import HttpResponse @@ -319,8 +317,8 @@ class CloudManager: lastLine = statusData[-1] if lastLine.find('[200]') > -1: - execPath = 'sudo rm -f ' + statusFile - ProcessUtilities.outputExecutioner(execPath) + command = 'sudo rm -f ' + statusFile + ProcessUtilities.executioner(command) data_ret = {'status': 1, 'abort': 1, 'installationProgress': "100", 'currentStatus': lastLine} json_data = json.dumps(data_ret) return HttpResponse(json_data) @@ -1053,11 +1051,9 @@ class CloudManager: if ProcessUtilities.decideDistro() == ProcessUtilities.centos: - execPath = 'sudo cat /etc/my.cnf' - finalData['conf'] = ProcessUtilities.outputExecutioner(execPath) + finalData['conf'] = ProcessUtilities.outputExecutioner('sudo cat /etc/my.cnf') else: - execPath = 'sudo cat /etc/mysql/my.cnf' - finalData['conf'] = ProcessUtilities.outputExecutioner(execPath) + finalData['conf'] = ProcessUtilities.outputExecutioner('sudo cat /etc/mysql/my.cnf') finalData['status'] = 1 diff --git a/containerization/container.py b/containerization/container.py index f4186b2b1..63bbc2242 100755 --- a/containerization/container.py +++ b/containerization/container.py @@ -1,17 +1,11 @@ #!/usr/local/CyberCP/bin/python2 -import os -import os.path import sys -import django sys.path.append('/usr/local/CyberCP') -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") -#django.setup() import plogical.CyberCPLogFileWriter as logging import argparse -import subprocess -import shlex -from plogical.processUtilities import ProcessUtilities -from xml.etree import ElementTree +from plogical.mailUtilities import mailUtilities +from serverStatus.serverStatusUtil import ServerStatusUtil + class Container: packages = ['talksho'] @@ -71,11 +65,38 @@ class Container: except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) + @staticmethod + def submitContainerInstall(): + try: + + mailUtilities.checkHome() + + statusFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w') + + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + "Starting Packages Installation..\n", 1) + + command = 'sudo yum install -y libcgroup-tools' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo systemctl enable cgconfig' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo systemctl enable cgred' + ServerStatusUtil.executioner(command, statusFile) + + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + "Packages successfully installed.[200]\n", 1) + + except BaseException, msg: + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) + def main(): parser = argparse.ArgumentParser(description='CyberPanel Container Manager') parser.add_argument('--userid', help='User ID') parser.add_argument('--package', help='Package') + parser.add_argument('--function', help='Function') parser.add_argument('--list-all', help='List all users/packages.', action='store_true') parser.add_argument('--list-packages', help='List all packages.', action='store_true') @@ -90,6 +111,11 @@ def main(): Container.listAll() elif args['list_packages']: Container.listPackages() + elif args['list_packages']: + Container.listPackages() + elif args["function"] == "submitContainerInstall": + Container.submitContainerInstall() + diff --git a/containerization/containerManager.py b/containerization/containerManager.py index bfff8322c..c2e004a76 100644 --- a/containerization/containerManager.py +++ b/containerization/containerManager.py @@ -2,10 +2,10 @@ from django.shortcuts import render from plogical.processUtilities import ProcessUtilities import threading as multi from plogical.acl import ACLManager -from plogical.mailUtilities import mailUtilities import plogical.CyberCPLogFileWriter as logging from serverStatus.serverStatusUtil import ServerStatusUtil import os, stat +from plogical.virtualHostUtilities import virtualHostUtilities class ContainerManager(multi.Thread): @@ -125,24 +125,9 @@ class ContainerManager(multi.Thread): 1) return 0 - mailUtilities.checkHome() - - statusFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w') - - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, - "Starting Packages Installation..\n", 1) - - command = 'sudo yum install -y libcgroup-tools' - ServerStatusUtil.executioner(command, statusFile) - - command = 'sudo systemctl enable cgconfig' - ServerStatusUtil.executioner(command, statusFile) - - command = 'sudo systemctl enable cgred' - ServerStatusUtil.executioner(command, statusFile) - - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, - "Packages successfully installed.[200]\n", 1) + execPath = "sudo python /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) diff --git a/containerization/views.py b/containerization/views.py index 4e0c8dac5..be31c7925 100644 --- a/containerization/views.py +++ b/containerization/views.py @@ -162,7 +162,7 @@ def saveWebsiteLimits(request): cgrules = '/etc/cgrules.conf' enforceString = '{} cpu,memory,blkio,net_cls {}/\n'.format(website.externalApp, website.externalApp) - cgrulesData = ProcessUtilities.outputExecutioner(shlex.split('sudo cat /etc/cgrules.conf')).splitlines() + cgrulesData = ProcessUtilities.outputExecutioner('sudo cat /etc/cgrules.conf').splitlines() writeToFile = open(cgrulesTemp, 'w') @@ -219,7 +219,7 @@ def saveWebsiteLimits(request): cgrulesTemp = "/home/cyberpanel/" + str(randint(1000, 9999)) cgrules = '/etc/cgrules.conf' - cgrulesData = ProcessUtilities.outputExecutioner(shlex.split('sudo cat /etc/cgrules.conf')).splitlines() + cgrulesData = ProcessUtilities.outputExecutioner('sudo cat /etc/cgrules.conf').splitlines() writeToFile = open(cgrulesTemp, 'w') @@ -293,7 +293,7 @@ def getUsageData(request): if type == 'memory': command = 'sudo cat /sys/fs/cgroup/memory/' + website.externalApp + '/memory.usage_in_bytes' - output = str(ProcessUtilities.outputExecutioner(command, shell=True)) + output = str(ProcessUtilities.outputExecutioner(command)) finalData['memory'] = int(float(output)/float(1024 * 1024)) elif type == 'io': @@ -305,7 +305,7 @@ def getUsageData(request): os.mkdir(path) command = 'sudo cat /sys/fs/cgroup/blkio/' + website.externalApp + '/blkio.throttle.io_service_bytes' - output = ProcessUtilities.outputExecutioner(command, shell=True).splitlines() + output = ProcessUtilities.outputExecutioner(command).splitlines() readCurrent = output[0].split(' ')[2] writeCurrent = output[1].split(' ')[2] @@ -332,8 +332,8 @@ def getUsageData(request): finalData['readRate'] = 0 finalData['writeRate'] = 0 except: - command = "sudo top -b -n 1 -u " + website.externalApp + " | awk 'NR>7 { sum += $9; } END { print sum; }'" - output = str(ProcessUtilities.outputExecutioner(command, shell=True)) + command = "top -b -n 1 -u " + website.externalApp + " | awk 'NR>7 { sum += $9; } END { print sum; }'" + output = str(subprocess.check_output(command, shell=True)) finalData = {} if len(output) == 0: diff --git a/databases/databaseManager.py b/databases/databaseManager.py index 1ed242cf4..ac2469cbb 100644 --- a/databases/databaseManager.py +++ b/databases/databaseManager.py @@ -9,12 +9,13 @@ from django.shortcuts import render, redirect from django.http import HttpResponse import json from plogical.acl import ACLManager -import subprocess, shlex import plogical.CyberCPLogFileWriter as logging from plogical.mysqlUtilities import mysqlUtilities from websiteFunctions.models import Websites from databases.models import Databases -from plogical.processUtilities import ProcessUtilities +import argparse +from loginSystem.models import Administrator +import plogical.randomPassword as randomPassword class DatabaseManager: @@ -24,6 +25,12 @@ class DatabaseManager: except BaseException, msg: return HttpResponse(str(msg)) + def phpMyAdmin(self, request = None, userID = None): + try: + return render(request, 'databases/phpMyAdmin.html') + except BaseException, msg: + return HttpResponse(str(msg)) + def createDatabase(self, request = None, userID = None): try: currentACL = ACLManager.loadedACL(userID) @@ -165,19 +172,10 @@ class DatabaseManager: userName = data['dbUserName'] dbPassword = data['dbPassword'] - passFile = "/etc/cyberpanel/mysqlPassword" - f = open(passFile) - data = f.read() - password = data.split('\n', 1)[0] + res = mysqlUtilities.changePassword(userName, dbPassword) - passwordCMD = "use mysql;SET PASSWORD FOR '" + userName + "'@'localhost' = PASSWORD('" + dbPassword + "');FLUSH PRIVILEGES;" - - command = 'sudo mysql -u root -p' + password + ' -e "' + passwordCMD + '"' - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) - - if res == 1: + if res == 0: data_ret = {'status': 0, 'changePasswordStatus': 0,'error_message': "Please see CyberPanel main log file."} json_data = json.dumps(data_ret) return HttpResponse(json_data) @@ -189,4 +187,49 @@ class DatabaseManager: except BaseException, msg: data_ret = {'status': 0, 'changePasswordStatus': 0, 'error_message': str(msg)} json_data = json.dumps(data_ret) - return HttpResponse(json_data) \ No newline at end of file + return HttpResponse(json_data) + + @staticmethod + def generatePHPMYAdminData(userID): + try: + + admin = Administrator.objects.get(id=userID) + path = '/etc/cyberpanel/' + admin.userName + + + currentACL = ACLManager.loadedACL(userID) + websiteOBJs = ACLManager.findWebsiteObjects(currentACL, userID) + finalUserPassword = randomPassword.generate_pass() + + writeToFile = open(path, 'w') + writeToFile.write(finalUserPassword) + writeToFile.close() + + mysqlUtilities.createDBUser(admin.userName, finalUserPassword) + mysqlUtilities.changePassword(admin.userName, finalUserPassword) + + for webs in websiteOBJs: + for db in webs.databases_set.all(): + mysqlUtilities.allowGlobalUserAccess(admin.userName, db.dbName) + + print "1," + finalUserPassword + + except BaseException, msg: + print "0," + str(msg) + +def main(): + + parser = argparse.ArgumentParser(description='CyberPanel Installer') + parser.add_argument('function', help='Specific a function to call!') + + parser.add_argument('--userID', help='Logged in user ID') + + + args = parser.parse_args() + + if args.function == "generatePHPMYAdminData": + DatabaseManager.generatePHPMYAdminData(int(args.userID)) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/databases/static/databases/databases.js b/databases/static/databases/databases.js index 22f246d91..e13d25977 100644 --- a/databases/static/databases/databases.js +++ b/databases/static/databases/databases.js @@ -4,7 +4,7 @@ /* Java script code to create database */ -app.controller('createDatabase', function($scope,$http) { +app.controller('createDatabase', function ($scope, $http) { $scope.createDatabaseLoading = true; $scope.dbDetails = true; @@ -14,103 +14,99 @@ app.controller('createDatabase', function($scope,$http) { $scope.generatedPasswordView = true; - $scope.showDetailsBoxes = function(){ + $scope.showDetailsBoxes = function () { $scope.dbDetails = false; }; - $scope.createDatabase = function(){ + $scope.createDatabase = function () { - $scope.createDatabaseLoading = false; + $scope.createDatabaseLoading = false; + $scope.dbDetails = false; + $scope.databaseCreationFailed = true; + $scope.databaseCreated = true; + $scope.couldNotConnect = true; + + + var databaseWebsite = $scope.databaseWebsite; + var dbName = $scope.dbName; + var dbUsername = $scope.dbUsername; + var dbPassword = $scope.dbPassword; + var webUserName = ""; + + // getting website username + + webUserName = databaseWebsite.replace(/-/g, ''); + webUserName = webUserName.split(".")[0]; + + if (webUserName.length > 5) { + webUserName = webUserName.substring(0, 4); + } + + var url = "/dataBases/submitDBCreation"; + + + var data = { + webUserName: webUserName, + databaseWebsite: databaseWebsite, + dbName: dbName, + dbUsername: dbUsername, + dbPassword: dbPassword + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.createDBStatus == 1) { + + $scope.createDatabaseLoading = true; $scope.dbDetails = false; $scope.databaseCreationFailed = true; - $scope.databaseCreated = true; + $scope.databaseCreated = false; $scope.couldNotConnect = true; - var databaseWebsite = $scope.databaseWebsite; - var dbName = $scope.dbName; - var dbUsername = $scope.dbUsername; - var dbPassword = $scope.dbPassword; - var webUserName = ""; + } - // getting website username - - webUserName = databaseWebsite.replace(/-/g, ''); - webUserName = webUserName.split(".")[0]; - - if(webUserName.length > 5){ - webUserName = webUserName.substring(0,4); - } - - var url = "/dataBases/submitDBCreation"; + else { - var data = { - webUserName:webUserName, - databaseWebsite:databaseWebsite, - dbName:dbName, - dbUsername:dbUsername, - dbPassword:dbPassword - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $scope.createDatabaseLoading = true; + $scope.dbDetails = false; + $scope.databaseCreationFailed = false; + $scope.databaseCreated = true; + $scope.couldNotConnect = true; + $scope.errorMessage = response.data.error_message; - function ListInitialDatas(response) { + } - if(response.data.createDBStatus == 1){ - - $scope.createDatabaseLoading = true; - $scope.dbDetails = false; - $scope.databaseCreationFailed = true; - $scope.databaseCreated = false; - $scope.couldNotConnect = true; - - - } - - else - { - - - $scope.createDatabaseLoading = true; - $scope.dbDetails = false; - $scope.databaseCreationFailed = false; - $scope.databaseCreated = true; - $scope.couldNotConnect = true; - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.createDatabaseLoading = true; - $scope.dbDetails = true; - $scope.databaseCreationFailed = true; - $scope.databaseCreated = true; - $scope.couldNotConnect = false; - } - + } + function cantLoadInitialDatas(response) { + $scope.createDatabaseLoading = true; + $scope.dbDetails = true; + $scope.databaseCreationFailed = true; + $scope.databaseCreated = true; + $scope.couldNotConnect = false; + } }; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.dbPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.dbPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -122,7 +118,7 @@ app.controller('createDatabase', function($scope,$http) { /* Java script code to delete database */ -app.controller('deleteDatabase', function($scope,$http) { +app.controller('deleteDatabase', function ($scope, $http) { $scope.deleteDatabaseLoading = true; $scope.fetchedDatabases = true; @@ -131,153 +127,147 @@ app.controller('deleteDatabase', function($scope,$http) { $scope.couldNotConnect = true; - $scope.fetchDatabases = function(){ + $scope.fetchDatabases = function () { - $scope.deleteDatabaseLoading = false; - $scope.fetchedDatabases = true; + $scope.deleteDatabaseLoading = false; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = true; + $scope.couldNotConnect = true; + + + var databaseWebsite = $scope.databaseWebsite; + + var url = "/dataBases/fetchDatabases"; + + + var data = { + databaseWebsite: databaseWebsite, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.fetchStatus == 1) { + + + $scope.dbnames = JSON.parse(response.data.data); + + + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = false; $scope.databaseDeletionFailed = true; $scope.databaseDeleted = true; $scope.couldNotConnect = true; - var databaseWebsite = $scope.databaseWebsite; + } - var url = "/dataBases/fetchDatabases"; + else { + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = false; + $scope.databaseDeleted = true; + $scope.couldNotConnect = true; - var data = { - databaseWebsite:databaseWebsite, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $scope.errorMessage = response.data.error_message; - function ListInitialDatas(response) { + } - if(response.data.fetchStatus == 1){ + } + + function cantLoadInitialDatas(response) { + + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = true; + $scope.couldNotConnect = false; - $scope.dbnames = JSON.parse(response.data.data); - - - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = false; - $scope.databaseDeletionFailed = true; - $scope.databaseDeleted = true; - $scope.couldNotConnect = true; - - - - } - - else - { - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = true; - $scope.databaseDeletionFailed = false; - $scope.databaseDeleted = true; - $scope.couldNotConnect = true; - - - - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = true; - $scope.databaseDeletionFailed = true; - $scope.databaseDeleted = true; - $scope.couldNotConnect = false; - - - } + } }; - $scope.deleteDatabase = function(){ + $scope.deleteDatabase = function () { - $scope.deleteDatabaseLoading = false; - $scope.fetchedDatabases = true; + $scope.deleteDatabaseLoading = false; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = true; + $scope.couldNotConnect = true; + + + var databaseWebsite = $scope.databaseWebsite; + + var url = "/dataBases/submitDatabaseDeletion"; + + + var data = { + dbName: $scope.selectedDB, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.deleteStatus == 1) { + + + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = false; $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = false; + $scope.couldNotConnect = true; + + + } + + else { + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = false; $scope.databaseDeleted = true; $scope.couldNotConnect = true; - var databaseWebsite = $scope.databaseWebsite; - - var url = "/dataBases/submitDatabaseDeletion"; + $scope.errorMessage = response.data.error_message; - var data = { - dbName:$scope.selectedDB, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + } - function ListInitialDatas(response) { + } + + function cantLoadInitialDatas(response) { + + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = true; + $scope.couldNotConnect = false; - if(response.data.deleteStatus == 1){ - - - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = false; - $scope.databaseDeletionFailed = true; - $scope.databaseDeleted = false; - $scope.couldNotConnect = true; - - - - } - - else - { - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = true; - $scope.databaseDeletionFailed = false; - $scope.databaseDeleted = true; - $scope.couldNotConnect = true; - - - - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = true; - $scope.databaseDeletionFailed = true; - $scope.databaseDeleted = true; - $scope.couldNotConnect = false; - - - } + } }; @@ -289,7 +279,7 @@ app.controller('deleteDatabase', function($scope,$http) { /* Java script code to list databases */ -app.controller('listDBs', function($scope,$http) { +app.controller('listDBs', function ($scope, $http) { $scope.recordsFetched = true; $scope.passwordChanged = true; @@ -303,161 +293,161 @@ app.controller('listDBs', function($scope,$http) { var globalDBUsername = ""; $scope.fetchDBs = function () { - populateCurrentRecords(); + populateCurrentRecords(); }; $scope.changePassword = function (dbUsername) { - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.dbLoading = true; - $scope.dbAccounts = false; - $scope.changePasswordBox = false; - $scope.notificationsBox = true; - $scope.dbUsername = dbUsername; + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.dbLoading = true; + $scope.dbAccounts = false; + $scope.changePasswordBox = false; + $scope.notificationsBox = true; + $scope.dbUsername = dbUsername; - globalDBUsername = dbUsername; + globalDBUsername = dbUsername; }; $scope.changePasswordBtn = function () { - $scope.dbLoading = false; - $scope.passwordChanged = true; + $scope.dbLoading = false; + $scope.passwordChanged = true; - url = "/dataBases/changePassword"; + url = "/dataBases/changePassword"; - var data = { - dbUserName:globalDBUsername, - dbPassword: $scope.dbPassword, - }; + var data = { + dbUserName: globalDBUsername, + dbPassword: $scope.dbPassword, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.changePasswordStatus == 1){ - $scope.notificationsBox = false; - $scope.passwordChanged = false; - $scope.dbLoading = true; - $scope.domainFeteched = $scope.selectedDomain; + if (response.data.changePasswordStatus == 1) { + $scope.notificationsBox = false; + $scope.passwordChanged = false; + $scope.dbLoading = true; + $scope.domainFeteched = $scope.selectedDomain; - } - else{ - $scope.notificationsBox = false; - $scope.canNotChangePassword = false; - $scope.dbLoading = true; - $scope.canNotChangePassword = false; - $scope.errorMessage = response.data.error_message; - } + } + else { + $scope.notificationsBox = false; + $scope.canNotChangePassword = false; + $scope.dbLoading = true; + $scope.canNotChangePassword = false; + $scope.errorMessage = response.data.error_message; + } - } - function cantLoadInitialDatas(response) { - $scope.notificationsBox = false; - $scope.couldNotConnect = false; - $scope.dbLoading = true; + } - } + function cantLoadInitialDatas(response) { + $scope.notificationsBox = false; + $scope.couldNotConnect = false; + $scope.dbLoading = true; - }; + } - function populateCurrentRecords(){ - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.dbLoading = false; - $scope.dbAccounts = true; - $scope.changePasswordBox = true; - $scope.notificationsBox = true; + }; - var selectedDomain = $scope.selectedDomain; + function populateCurrentRecords() { + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.dbLoading = false; + $scope.dbAccounts = true; + $scope.changePasswordBox = true; + $scope.notificationsBox = true; - url = "/dataBases/fetchDatabases"; + var selectedDomain = $scope.selectedDomain; - var data = { - databaseWebsite:selectedDomain, - }; + url = "/dataBases/fetchDatabases"; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var data = { + databaseWebsite: selectedDomain, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = JSON.parse(response.data.data); - $scope.recordsFetched = false; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.dbLoading = true; - $scope.dbAccounts = false; - $scope.changePasswordBox = true; - $scope.notificationsBox = false; + $scope.recordsFetched = false; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.dbLoading = true; + $scope.dbAccounts = false; + $scope.changePasswordBox = true; + $scope.notificationsBox = false; - $scope.domainFeteched = $scope.selectedDomain; + $scope.domainFeteched = $scope.selectedDomain; - } - else{ - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.dbLoading = true; - $scope.dbAccounts = true; - $scope.changePasswordBox = true; - $scope.notificationsBox = true; + } + else { + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.dbLoading = true; + $scope.dbAccounts = true; + $scope.changePasswordBox = true; + $scope.notificationsBox = true; - $scope.errorMessage = response.data.error_message; - } + $scope.errorMessage = response.data.error_message; + } - } - function cantLoadInitialDatas(response) { - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = false; - $scope.dbLoading = true; - $scope.dbAccounts = true; - $scope.changePasswordBox = true; - $scope.notificationsBox = true; + } - } + function cantLoadInitialDatas(response) { + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = false; + $scope.dbLoading = true; + $scope.dbAccounts = true; + $scope.changePasswordBox = true; + $scope.notificationsBox = true; - } + } + + } //// $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.dbPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.dbPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -467,4 +457,40 @@ app.controller('listDBs', function($scope,$http) { }); -/* Java script code to list database ends here */ \ No newline at end of file +/* Java script code to list database ends here */ + + +app.controller('phpMyAdmin', function ($scope, $http, $window) { + + function setupPHPMYAdminSession() { + + url = "/dataBases/setupPHPMYAdminSession"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.status === 1) { + $window.location.href = '/phpmyadmin'; + } + else {} + + } + + function cantLoadInitialDatas(response) {} + + } + setupPHPMYAdminSession(); + +}); \ No newline at end of file diff --git a/databases/templates/databases/phpMyAdmin.html b/databases/templates/databases/phpMyAdmin.html new file mode 100644 index 000000000..ace75735c --- /dev/null +++ b/databases/templates/databases/phpMyAdmin.html @@ -0,0 +1,73 @@ +{% extends "baseTemplate/index.html" %} +{% load i18n %} +{% block title %}{% trans "phpMyAdmin - CyberPanel" %}{% endblock %} +{% block content %} + +{% load static %} +{% get_current_language as LANGUAGE_CODE %} + + +
+
+

{% trans "Create Database" %}

+

{% trans "Create a new database on this page." %}

+
+ +
+
+

+ {% trans "Create Database" %} +

+
+ +
+ +
+ +
+ +
+
+ + +
+ +
+
+

{% trans "Cannot create database. Error message:" %} {$ errorMessage $}

+
+ +
+

{% trans "Database created successfully." %}

+
+ + +
+

{% trans "Could not connect to server. Please refresh this page." %}

+
+
+ + + +
+ + +
+ + + + +
+
+
+ + + +
+ + +{% endblock %} diff --git a/databases/urls.py b/databases/urls.py index 9e4926fa1..3ef288986 100644 --- a/databases/urls.py +++ b/databases/urls.py @@ -14,4 +14,6 @@ urlpatterns = [ url(r'^listDBs', views.listDBs, name='listDBs'), url(r'^changePassword', views.changePassword, name='changePassword'), + url(r'^phpMyAdmin$', views.phpMyAdmin, name='phpMyAdmin'), + url(r'^setupPHPMYAdminSession$', views.setupPHPMYAdminSession, name='setupPHPMYAdminSession'), ] \ No newline at end of file diff --git a/databases/views.py b/databases/views.py index 7edc6b02e..b9e97de24 100644 --- a/databases/views.py +++ b/databases/views.py @@ -1,11 +1,14 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.shortcuts import redirect +from django.shortcuts import redirect, HttpResponse from loginSystem.views import loadLoginPage from databaseManager import DatabaseManager from pluginManager import pluginManager import json +from plogical.processUtilities import ProcessUtilities +from loginSystem.models import Administrator +import CyberCP.settings as settings # Create your views here. def loadDatabaseHome(request): @@ -116,3 +119,39 @@ def changePassword(request): return coreResult except KeyError: return redirect(loadLoginPage) + +def phpMyAdmin(request): + try: + userID = request.session['userID'] + dm = DatabaseManager() + return dm.phpMyAdmin(request, userID) + except KeyError: + return redirect(loadLoginPage) + +def setupPHPMYAdminSession(request): + try: + + userID = request.session['userID'] + admin = Administrator.objects.get(id = userID) + + execPath = "sudo python /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) diff --git a/dockerManager/container.py b/dockerManager/container.py index 9f2452fb7..43387a0fb 100644 --- a/dockerManager/container.py +++ b/dockerManager/container.py @@ -64,7 +64,7 @@ class ContainerManager(multi.Thread): @staticmethod def executioner(command, statusFile): try: - res = ProcessUtilities.executioner(shlex.split(command), stdout=statusFile, stderr=statusFile) + res = subprocess.call(shlex.split(command), stdout=statusFile, stderr=statusFile) if res == 1: return 0 else: @@ -80,49 +80,11 @@ class ContainerManager(multi.Thread): if ACLManager.currentContextPermission(currentACL, 'createContainer') == 0: return ACLManager.loadError() + writeToFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w') + writeToFile.close() - mailUtilities.checkHome() - - statusFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w') - - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, - "Starting Docker Installation..\n", 1) - - command = "sudo adduser docker" - ServerStatusUtil.executioner(command, statusFile) - - command = 'sudo groupadd docker' - ServerStatusUtil.executioner(command, statusFile) - - command = 'sudo usermod -aG docker docker' - ServerStatusUtil.executioner(command, statusFile) - - command = 'sudo usermod -aG docker cyberpanel' - ServerStatusUtil.executioner(command, statusFile) - - if ProcessUtilities.decideDistro() == ProcessUtilities.centos: - command = 'sudo yum install -y docker' - else: - command = 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y docker.io' - - if not ServerStatusUtil.executioner(command, statusFile): - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, - "Failed to install Docker. [404]\n", 1) - return 0 - - command = 'sudo systemctl enable docker' - ServerStatusUtil.executioner(command, statusFile) - - command = 'sudo systemctl start docker' - ServerStatusUtil.executioner(command, statusFile) - - logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, - "Docker successfully installed.[200]\n", 1) - - time.sleep(2) - - cm = ContainerManager(self.name, 'restartGunicorn') - cm.start() + execPath = "sudo python /usr/local/CyberCP/dockerManager/dockerInstall.py" + ProcessUtilities.executioner(execPath) except BaseException, msg: logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) diff --git a/dockerManager/dockerInstall.py b/dockerManager/dockerInstall.py new file mode 100644 index 000000000..420d890fa --- /dev/null +++ b/dockerManager/dockerInstall.py @@ -0,0 +1,63 @@ +#!/usr/local/CyberCP/bin/python2 +import sys +sys.path.append('/usr/local/CyberCP') +import plogical.CyberCPLogFileWriter as logging +from plogical.mailUtilities import mailUtilities +from serverStatus.serverStatusUtil import ServerStatusUtil +from plogical.processUtilities import ProcessUtilities +import time + + +class DockerInstall: + + @staticmethod + def submitInstallDocker(): + try: + + mailUtilities.checkHome() + + statusFile = open(ServerStatusUtil.lswsInstallStatusPath, 'w') + + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + "Starting Docker Installation..\n", 1) + + command = "sudo adduser docker" + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo groupadd docker' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo usermod -aG docker docker' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo usermod -aG docker cyberpanel' + ServerStatusUtil.executioner(command, statusFile) + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos: + command = 'sudo yum install -y docker' + else: + command = 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y docker.io' + + if not ServerStatusUtil.executioner(command, statusFile): + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + "Failed to install Docker. [404]\n", 1) + return 0 + + command = 'sudo systemctl enable docker' + ServerStatusUtil.executioner(command, statusFile) + + command = 'sudo systemctl start docker' + ServerStatusUtil.executioner(command, statusFile) + + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, + "Docker successfully installed.[200]\n", 1) + + time.sleep(2) + + command = 'sudo systemctl restart gunicorn.socket' + ProcessUtilities.executioner(command) + + except BaseException, msg: + logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1) + +DockerInstall.submitInstallDocker() \ No newline at end of file diff --git a/emailMarketing/emailMarketing.py b/emailMarketing/emailMarketing.py index 937e38751..18d8aa578 100644 --- a/emailMarketing/emailMarketing.py +++ b/emailMarketing/emailMarketing.py @@ -14,7 +14,6 @@ from random import randint import subprocess, shlex from plogical.processUtilities import ProcessUtilities - class emailMarketing(multi.Thread): def __init__(self, function, extraArgs): multi.Thread.__init__(self) @@ -213,7 +212,7 @@ class emailMarketing(multi.Thread): messageFile.close() command = "sudo sed -i 's/{{ unsubscribeCheck }}/" + removalLink + "/g' " + tempPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) messageFile = open(tempPath, 'r') finalMessage = messageFile.read() diff --git a/emailPremium/views.py b/emailPremium/views.py index 97df5ae0d..79a475e28 100644 --- a/emailPremium/views.py +++ b/emailPremium/views.py @@ -20,7 +20,7 @@ import shlex from plogical.virtualHostUtilities import virtualHostUtilities from random import randint from plogical.acl import ACLManager - +from plogical.processUtilities import ProcessUtilities # Create your views here. @@ -54,7 +54,7 @@ def fetchPolicyServerStatus(request): if request.method == 'POST': command = 'sudo cat /etc/postfix/main.cf' - output = ProcessUtilities.outputExecutioner(shlex.split(command)).split('\n') + output = ProcessUtilities.outputExecutioner(command).split('\n') installCheck = 0 @@ -104,10 +104,8 @@ def savePolicyServerStatus(request): ## save configuration data execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" - execPath = execPath + " savePolicyServerStatus --install " + install - - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'status': 1, 'error_message': "None"} @@ -148,7 +146,7 @@ def listDomains(request): ## Check if Policy Server is installed. command = 'sudo cat /etc/postfix/main.cf' - output = ProcessUtilities.outputExecutioner(shlex.split(command)).split('\n') + output = ProcessUtilities.outputExecutioner(command).split('\n') installCheck = 0 @@ -806,15 +804,13 @@ def installStatusSpamAssassin(request): if request.method == 'POST': command = "sudo cat " + mailUtilities.spamassassinInstallLogPath - installStatus = ProcessUtilities.outputExecutioner(shlex.split(command)) + installStatus = ProcessUtilities.outputExecutioner(command) if installStatus.find("[200]")>-1: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" - execPath = execPath + " configureSpamAssassin" - - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: pass @@ -884,7 +880,7 @@ def fetchSpamAssassinSettings(request): command = "sudo cat " + confPath - data = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + data = ProcessUtilities.outputExecutioner(command).splitlines() for items in data: if items.find('report_safe ') > -1: @@ -984,10 +980,8 @@ def saveSpamAssassinConfigurations(request): ## save configuration data execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" - execPath = execPath + " saveSpamAssassinConfigs --tempConfigPath " + tempConfigPath - - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'saveStatus': 1, 'error_message': "None"} diff --git a/filemanager/filemanager.py b/filemanager/filemanager.py index fa37a9fbd..ff1baa084 100644 --- a/filemanager/filemanager.py +++ b/filemanager/filemanager.py @@ -40,7 +40,7 @@ class FileManager: return self.ajaxPre(0, 'Not allowed to browse this path, going back home!') command = "sudo ls -la --group-directories-first " + self.returnPathEnclosed(self.data['completeStartingPath']) - output = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + output = ProcessUtilities.outputExecutioner(command).splitlines() counter = 0 for items in output: @@ -72,7 +72,7 @@ class FileManager: finalData['status'] = 1 command = "sudo ls -la --group-directories-first " + self.returnPathEnclosed(self.data['completeStartingPath']) - output = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + output = ProcessUtilities.outputExecutioner(command).splitlines() counter = 0 for items in output: @@ -225,7 +225,7 @@ class FileManager: command = 'sudo cat ' + self.returnPathEnclosed(self.data['fileName']) ProcessUtilities.executioner(command) - finalData['fileContents'] = ProcessUtilities.outputExecutioner(shlex.split(command)) + finalData['fileContents'] = subprocess.check_output(shlex.split(command)) json_data = json.dumps(finalData) return HttpResponse(json_data) diff --git a/filemanager/views.py b/filemanager/views.py index 527a4cde1..b9cfae2ea 100644 --- a/filemanager/views.py +++ b/filemanager/views.py @@ -54,10 +54,10 @@ def changePermissions(request): externalApp = website.externalApp command = "sudo chown -R " + externalApp + ":" + externalApp +" /home/"+domainName - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "sudo chown -R lscpd:lscpd /home/" + domainName+"/logs" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) data_ret = {'permissionsChanged': 1, 'error_message': "None"} json_data = json.dumps(data_ret) diff --git a/firewall/admin.py b/firewall/admin.py index 8c38f3f3d..eba54e2af 100644 --- a/firewall/admin.py +++ b/firewall/admin.py @@ -1,3 +1,4 @@ from django.contrib import admin - +import models # Register your models here. +admin.site.register(models.FirewallRules) \ No newline at end of file diff --git a/firewall/firewallManager.py b/firewall/firewallManager.py index 019489839..6d2843a5f 100644 --- a/firewall/firewallManager.py +++ b/firewall/firewallManager.py @@ -162,10 +162,9 @@ class FirewallManager: return ACLManager.loadErrorJson('reload_status', 0) command = 'sudo firewall-cmd --reload' - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = ProcessUtilities.executioner(command) - if res == 0: + if res == 1: final_dic = {'reload_status': 1, 'error_message': "None"} final_json = json.dumps(final_dic) return HttpResponse(final_json) @@ -191,12 +190,9 @@ class FirewallManager: return ACLManager.loadErrorJson('start_status', 0) command = 'sudo systemctl start firewalld' + res = ProcessUtilities.executioner(command) - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - - if res == 0: + if res == 1: final_dic = {'start_status': 1, 'error_message': "None"} final_json = json.dumps(final_dic) return HttpResponse(final_json) @@ -222,10 +218,9 @@ class FirewallManager: return ACLManager.loadErrorJson('stop_status', 0) command = 'sudo systemctl stop firewalld' - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = ProcessUtilities.executioner(command) - if res == 0: + if res == 1: final_dic = {'stop_status': 1, 'error_message': "None"} final_json = json.dumps(final_dic) return HttpResponse(final_json) @@ -251,8 +246,7 @@ class FirewallManager: return ACLManager.loadErrorJson() command = 'sudo systemctl status firewalld' - - status = ProcessUtilities.outputExecutioner(shlex.split(command)) + status = ProcessUtilities.outputExecutioner(command) if status.find("active") > -1: final_dic = {'status': 1, 'error_message': "none", 'firewallStatus': 1} @@ -297,15 +291,10 @@ class FirewallManager: ## temporarily changing permission for sshd files - command = 'sudo chown -R cyberpanel:cyberpanel /etc/ssh/sshd_config' - - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - pathToSSH = "/etc/ssh/sshd_config" - data = open(pathToSSH, 'r').readlines() + cat = "sudo cat " + pathToSSH + data = ProcessUtilities.outputExecutioner(cat).split('\n') permitRootLogin = 0 sshPort = "22" @@ -318,34 +307,19 @@ class FirewallManager: if items.find("Port") > -1 and not items.find("GatewayPorts") > -1: sshPort = items.split(" ")[1].strip("\n") - ## changing permission back - - command = 'sudo chown -R root:root /etc/ssh/sshd_config' - - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - final_dic = {'status': 1, 'permitRootLogin': permitRootLogin, 'sshPort': sshPort} final_json = json.dumps(final_dic) return HttpResponse(final_json) else: - ## temporarily changing permission for sshd files - - command = 'sudo chown -R cyberpanel:cyberpanel /root' - - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - pathToKeyFile = "/root/.ssh/authorized_keys" + cat = "sudo cat " + pathToKeyFile + data = ProcessUtilities.outputExecutioner(cat).split('\n') + json_data = "[" checker = 0 - data = open(pathToKeyFile, 'r').readlines() - for items in data: if items.find("ssh-rsa") > -1: keydata = items.split(" ") @@ -374,12 +348,6 @@ class FirewallManager: json_data = json_data + ']' - ## changing permission back - - command = 'sudo chown -R root:root /root' - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) - final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) return HttpResponse(final_json) @@ -398,17 +366,20 @@ class FirewallManager: return ACLManager.loadErrorJson('saveStatus', 0) type = data['type'] + sshPort = data['sshPort'] + rootLogin = data['rootLogin'] - if type == "1": + if rootLogin == True: + rootLogin = "1" + else: + rootLogin = "0" - sshPort = data['sshPort'] - rootLogin = data['rootLogin'] + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/firewallUtilities.py" + execPath = execPath + " saveSSHConfigs --type " + str(type) + " --sshPort " + sshPort + " --rootLogin " + rootLogin - command = 'sudo semanage port -a -t ssh_port_t -p tcp ' + sshPort - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + output = ProcessUtilities.outputExecutioner(execPath) - FirewallUtilities.addRule('tcp', sshPort, "0.0.0.0/0") + if output.find("1,None") > -1: try: updateFW = FirewallRules.objects.get(name="SSHCustom") @@ -422,60 +393,13 @@ class FirewallManager: except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) - ## temporarily changing permission for sshd files - - command = 'sudo chown -R cyberpanel:cyberpanel /etc/ssh/sshd_config' - - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - - ## - - - if rootLogin == True: - rootLogin = "PermitRootLogin yes\n" - else: - rootLogin = "PermitRootLogin no\n" - - sshPort = "Port " + sshPort + "\n" - - pathToSSH = "/etc/ssh/sshd_config" - - data = open(pathToSSH, 'r').readlines() - - writeToFile = open(pathToSSH, "w") - - for items in data: - if items.find("PermitRootLogin") > -1: - if items.find("Yes") > -1 or items.find("yes"): - writeToFile.writelines(rootLogin) - continue - elif items.find("Port") > -1: - writeToFile.writelines(sshPort) - else: - writeToFile.writelines(items) - writeToFile.close() - - command = 'sudo systemctl restart sshd' - - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - - ## changin back permissions - - command = 'sudo chown -R root:root /etc/ssh/sshd_config' - - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - - ## - final_dic = {'status': 1, 'saveStatus': 1} final_json = json.dumps(final_dic) return HttpResponse(final_json) + else: + final_dic = {'status': 0, 'saveStatus': 0, "error_message": output} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) except BaseException, msg: final_dic = {'status': 0 ,'saveStatus': 0, 'error_message': str(msg)} @@ -493,44 +417,19 @@ class FirewallManager: key = data['key'] - # temp change of permissions + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/firewallUtilities.py" + execPath = execPath + " deleteSSHKey --key '" + key + "'" - command = 'sudo chown -R cyberpanel:cyberpanel /root' + output = ProcessUtilities.outputExecutioner(execPath) - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - - ## - - keyPart = key.split(" ")[1] - - pathToSSH = "/root/.ssh/authorized_keys" - - data = open(pathToSSH, 'r').readlines() - - writeToFile = open(pathToSSH, "w") - - for items in data: - if items.find("ssh-rsa") > -1 and items.find(keyPart) > -1: - continue - else: - writeToFile.writelines(items) - writeToFile.close() - - # change back permissions - - command = 'sudo chown -R root:root /root' - - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - - ## - - final_dic = {'status': 1, 'delete_status': 1} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + if output.find("1,None") > -1: + final_dic = {'status': 1, 'delete_status': 1} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'status': 1, 'delete_status': 1, "error_mssage": output} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) except BaseException, msg: final_dic = {'status': 0, 'delete_status': 0, 'error_mssage': str(msg)} @@ -548,62 +447,25 @@ class FirewallManager: key = data['key'] - # temp change of permissions + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - command = 'sudo chown -R cyberpanel:cyberpanel /root' + writeToFile = open(tempPath, "w") + writeToFile.write(key) + writeToFile.close() - cmd = shlex.split(command) + execPath = "sudo /usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/firewallUtilities.py" + execPath = execPath + " addSSHKey --tempPath " + tempPath - res = ProcessUtilities.executioner(cmd) + output = ProcessUtilities.outputExecutioner(execPath) - ## - - sshDir = "/root/.ssh" - - pathToSSH = "/root/.ssh/authorized_keys" - - if os.path.exists(sshDir): - pass + if output.find("1,None") > -1: + final_dic = {'status': 1, 'add_status': 1} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) else: - os.mkdir(sshDir) - - if os.path.exists(pathToSSH): - pass - else: - sshFile = open(pathToSSH, 'w') - sshFile.writelines("#Created by CyberPanel\n") - sshFile.close() - - presenseCheck = 0 - try: - data = open(pathToSSH, "r").readlines() - for items in data: - if items.find(key) > -1: - presenseCheck = 1 - except: - pass - - if presenseCheck == 0: - writeToFile = open(pathToSSH, 'a') - writeToFile.writelines("#Added by CyberPanel\n") - writeToFile.writelines("\n") - writeToFile.writelines(key) - writeToFile.writelines("\n") - writeToFile.close() - - # change back permissions - - command = 'sudo chown -R root:root /root' - - cmd = shlex.split(command) - - res = ProcessUtilities.executioner(cmd) - - ## - - final_dic = {'status': 1, 'add_status': 1} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + final_dic = {'status': 0, 'add_status': 0, "error_mssage": output} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) except BaseException, msg: final_dic = {'status': 0, 'add_status': 0, 'error_mssage': str(msg)} @@ -624,7 +486,7 @@ class FirewallManager: confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines() modSecInstalled = 0 @@ -649,7 +511,14 @@ class FirewallManager: else: return ACLManager.loadErrorJson('installModSec', 0) - thread.start_new_thread(modSec.installModSec, ('Install', 'modSec')) + writeToFile = open(modSec.installLogPath, "w") + writeToFile.close() + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" + execPath = execPath + " installModSec" + + ProcessUtilities.popenExecutioner(execPath) + final_json = json.dumps({'installModSec': 1, 'error_message': "None"}) return HttpResponse(final_json) @@ -661,7 +530,8 @@ class FirewallManager: def installStatusModSec(self, userID = None, data = None): try: - installStatus = unicode(open(modSec.installLogPath, "r").read()) + command = "sudo cat " + modSec.installLogPath + installStatus = ProcessUtilities.outputExecutioner(command) if installStatus.find("[200]") > -1: @@ -669,7 +539,7 @@ class FirewallManager: execPath = execPath + " installModSecConfigs" - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = subprocess.check_output(shlex.split(execPath)) if output.find("1,None") > -1: pass @@ -738,7 +608,7 @@ class FirewallManager: if os.path.exists(modSecPath): command = "sudo cat " + confPath - data = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + data = ProcessUtilities.outputExecutioner(command).split('\n') for items in data: @@ -803,7 +673,7 @@ class FirewallManager: command = "sudo cat " + confPath - data = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + data = ProcessUtilities.outputExecutioner(command).split('\n') for items in data: if items.find('SecAuditEngine ') > -1: @@ -917,7 +787,7 @@ class FirewallManager: execPath = execPath + " saveModSecConfigs --tempConfigPath " + tempConfigPath - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: installUtilities.reStartLiteSpeed() @@ -973,7 +843,7 @@ class FirewallManager: execPath = execPath + " saveModSecConfigs --tempConfigPath " + tempConfigPath - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: installUtilities.reStartLiteSpeed() @@ -1004,7 +874,7 @@ class FirewallManager: confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n') modSecInstalled = 0 @@ -1034,7 +904,7 @@ class FirewallManager: confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n') modSecInstalled = 0 @@ -1047,7 +917,7 @@ class FirewallManager: if modSecInstalled: command = "sudo cat " + rulesPath - currentModSecRules = ProcessUtilities.outputExecutioner(shlex.split(command)) + currentModSecRules = ProcessUtilities.outputExecutioner(command).split('\n') final_dic = {'modSecInstalled': 1, 'currentModSecRules': currentModSecRules} @@ -1063,7 +933,7 @@ class FirewallManager: rulesPath = os.path.join(virtualHostUtilities.Server_root + "/conf/rules.conf") command = "sudo cat " + rulesPath - currentModSecRules = ProcessUtilities.outputExecutioner(shlex.split(command)) + currentModSecRules = ProcessUtilities.outputExecutioner(command).split('\n') final_dic = {'modSecInstalled': 1, 'currentModSecRules': currentModSecRules} @@ -1098,7 +968,7 @@ class FirewallManager: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" execPath = execPath + " saveModSecRules" - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath).split('\n') if output.find("1,None") > -1: installUtilities.reStartLiteSpeed() @@ -1130,7 +1000,7 @@ class FirewallManager: confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n') modSecInstalled = 0 @@ -1160,7 +1030,7 @@ class FirewallManager: confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines() modSecInstalled = 0 @@ -1174,7 +1044,7 @@ class FirewallManager: if modSecInstalled: command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines() for items in httpdConfig: @@ -1205,9 +1075,9 @@ class FirewallManager: try: command = 'sudo cat /usr/local/lsws/conf/comodo_litespeed/rules.conf.main' - res = ProcessUtilities.executioner(shlex.split(command)) + res = ProcessUtilities.executioner(command) - if res == 0: + if res == 1: comodoInstalled = 1 except subprocess.CalledProcessError: pass @@ -1242,7 +1112,7 @@ class FirewallManager: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" execPath = execPath + " " + packName - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: installUtilities.reStartLiteSpeed() @@ -1260,7 +1130,7 @@ class FirewallManager: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" execPath = execPath + " " + packName - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: installUtilities.reStartLiteSpeed() @@ -1292,7 +1162,7 @@ class FirewallManager: confPath = os.path.join(virtualHostUtilities.Server_root, 'conf/httpd_config.conf') command = "sudo cat " + confPath - httpdConfig = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines() json_data = "[" checker = 0 @@ -1334,7 +1204,7 @@ class FirewallManager: comodoPath = '/usr/local/lsws/conf/comodo_litespeed' command = 'sudo chown -R cyberpanel:cyberpanel /usr/local/lsws/conf' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) json_data = "[" @@ -1370,7 +1240,7 @@ class FirewallManager: json_data = json_data + ',' + json.dumps(dic) command = 'sudo chown -R lsadm:lsadm /usr/local/lsws/conf' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) json_data = json_data + ']' final_json = json.dumps({'fetchStatus': 1, 'error_message': "None", "data": json_data}) @@ -1403,7 +1273,7 @@ class FirewallManager: execPath = execPath + " " + functionName + ' --packName ' + packName + ' --fileName ' + fileName - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: installUtilities.reStartLiteSpeed() @@ -1433,8 +1303,8 @@ class FirewallManager: csfInstalled = 1 try: command = 'sudo csf -h' - res = ProcessUtilities.executioner(shlex.split(command)) - if res == 1: + res = ProcessUtilities.executioner(command) + if res == 0: csfInstalled = 0 except subprocess.CalledProcessError: csfInstalled = 0 @@ -1454,7 +1324,7 @@ class FirewallManager: execPath = "sudo /usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/csf.py" execPath = execPath + " installCSF" - ProcessUtilities.popenExecutioner(shlex.split(execPath)) + ProcessUtilities.popenExecutioner(execPath) time.sleep(2) @@ -1477,7 +1347,7 @@ class FirewallManager: if installStatus.find("[200]")>-1: command = 'sudo rm -f ' + CSF.installLogPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) final_json = json.dumps({ 'error_message': "None", @@ -1488,7 +1358,7 @@ class FirewallManager: return HttpResponse(final_json) elif installStatus.find("[404]") > -1: command = 'sudo rm -f ' + CSF.installLogPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) final_json = json.dumps({ 'abort':1, 'installed':0, @@ -1522,7 +1392,7 @@ class FirewallManager: execPath = "sudo /usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/csf.py" execPath = execPath + " removeCSF" - ProcessUtilities.popenExecutioner(shlex.split(execPath)) + ProcessUtilities.popenExecutioner(execPath) time.sleep(2) @@ -1581,7 +1451,7 @@ class FirewallManager: execPath = "sudo /usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/csf.py" execPath = execPath + " changeStatus --controller " + controller + " --status " + status - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {"status": 1} @@ -1615,7 +1485,7 @@ class FirewallManager: execPath = "sudo /usr/local/CyberCP/bin/python2 " + virtualHostUtilities.cyberPanel + "/plogical/csf.py" execPath = execPath + " modifyPorts --protocol " + protocol + " --ports " + ports - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {"status": 1} diff --git a/firewall/models.py b/firewall/models.py index 9ce57c2c9..921137655 100644 --- a/firewall/models.py +++ b/firewall/models.py @@ -2,7 +2,6 @@ from django.db import models # Create your models here. - class FirewallRules(models.Model): name = models.CharField(unique=True, max_length=32) # Field name made lowercase. proto = models.CharField(max_length=10) diff --git a/ftp/ftpManager.py b/ftp/ftpManager.py index b05d1535c..0e10b99e7 100644 --- a/ftp/ftpManager.py +++ b/ftp/ftpManager.py @@ -13,12 +13,11 @@ from loginSystem.models import Administrator import plogical.CyberCPLogFileWriter as logging from loginSystem.views import loadLoginPage from websiteFunctions.models import Websites -import subprocess from plogical.virtualHostUtilities import virtualHostUtilities -import shlex from plogical.ftpUtilities import FTPUtilities import os from plogical.acl import ACLManager +from plogical.processUtilities import ProcessUtilities class FTPManager: def __init__(self, request): @@ -85,7 +84,9 @@ class FTPManager: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/ftpUtilities.py" execPath = execPath + " submitFTPCreation --domainName " + domainName + " --userName " + userName \ + " --password " + password + " --path " + path + " --owner " + admin.userName + ' --api ' + api - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,None") > -1: data_ret = {'status': 1, 'creatFTPStatus': 1, 'error_message': 'None'} json_data = json.dumps(data_ret) diff --git a/highAvailability/haManager.py b/highAvailability/haManager.py index 1028a5792..e83acc336 100644 --- a/highAvailability/haManager.py +++ b/highAvailability/haManager.py @@ -55,7 +55,7 @@ class HAManager(multi.Thread): for command in commands: try: - result = ProcessUtilities.executioner(command, shell=True) + result = subprocess.call(command, shell=True) if result != 0: logging.writeToFile(command + ' Failed.') except BaseException: @@ -99,14 +99,14 @@ class HAManager(multi.Thread): workerToken = '' command = "sudo docker swarm join-token manager" - output = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + output = subprocess.check_output(shlex.split(command)).splitlines() for items in output: if items.find('--token') > -1: managerToken = items.split(' ')[-2] command = "sudo docker swarm join-token worker" - output = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + output = subprocess.check_output(shlex.split(command)).splitlines() for items in output: if items.find('--token') > -1: @@ -160,7 +160,7 @@ class HAManager(multi.Thread): for command in commands: try: - result = ProcessUtilities.executioner(command, shell=True) + result = subprocess.call(command, shell=True) if result != 0: logging.writeToFile(command + ' Failed.') except BaseException, msg: diff --git a/install/firewallUtilities.py b/install/firewallUtilities.py index 539a4f21f..b4bfacd54 100644 --- a/install/firewallUtilities.py +++ b/install/firewallUtilities.py @@ -8,7 +8,7 @@ class FirewallUtilities: import install as inst try: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if inst.preFlightsChecks.resFailed(inst.get_distro(), res): inst.preFlightsChecks.stdOut("Failed to apply rule: " + command + " Error #" + str(res), 1) return 0 diff --git a/install/install.py b/install/install.py index f16786f8a..b7d38eded 100644 --- a/install/install.py +++ b/install/install.py @@ -21,6 +21,53 @@ import stat centos = 0 ubuntu = 1 +def get_distro(): + distro = -1 + distro_file = "" + if exists("/etc/lsb-release"): + distro_file = "/etc/lsb-release" + with open(distro_file) as f: + for line in f: + if line == "DISTRIB_ID=Ubuntu\n": + distro = ubuntu + + elif exists("/etc/os-release"): + distro_file = "/etc/os-release" + distro = centos + + else: + logging.InstallLog.writeToFile("Can't find linux release file - fatal error") + preFlightsChecks.stdOut("Can't find linux release file - fatal error") + os._exit(os.EX_UNAVAILABLE) + + if distro == -1: + logging.InstallLog.writeToFile("Can't find distro name in " + distro_file + " - fatal error") + preFlightsChecks.stdOut("Can't find distro name in " + distro_file + " - fatal error") + os._exit(os.EX_UNAVAILABLE) + + return distro + + +def get_Ubuntu_release(): + release = -1 + if exists("/etc/lsb-release"): + distro_file = "/etc/lsb-release" + with open(distro_file) as f: + for line in f: + if line[:16] == "DISTRIB_RELEASE=": + release = float(line[16:]) + + if release == -1: + preFlightsChecks.stdOut("Can't find distro release name in " + distro_file + " - fatal error", 1, 1, + os.EX_UNAVAILABLE) + + else: + logging.InstallLog.writeToFile("Can't find linux release file - fatal error") + preFlightsChecks.stdOut("Can't find linux release file - fatal error") + os._exit(os.EX_UNAVAILABLE) + + return release + class preFlightsChecks: cyberPanelMirror = "mirror.cyberpanel.net/pip" @@ -33,40 +80,6 @@ class preFlightsChecks: self.cyberPanelPath = cyberPanelPath self.distro = distro - def mountTemp(self): - try: - command = "mkdir -p /root/images/" - ProcessUtilities.executioner(shlex.split(command)) - - command = "dd if=/dev/zero of=/root/images/tmpfile.bin bs=1 count=0 seek=4G" - ProcessUtilities.executioner(shlex.split(command)) - - command = "mkfs.ext4 /root/images/tmpfile.bin" - ProcessUtilities.executioner(shlex.split(command)) - - command = "mount -o loop,rw,nodev,nosuid,noexec /root/images/tmpfile.bin /tmp" - ProcessUtilities.executioner(shlex.split(command)) - - command = "chmod 1777 /tmp" - ProcessUtilities.executioner(shlex.split(command)) - - command = "mount -o rw,noexec,nosuid,nodev,bind /tmp /var/tmp" - ProcessUtilities.executioner(shlex.split(command)) - - tmp = "/root/images/tmpfile.bin /tmp ext4 loop,rw,noexec,nosuid,nodev 0 0\n" - varTmp = "/tmp /var/tmp none rw,noexec,nosuid,nodev,bind 0 0\n" - - fstab = "/etc/fstab" - writeToFile = open(fstab, "a") - writeToFile.writelines(tmp); - writeToFile.writelines(varTmp) - writeToFile.close() - - except BaseException, msg: - preFlightsChecks.stdOut("[Failed:mountTemp] " + str(msg)) - return 0 - - @staticmethod def stdOut(message, log=0, do_exit=0, code=os.EX_OK): print("\n\n") @@ -81,6 +94,51 @@ class preFlightsChecks: if do_exit: sys.exit(code) + def mountTemp(self): + try: + command = "mkdir -p /root/images/" + preFlightsChecks.call(command, self.distro, '[mountTemp]', + 'mountTemp', + 1, 0, os.EX_OSERR) + + command = "dd if=/dev/zero of=/root/images/tmpfile.bin bs=1 count=0 seek=4G" + preFlightsChecks.call(command, self.distro, '[mountTemp]', + 'mountTemp', + 1, 0, os.EX_OSERR) + + command = "mkfs.ext4 -F /root/images/tmpfile.bin" + preFlightsChecks.call(command, self.distro, '[mountTemp]', + 'mountTemp', + 1, 0, os.EX_OSERR) + + command = "mount -o loop,rw,nodev,nosuid,noexec /root/images/tmpfile.bin /tmp" + preFlightsChecks.call(command, self.distro, '[mountTemp]', + 'mountTemp', + 1, 0, os.EX_OSERR) + + command = "chmod 1777 /tmp" + preFlightsChecks.call(command, self.distro, '[mountTemp]', + 'mountTemp', + 1, 0, os.EX_OSERR) + + command = "mount -o rw,noexec,nosuid,nodev,bind /tmp /var/tmp" + preFlightsChecks.call(command, self.distro, '[mountTemp]', + 'mountTemp', + 1, 0, os.EX_OSERR) + + tmp = "/root/images/tmpfile.bin /tmp ext4 loop,rw,noexec,nosuid,nodev 0 0\n" + varTmp = "/tmp /var/tmp none rw,noexec,nosuid,nodev,bind 0 0\n" + + fstab = "/etc/fstab" + writeToFile = open(fstab, "a") + writeToFile.writelines(tmp); + writeToFile.writelines(varTmp) + writeToFile.close() + + except BaseException, msg: + preFlightsChecks.stdOut("[Failed:mountTemp] " + str(msg)) + return 0 + @staticmethod def pureFTPDServiceName(distro): if distro == ubuntu: @@ -100,7 +158,7 @@ class preFlightsChecks: preFlightsChecks.stdOut(message + " " + bracket, log) count = 0 while True: - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(distro, res): count = count + 1 @@ -121,7 +179,7 @@ class preFlightsChecks: def checkIfSeLinuxDisabled(self): try: command = "sestatus" - output = ProcessUtilities.outputExecutioner(shlex.split(command)) + output = subprocess.check_output(shlex.split(command)) if output.find("disabled") > -1 or output.find("permissive") > -1: logging.InstallLog.writeToFile("SELinux Check OK. [checkIfSeLinuxDisabled]") @@ -178,7 +236,7 @@ class preFlightsChecks: self.stdOut("Add Cyberpanel user") command = "useradd cyberpanel -m -U -G sudo" cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res != 0 and res != 9: logging.InstallLog.writeToFile("Can not create cyberpanel user, error #" + str(res)) preFlightsChecks.stdOut("Can not create cyberpanel user, error #" + str(res)) @@ -233,7 +291,7 @@ class preFlightsChecks: command = 'yum update -y' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -267,7 +325,7 @@ class preFlightsChecks: filename = "enable_lst_debain_repo.sh" command = "wget http://rpms.litespeedtech.com/debian/" + filename cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res != 0: logging.InstallLog.writeToFile( "Unable to download Ubuntu CyberPanel installer! [installCyberPanelRepo]:" @@ -280,7 +338,7 @@ class preFlightsChecks: command = "./" + filename cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res != 0: logging.InstallLog.writeToFile("Unable to install Ubuntu CyberPanel! [installCyberPanelRepo]:" @@ -304,7 +362,7 @@ class preFlightsChecks: cmd.append("rpm") cmd.append("-ivh") cmd.append("http://rpms.litespeedtech.com/centos/litespeed-repo-1.1-1.el7.noarch.rpm") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -330,7 +388,7 @@ class preFlightsChecks: cmd.append("-y") cmd.append("install") cmd.append("epel-release") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -367,7 +425,7 @@ class preFlightsChecks: command = "apt-get -y install python-pip" else: command = "yum -y install python-pip" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -389,7 +447,7 @@ class preFlightsChecks: command = "yum -y install python-devel" else: command = "apt-get -y install python-dev" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -414,7 +472,7 @@ class preFlightsChecks: command = "yum -y install gcc" else: command = "apt-get -y install gcc" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -432,7 +490,7 @@ class preFlightsChecks: count = 0 while (1): command = "yum -y install python-setuptools" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -456,10 +514,10 @@ class preFlightsChecks: ## Un-install ULRLIB3 and requests command = "pip uninstall --yes urllib3" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) command = "pip uninstall --yes requests" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) ## Install specific versions @@ -468,7 +526,7 @@ class preFlightsChecks: command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/urllib3-1.22.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -489,7 +547,7 @@ class preFlightsChecks: command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/requests-2.18.4.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -512,7 +570,7 @@ class preFlightsChecks: command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/urllib3-1.22.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -533,7 +591,7 @@ class preFlightsChecks: command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/requests-2.18.4.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -554,14 +612,14 @@ class preFlightsChecks: import pexpect command = "pip uninstall --yes pexpect" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) count = 0 while (1): command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/pexpect-4.4.0.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -581,7 +639,7 @@ class preFlightsChecks: while (1): command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/pexpect-4.4.0.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -601,7 +659,7 @@ class preFlightsChecks: while (1): command = "pip install django==1.11" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -623,7 +681,7 @@ class preFlightsChecks: command = "yum -y install MySQL-python" else: command = "apt-get -y install libmysqlclient-dev" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 preFlightsChecks.stdOut("Unable to install MySQL-python, trying again, try number: " + str(count)) @@ -639,7 +697,7 @@ class preFlightsChecks: if self.distro == ubuntu: command = "pip install MySQL-python" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if res != 0: logging.InstallLog.writeToFile( "Unable to install MySQL-python, exiting installer! [install_python_mysql_library] Error: " + str( @@ -657,7 +715,7 @@ class preFlightsChecks: command = "pip install gunicorn" else: command = "easy_install gunicorn" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 preFlightsChecks.stdOut("Unable to install GUNICORN, trying again, try number: " + str(count)) @@ -695,7 +753,7 @@ class preFlightsChecks: while (1): command = "systemctl enable gunicorn.socket" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -722,12 +780,12 @@ class preFlightsChecks: ## command = "pip uninstall --yes psutil" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) count = 0 while (1): command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/psutil-5.4.3.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -745,7 +803,7 @@ class preFlightsChecks: count = 0 while (1): command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/psutil-5.4.3.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -768,7 +826,7 @@ class preFlightsChecks: cmd.append("httpd_can_network_connect") cmd.append("1") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): logging.InstallLog.writeToFile("fix_selinux_issue problem") @@ -785,7 +843,7 @@ class preFlightsChecks: command = "yum -y install psmisc" else: command = "apt-get -y install psmisc" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 preFlightsChecks.stdOut("Unable to install psmisc, trying again, try number: " + str(count)) @@ -802,7 +860,7 @@ class preFlightsChecks: try: ## On OpenVZ there is an issue with requests module, which needs to upgrade requests module - if ProcessUtilities.outputExecutioner('systemd-detect-virt').find("openvz") > -1: + if subprocess.check_output('systemd-detect-virt').find("openvz") > -1: command = "pip install --upgrade requests" preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', 'Upgrade requests', @@ -903,18 +961,46 @@ class preFlightsChecks: preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', 'Move static content', 1, 1, os.EX_OSERR) - ## fix permissions + def fixCyberPanelPermissions(self): + ###### fix Core CyberPanel permissions - command = "chmod -R 744 /usr/local/CyberCP" + command = "find /usr/local/CyberCP -type d -exec chmod 0755 {} \;" preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', - 'change permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) + 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) + command = "find /usr/local/CyberCP -type f -exec chmod 0644 {} \;" + preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', + 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) + + command = "chmod -R 755 /usr/local/CyberCP/bin" + preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', + 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) ## change owner - command = "chown -R cyberpanel:cyberpanel /usr/local/CyberCP" + command = "chown -R root:root /usr/local/CyberCP" preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', - 'change owner /usr/local/CyberCP', 1, 0, os.EX_OSERR) + 'change owner /usr/local/CyberCP', 1, 0, os.EX_OSERR) + + ########### Fix LSCPD + + command = "find /usr/local/lscp -type d -exec chmod 0755 {} \;" + preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', + 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) + + command = "find /usr/local/lscp -type f -exec chmod 0644 {} \;" + preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', + 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) + + command = "chmod -R 755 /usr/local/lscp/bin" + preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', + 'fix permissions /usr/local/CyberCP', 1, 0, os.EX_OSERR) + + ## change owner + + command = "chown -R root:root /usr/local/lscp" + preFlightsChecks.call(command, self.distro, '[download_install_CyberPanel]', + 'change owner /usr/local/CyberCP', 1, 0, os.EX_OSERR) def install_unzip(self): @@ -974,7 +1060,7 @@ class preFlightsChecks: os.mkdir('/usr/local/lscp/cyberpanel/phpmyadmin/tmp') command = 'chown -R lscpd:lscpd /usr/local/lscp/cyberpanel/phpmyadmin' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except BaseException, msg: logging.InstallLog.writeToFile(str(msg) + " [download_install_phpmyadmin]") @@ -991,7 +1077,7 @@ class preFlightsChecks: else: command = 'apt-get -y remove postfix' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) self.stdOut("Install dovecot - do the install") count = 0 @@ -1000,19 +1086,19 @@ class preFlightsChecks: command = 'yum install -y postfix' else: command = 'apt-get -y debconf-utils' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) file_name = self.cwd + '/pf.unattend.text' pf = open(file_name, 'w') pf.write('postfix postfix/mailname string ' + str(socket.getfqdn() + '\n')) pf.write('postfix postfix/main_mailer_type string "Internet Site"\n') pf.close() command = 'debconf-set-selections ' + file_name - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = 'apt-get -y install postfix' # os.remove(file_name) cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1036,7 +1122,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1061,7 +1147,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1281,7 +1367,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1305,7 +1391,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1365,7 +1451,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1391,7 +1477,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1415,7 +1501,7 @@ class preFlightsChecks: command = 'chmod o= /etc/postfix/mysql-virtual_mailboxes.cf' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1440,7 +1526,7 @@ class preFlightsChecks: command = 'chmod o= /etc/postfix/mysql-virtual_email2email.cf' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1464,7 +1550,7 @@ class preFlightsChecks: command = 'chmod o= ' + main cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1490,7 +1576,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1515,7 +1601,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1537,7 +1623,7 @@ class preFlightsChecks: while (1): command = 'chgrp postfix /etc/postfix/mysql-virtual_forwardings.cf' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1560,7 +1646,7 @@ class preFlightsChecks: while (1): command = 'chgrp postfix /etc/postfix/mysql-virtual_mailboxes.cf' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1584,7 +1670,7 @@ class preFlightsChecks: command = 'chgrp postfix /etc/postfix/mysql-virtual_email2email.cf' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1606,7 +1692,7 @@ class preFlightsChecks: while (1): command = 'chgrp postfix ' + main cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1631,7 +1717,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1656,7 +1742,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1680,7 +1766,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1708,7 +1794,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1733,7 +1819,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1757,7 +1843,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1783,7 +1869,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1809,7 +1895,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1831,7 +1917,7 @@ class preFlightsChecks: while (1): command = 'systemctl start dovecot.service' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1855,7 +1941,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1878,7 +1964,7 @@ class preFlightsChecks: command = "chmod 755 " + main cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1897,18 +1983,18 @@ class preFlightsChecks: if self.distro == ubuntu: command = "mkdir -p /etc/pki/dovecot/private/" cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) command = "mkdir -p /etc/pki/dovecot/certs/" cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) command = "mkdir -p /etc/opendkim/keys/" cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) command = "sed -i 's/auth_mechanisms = plain/#auth_mechanisms = plain/g' /etc/dovecot/conf.d/10-auth.conf" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) ## Ubuntu 18.10 ssl_dh for dovecot 2.3.2.1 @@ -1926,7 +2012,7 @@ class preFlightsChecks: writeToFile.close() command = "systemctl restart dovecot" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) logging.InstallLog.writeToFile("Postfix and Dovecot configured") @@ -1947,7 +2033,7 @@ class preFlightsChecks: while (1): command = 'chown -R lscpd:lscpd /usr/local/lscp/cyberpanel/' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1974,7 +2060,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -1997,7 +2083,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2022,7 +2108,7 @@ class preFlightsChecks: while (1): command = 'find . -type d -exec chmod 755 {} \;' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2046,7 +2132,7 @@ class preFlightsChecks: command = 'find . -type f -exec chmod 644 {} \;' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2068,7 +2154,7 @@ class preFlightsChecks: command = 'chown -R lscpd:lscpd .' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2107,7 +2193,7 @@ class preFlightsChecks: cmd.append(self.server_root_path + "bin/lswsctrl") cmd.append("restart") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2131,7 +2217,7 @@ class preFlightsChecks: def removeUfw(self): try: preFlightsChecks.stdOut("Checking to see if ufw firewall is installed (will be removed)", 1) - status = ProcessUtilities.outputExecutioner(shlex.split('ufw status')) + status = subprocess.check_output(shlex.split('ufw status')) preFlightsChecks.stdOut("ufw current status: " + status + "...will be removed") except BaseException, msg: preFlightsChecks.stdOut("Expected access to ufw not available, do not need to remove it", 1) @@ -2192,6 +2278,14 @@ class preFlightsChecks: FirewallUtilities.addRule("tcp", "80") FirewallUtilities.addRule("tcp", "443") FirewallUtilities.addRule("tcp", "21") + FirewallUtilities.addRule("tcp", "25") + FirewallUtilities.addRule("tcp", "587") + FirewallUtilities.addRule("tcp", "465") + FirewallUtilities.addRule("tcp", "110") + FirewallUtilities.addRule("tcp", "143") + FirewallUtilities.addRule("tcp", "993") + FirewallUtilities.addRule("udp", "53") + FirewallUtilities.addRule("tcp", "53") FirewallUtilities.addRule("tcp", "40110-40210") logging.InstallLog.writeToFile("FirewallD installed and configured!") @@ -2209,6 +2303,195 @@ class preFlightsChecks: ## from here + + def installLSCPD(self): + try: + + logging.InstallLog.writeToFile("Starting LSCPD installation..") + + os.chdir(self.cwd) + + if self.distro == ubuntu: + command = "apt-get -y install gcc g++ make autoconf rcs" + else: + command = 'yum -y install gcc gcc-c++ make autoconf glibc rcs' + + preFlightsChecks.call(command, self.distro, '[installLSCPD]', + 'Install LSCPD', + 1, 1, os.EX_OSERR) + + if self.distro == ubuntu: + command = "apt-get -y install libpcre3 libpcre3-dev openssl libexpat1 libexpat1-dev libgeoip-dev" \ + " zlib1g zlib1g-dev libudns-dev whichman curl" + else: + command = 'yum -y install pcre-devel openssl-devel expat-devel geoip-devel zlib-devel udns-devel' \ + ' which curl' + + preFlightsChecks.call(command, self.distro, '[installLSCPD]', + 'Install LSCPD', + 1, 1, os.EX_OSERR) + + + command = 'tar zxf lscp.tar.gz -C /usr/local/' + preFlightsChecks.call(command, self.distro, '[installLSCPD]', + 'Install LSCPD', + 1, 1, os.EX_OSERR) + + + command = 'openssl req -newkey rsa:1024 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout /usr/local/lscp/key.pem -out /usr/local/lscp/cert.pem' + preFlightsChecks.call(command, self.distro, '[installLSCPD]', + 'Install LSCPD', + 1, 1, os.EX_OSERR) + + try: + os.remove("/usr/local/lscp/fcgi-bin/lsphp") + shutil.copy("/usr/local/lsws/lsphp70/bin/lsphp","/usr/local/lscp/fcgi-bin/lsphp") + except: + pass + + if self.distro == centos: + command = 'adduser lscpd -M -d /usr/local/lscp' + else: + command = 'useradd lscpd -M -d /usr/local/lscp' + + preFlightsChecks.call(command, self.distro, '[installLSCPD]', + 'Install LSCPD', + 1, 0, os.EX_OSERR) + + if self.distro == centos: + command = 'groupadd lscpd' + preFlightsChecks.call(command, self.distro, '[installLSCPD]', + 'Install LSCPD', + 1, 0, os.EX_OSERR) + # Added group in useradd for Ubuntu + + command = 'usermod -a -G lscpd lscpd' + preFlightsChecks.call(command, self.distro, '[installLSCPD]', + 'Install LSCPD', + 1, 0, os.EX_OSERR) + + command = 'usermod -a -G lsadm lscpd' + preFlightsChecks.call(command, self.distro, '[installLSCPD]', + 'Install LSCPD', + 1, 0, os.EX_OSERR) + + os.mkdir('/usr/local/lscp/cyberpanel') + os.mkdir('/usr/local/lscp/cyberpanel/logs') + + self.setupComodoRules() + self.setupPort() + + logging.InstallLog.writeToFile("LSCPD successfully installed!") + + except BaseException, msg: + logging.InstallLog.writeToFile(str(msg) + " [installLSCPD]") + + def setupComodoRules(self): + try: + os.chdir(self.cwd) + + extractLocation = "/usr/local/lscp/modsec" + + command = "mkdir -p /usr/local/lscp/modsec" + preFlightsChecks.call(command, self.distro, '[setupComodoRules]', + 'setupComodoRules', + 1, 0, os.EX_OSERR) + + try: + if os.path.exists('comodo.tar.gz'): + os.remove('comodo.tar.gz') + except: + pass + + command = "wget https://cyberpanel.net/modsec/comodo.tar.gz" + result = preFlightsChecks.call(command, self.distro, '[setupComodoRules]', + 'setupComodoRules', + 1, 0, os.EX_OSERR) + + command = "tar -zxf comodo.tar.gz -C /usr/local/lscp/modsec" + preFlightsChecks.call(command, self.distro, '[setupComodoRules]', + 'setupComodoRules', + 1, 0, os.EX_OSERR) + + ### + + modsecConfPath = "/usr/local/lscp/conf/modsec.conf" + + modsecConfig = """ + module mod_security { + modsecurity on + modsecurity_rules ` + SecDebugLogLevel 0 + SecDebugLog /usr/local/lscp/logs/modsec.log + SecAuditEngine on + SecAuditLogRelevantStatus "^(?:5|4(?!04))" + SecAuditLogParts AFH + SecAuditLogType Serial + SecAuditLog /usr/local/lscp/logs/auditmodsec.log + SecRuleEngine On + ` + modsecurity_rules_file /usr/local/lscp/modsec/comodo/modsecurity.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/00_Init_Initialization.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/01_Init_AppsInitialization.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/02_Global_Generic.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/03_Global_Agents.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/04_Global_Domains.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/05_Global_Backdoor.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/06_XSS_XSS.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/07_Global_Other.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/08_Bruteforce_Bruteforce.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/09_HTTP_HTTP.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/10_HTTP_HTTPDoS.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/11_HTTP_Protocol.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/12_HTTP_Request.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/13_Outgoing_FilterGen.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/14_Outgoing_FilterASP.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/15_Outgoing_FilterPHP.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/16_Outgoing_FilterSQL.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/17_Outgoing_FilterOther.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/18_Outgoing_FilterInFrame.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/19_Outgoing_FiltersEnd.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/20_PHP_PHPGen.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/21_SQL_SQLi.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/22_Apps_Joomla.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/23_Apps_JComponent.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/24_Apps_WordPress.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/25_Apps_WPPlugin.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/26_Apps_WHMCS.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/27_Apps_Drupal.conf + modsecurity_rules_file /usr/local/lscp/modsec/comodo/28_Apps_OtherApps.conf + } + """ + + writeToFile = open(modsecConfPath, 'w') + writeToFile.write(modsecConfig) + writeToFile.close() + + ### + + command = "chown -R lscpd:lscpd /usr/local/lscp/modsec" + preFlightsChecks.call(command, self.distro, '[setupComodoRules]', + 'setupComodoRules', + 1, 0, os.EX_OSERR) + + return 1 + + except BaseException, msg: + logging.InstallLog.writeToFile("[Failed:setupComodoRules] " + str(msg)) + return 0 + + def setupPort(self): + try: + ### + bindConfPath = "/usr/local/lscp/conf/bind.conf" + + writeToFile = open(bindConfPath, 'w') + writeToFile.write("*:" + self.port) + writeToFile.close() + + except: + return 0 + def setupLSCPDDaemon(self): try: @@ -2227,7 +2510,7 @@ class preFlightsChecks: while (1): command = 'chmod +x /usr/local/lscp/bin/lscpdctrl' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2252,7 +2535,7 @@ class preFlightsChecks: command = 'systemctl enable lscpd.service' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2272,7 +2555,7 @@ class preFlightsChecks: # In Ubuntu, the library that lscpd looks for is libpcre.so.1, but the one it installs is libpcre.so.3... if self.distro == ubuntu: command = 'ln -s /lib/x86_64-linux-gnu/libpcre.so.3 /lib/x86_64-linux-gnu/libpcre.so.1' - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if res == 0: self.stdOut("Created ubuntu symbolic link to pcre") else: @@ -2286,7 +2569,7 @@ class preFlightsChecks: command = 'systemctl start lscpd' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2327,7 +2610,7 @@ class preFlightsChecks: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=file) + res = subprocess.call(cmd, stdout=file) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2351,7 +2634,7 @@ class preFlightsChecks: command = 'systemctl enable cron' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=file) + res = subprocess.call(cmd, stdout=file) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2374,7 +2657,7 @@ class preFlightsChecks: else: command = 'systemctl start cron' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=file) + res = subprocess.call(cmd, stdout=file) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2399,11 +2682,11 @@ class preFlightsChecks: command = 'chmod +x /usr/local/CyberCP/plogical/findBWUsage.py' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=file) + res = subprocess.call(cmd, stdout=file) command = 'chmod +x /usr/local/CyberCP/plogical/upgradeCritical.py' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=file) + res = subprocess.call(cmd, stdout=file) if preFlightsChecks.resFailed(self.distro, res): logging.InstallLog.writeToFile("1427 [setup_cron]") @@ -2413,7 +2696,7 @@ class preFlightsChecks: command = 'chmod +x /usr/local/CyberCP/postfixSenderPolicy/client.py' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=file) + res = subprocess.call(cmd, stdout=file) if preFlightsChecks.resFailed(self.distro, res): logging.InstallLog.writeToFile("1428 [setup_cron]") @@ -2428,7 +2711,7 @@ class preFlightsChecks: else: command = 'systemctl restart cron.service' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=file) + res = subprocess.call(cmd, stdout=file) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2467,7 +2750,7 @@ class preFlightsChecks: command = "ssh-keygen -f /root/.ssh/cyberpanel -t rsa -N ''" cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2500,7 +2783,7 @@ class preFlightsChecks: command = 'apt-get -y install rsync' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2532,17 +2815,17 @@ class preFlightsChecks: except BaseException, msg: command = "pip uninstall --yes urllib3" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "pip uninstall --yes requests" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) count = 0 while (1): command = "pip install http://mirror.cyberpanel.net/urllib3-1.22.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2563,7 +2846,7 @@ class preFlightsChecks: command = "pip install http://mirror.cyberpanel.net/requests-2.18.4.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2597,16 +2880,16 @@ class preFlightsChecks: try: command = "pip uninstall --yes pyOpenSSL" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) command = "pip uninstall --yes certbot" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) count = 0 while (1): command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/pyOpenSSL-17.5.0.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2626,7 +2909,7 @@ class preFlightsChecks: while (1): command = "pip install http://" + preFlightsChecks.cyberPanelMirror + "/certbot-0.21.1.tar.gz" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2667,7 +2950,7 @@ class preFlightsChecks: while (1): command = "pip install tldextract" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2706,7 +2989,7 @@ class preFlightsChecks: command = 'apt-get -y install opendkim' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2723,13 +3006,13 @@ class preFlightsChecks: if self.distro == ubuntu: try: command = 'apt install opendkim-tools' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except: pass try: command = 'mkdir -p /etc/opendkim/keys/' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except: pass @@ -2789,15 +3072,15 @@ milter_default_action = accept #### Restarting Postfix and OpenDKIM command = "systemctl start opendkim" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "systemctl enable opendkim" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) ## command = "systemctl start postfix" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except OSError, msg: logging.InstallLog.writeToFile(str(msg) + " [configureOpenDKIM]") @@ -2814,7 +3097,7 @@ milter_default_action = accept while (1): command = "pip install dnspython" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2836,7 +3119,7 @@ milter_default_action = accept count = 0 while (1): command = "ln -s /usr/local/CyberCP/cli/cyberPanel.py /usr/bin/cyberpanel" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -2851,7 +3134,7 @@ milter_default_action = accept break command = "chmod +x /usr/local/CyberCP/cli/cyberPanel.py" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) except OSError, msg: logging.InstallLog.writeToFile(str(msg) + " [setupCLI]") @@ -2872,17 +3155,17 @@ milter_default_action = accept os.symlink('/usr/local/lsws/lsphp72/bin/php7.2', '/usr/local/lsws/lsphp72/bin/php') command = "cp /usr/local/lsws/lsphp71/bin/php /usr/bin/" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) os.chdir(self.cwd) command = "chmod +x composer.sh" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) command = "./composer.sh" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) except OSError, msg: logging.InstallLog.writeToFile(str(msg) + " [setupPHPAndComposer]") @@ -2890,7 +3173,7 @@ milter_default_action = accept @staticmethod def installOne(package): - res = ProcessUtilities.executioner(shlex.split('apt-get -y install ' + package)) + res = subprocess.call(shlex.split('apt-get -y install ' + package)) if res != 0: preFlightsChecks.stdOut("Error #" + str(res) + ' installing:' + package + '. This may not be an issue ' \ 'but may affect installation of something later', @@ -2938,7 +3221,7 @@ milter_default_action = accept else: while (1): command = "yum install -y libattr-devel xz-devel gpgme-devel mariadb-devel curl-devel" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(distro, res): count = count + 1 @@ -2960,7 +3243,7 @@ milter_default_action = accept count = 0 while (1): command = "pip install virtualenv" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(distro, res): count = count + 1 @@ -2981,7 +3264,7 @@ milter_default_action = accept count = 0 while (1): command = "virtualenv --system-site-packages /usr/local/CyberCP" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(distro, res): count = count + 1 @@ -3000,7 +3283,7 @@ milter_default_action = accept ## env_path = '/usr/local/CyberCP' - ProcessUtilities.executioner(['virtualenv', env_path]) + subprocess.call(['virtualenv', env_path]) activate_this = os.path.join(env_path, 'bin', 'activate_this.py') execfile(activate_this, dict(__file__=activate_this)) @@ -3023,7 +3306,7 @@ milter_default_action = accept count = 0 while (1): command = "pip install --ignore-installed -r " + install_file - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if preFlightsChecks.resFailed(distro, res): count = count + 1 @@ -3039,10 +3322,10 @@ milter_default_action = accept break command = "systemctl restart gunicorn.socket" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) command = "virtualenv --system-site-packages /usr/local/CyberCP" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) @@ -3058,10 +3341,10 @@ milter_default_action = accept if state == 'Off': command = 'sudo systemctl stop pdns' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = 'sudo systemctl disable pdns' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) try: os.remove(servicePath) @@ -3084,10 +3367,10 @@ milter_default_action = accept if state == 'Off': command = 'sudo systemctl stop postfix' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = 'sudo systemctl disable postfix' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) try: os.remove(servicePath) @@ -3110,10 +3393,10 @@ milter_default_action = accept if state == 'Off': command = 'sudo systemctl stop ' + preFlightsChecks.pureFTPDServiceName(distro) - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = 'sudo systemctl disable ' + preFlightsChecks.pureFTPDServiceName(distro) - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) try: os.remove(servicePath) @@ -3128,172 +3411,15 @@ milter_default_action = accept logging.InstallLog.writeToFile(str(msg) + " [enableDisableEmail]") return 0 - def setupComodoRules(self): - try: - - os.chdir(self.cwd) - - extractLocation = "/usr/local/lscp/modsec" - - command = "mkdir -p /usr/local/lscp/modsec" - ProcessUtilities.executioner(shlex.split(command)) - - try: - if os.path.exists('comodo.tar.gz'): - os.remove('comodo.tar.gz') - except: - pass - - command = "wget https://cyberpanel.net/modsec/comodo.tar.gz" - result = ProcessUtilities.executioner(shlex.split(command)) - - if result == 1: - return 0 - - command = "tar -zxf comodo.tar.gz -C /usr/local/lscp/modsec" - result = ProcessUtilities.executioner(shlex.split(command)) - - ### - - modsecConfPath = "/usr/local/lscp/conf/myconf.conf" - - modsecConfig = """ -module mod_security { -modsecurity on -modsecurity_rules ` -SecDebugLogLevel 0 -SecDebugLog /usr/local/lscp/logs/modsec.log -SecAuditEngine on -SecAuditLogRelevantStatus "^(?:5|4(?!04))" -SecAuditLogParts AFH -SecAuditLogType Serial -SecAuditLog /usr/local/lscp/logs/auditmodsec.log -SecRuleEngine On -` - modsecurity_rules_file /usr/local/lscp/modsec/comodo/modsecurity.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/00_Init_Initialization.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/01_Init_AppsInitialization.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/02_Global_Generic.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/03_Global_Agents.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/04_Global_Domains.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/05_Global_Backdoor.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/06_XSS_XSS.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/07_Global_Other.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/08_Bruteforce_Bruteforce.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/09_HTTP_HTTP.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/10_HTTP_HTTPDoS.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/11_HTTP_Protocol.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/12_HTTP_Request.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/13_Outgoing_FilterGen.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/14_Outgoing_FilterASP.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/15_Outgoing_FilterPHP.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/16_Outgoing_FilterSQL.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/17_Outgoing_FilterOther.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/18_Outgoing_FilterInFrame.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/19_Outgoing_FiltersEnd.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/20_PHP_PHPGen.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/21_SQL_SQLi.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/22_Apps_Joomla.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/23_Apps_JComponent.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/24_Apps_WordPress.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/25_Apps_WPPlugin.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/26_Apps_WHMCS.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/27_Apps_Drupal.conf - modsecurity_rules_file /usr/local/lscp/modsec/comodo/28_Apps_OtherApps.conf -} -""" - - writeToFile = open(modsecConfPath, 'w') - writeToFile.write(modsecConfig) - writeToFile.close() - - ### - - command = "chown -R lscpd:lscpd /usr/local/lscp/modsec" - ProcessUtilities.executioner(shlex.split(command)) - - return 1 - - except BaseException, msg: - preFlightsChecks.stdOut("[Failed:setupComodoRules] " + str(msg)) - return 0 - - def setupPort(self, port): - try: - ### - bindConfPath = "/usr/local/lscp/conf/bind.conf" - - writeToFile = open(bindConfPath, 'w') - writeToFile.write(port) - writeToFile.close() - - ### - - command = "chown -R lscpd:lscpd /usr/local/lscp/modsec" - ProcessUtilities.executioner(shlex.split(command)) - - return 1 - - except: - return 0 - @staticmethod def setUpFirstAccount(): try: command = 'python /usr/local/CyberCP/plogical/adminPass.py --password 1234567' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except: pass -def get_distro(): - distro = -1 - distro_file = "" - if exists("/etc/lsb-release"): - distro_file = "/etc/lsb-release" - with open(distro_file) as f: - for line in f: - if line == "DISTRIB_ID=Ubuntu\n": - distro = ubuntu - - elif exists("/etc/os-release"): - distro_file = "/etc/os-release" - distro = centos - - else: - logging.InstallLog.writeToFile("Can't find linux release file - fatal error") - preFlightsChecks.stdOut("Can't find linux release file - fatal error") - os._exit(os.EX_UNAVAILABLE) - - if distro == -1: - logging.InstallLog.writeToFile("Can't find distro name in " + distro_file + " - fatal error") - preFlightsChecks.stdOut("Can't find distro name in " + distro_file + " - fatal error") - os._exit(os.EX_UNAVAILABLE) - - return distro - - -def get_Ubuntu_release(): - release = -1 - if exists("/etc/lsb-release"): - distro_file = "/etc/lsb-release" - with open(distro_file) as f: - for line in f: - if line[:16] == "DISTRIB_RELEASE=": - release = float(line[16:]) - - if release == -1: - preFlightsChecks.stdOut("Can't find distro release name in " + distro_file + " - fatal error", 1, 1, - os.EX_UNAVAILABLE) - - else: - logging.InstallLog.writeToFile("Can't find linux release file - fatal error") - preFlightsChecks.stdOut("Can't find linux release file - fatal error") - os._exit(os.EX_UNAVAILABLE) - - return release - - def main(): parser = argparse.ArgumentParser(description='CyberPanel Installer') parser.add_argument('publicip', help='Please enter public IP for your VPS or dedicated server.') @@ -3303,7 +3429,7 @@ def main(): parser.add_argument('--ftp', help='Enable or disable ftp Service.') parser.add_argument('--ent', help='Install LS Ent or OpenLiteSpeed') parser.add_argument('--serial', help='Install LS Ent or OpenLiteSpeed') - parser.add_argument('--port', help='Install LS Ent or OpenLiteSpeed') + parser.add_argument('--port', help='LSCPD Port') args = parser.parse_args() logging.InstallLog.writeToFile("Starting CyberPanel installation..") @@ -3326,11 +3452,6 @@ def main(): preFlightsChecks.stdOut("Installation failed, please specify LiteSpeed Enterprise key using --serial") os._exit(0) - if args.port == None: - port = "8090" - else: - port = args.port - ## Writing public IP try: @@ -3351,6 +3472,11 @@ def main(): if distro == ubuntu: os.chdir("/etc/cyberpanel") + if args.port == None: + port = "8090" + else: + port = args.port + if args.mysql == None: mysql = 'One' preFlightsChecks.stdOut("Single MySQL instance version will be installed.") @@ -3379,10 +3505,12 @@ def main(): import installCyberPanel if ent == 0: - installCyberPanel.Main(cwd, mysql, distro, ent) + installCyberPanel.Main(cwd, mysql, distro, ent, port) else: - installCyberPanel.Main(cwd, mysql, distro, ent, serial) + installCyberPanel.Main(cwd, mysql, distro, ent, serial, port) + checks.installLSCPD() + checks.setupLSCPDDaemon() checks.setupPHPAndComposer() checks.fix_selinux_issue() checks.install_psmisc() @@ -3398,7 +3526,7 @@ def main(): checks.installFirewalld() - checks.setupLSCPDDaemon() + checks.install_python_requests() checks.install_default_keys() @@ -3416,11 +3544,10 @@ def main(): checks.installOpenDKIM() checks.configureOpenDKIM() - checks.setupComodoRules() - checks.setupPort(port) checks.modSecPreReqs() checks.setupVirtualEnv(distro) + checks.fixCyberPanelPermissions() if args.postfix != None: @@ -3441,6 +3568,7 @@ def main(): preFlightsChecks.stdOut("Pure-FTPD will be installed and enabled.") checks.enableDisableFTP('On', distro) + checks.setUpFirstAccount() logging.InstallLog.writeToFile("CyberPanel installation successfully completed!") checks.installation_successfull() diff --git a/install/installCyberPanel.py b/install/installCyberPanel.py index 902b33c5a..736ab1e31 100644 --- a/install/installCyberPanel.py +++ b/install/installCyberPanel.py @@ -18,12 +18,13 @@ class InstallCyberPanel: mysql_Root_password = "" mysqlPassword = "" - def __init__(self, rootPath, cwd, distro, ent, serial = None): + def __init__(self, rootPath, cwd, distro, ent, serial = None, port = None): self.server_root_path = rootPath self.cwd = cwd self.distro = distro self.ent = ent self.serial = serial + self.port = port @staticmethod def stdOut(message, log=0, exit=0, code=os.EX_OK): @@ -337,7 +338,7 @@ class InstallCyberPanel: while (1): command = "systemctl start mysqld@1" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if install.preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -357,7 +358,7 @@ class InstallCyberPanel: while (1): command = "systemctl enable mysqld@1" - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if install.preFlightsChecks.resFailed(self.distro, res): count = count + 1 @@ -546,7 +547,7 @@ class InstallCyberPanel: shutil.copy(ftpdPath + "/pureftpd-mysql.conf", '/etc/pure-ftpd/db/mysql.conf') command = 'echo 1 > /etc/pure-ftpd/conf/TLS' - ProcessUtilities.executioner(command, shell=True) + subprocess.call(command, shell=True) command = 'systemctl restart pure-ftpd-mysql.service' install.preFlightsChecks.call(command, self.distro, '[installPureFTPDConfigurations]', @@ -565,12 +566,12 @@ class InstallCyberPanel: if self.distro == ubuntu: command = 'systemctl stop systemd-resolved' - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if res != 0: InstallCyberPanel.stdOut('Unable to stop systemd.resolved, prohits install of PowerDNS, error #' + str(res), 1, 1, os.EX_OSERR) command = 'systemctl disable systemd-resolved.service' - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if res != 0: InstallCyberPanel.stdOut( 'Unable to disable systemd.resolved, prohits install of PowerDNS, error #' + @@ -684,83 +685,6 @@ class InstallCyberPanel: except BaseException, msg: logging.InstallLog.writeToFile(str(msg) + " [startPowerDNS]") - def installLSCPD(self): - try: - - InstallCyberPanel.stdOut("Starting LSCPD installation..", 1) - - os.chdir(self.cwd) - - if self.distro == ubuntu: - command = "apt-get -y install gcc g++ make autoconf rcs" - else: - command = 'yum -y install gcc gcc-c++ make autoconf glibc rcs' - - install.preFlightsChecks.call(command, self.distro, '[installLSCPD]', - 'Install LSCPD', - 1, 1, os.EX_OSERR) - - if self.distro == ubuntu: - command = "apt-get -y install libpcre3 libpcre3-dev openssl libexpat1 libexpat1-dev libgeoip-dev" \ - " zlib1g zlib1g-dev libudns-dev whichman curl" - else: - command = 'yum -y install pcre-devel openssl-devel expat-devel geoip-devel zlib-devel udns-devel' \ - ' which curl' - install.preFlightsChecks.call(command, self.distro, '[installLSCPD]', - 'Install LSCPD', - 1, 1, os.EX_OSERR) - - - command = 'tar zxf lscp.tar.gz -C /usr/local/' - install.preFlightsChecks.call(command, self.distro, '[installLSCPD]', - 'Install LSCPD', - 1, 1, os.EX_OSERR) - - - command = 'openssl req -newkey rsa:1024 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout /usr/local/lscp/key.pem -out /usr/local/lscp/cert.pem' - install.preFlightsChecks.call(command, self.distro, '[installLSCPD]', - 'Install LSCPD', - 1, 1, os.EX_OSERR) - - try: - os.remove("/usr/local/lscp/fcgi-bin/lsphp") - shutil.copy("/usr/local/lsws/lsphp70/bin/lsphp","/usr/local/lscp/fcgi-bin/lsphp") - except: - pass - - if self.distro == centos: - command = 'adduser lscpd -M -d /usr/local/lscp' - else: - command = 'useradd lscpd -M -d /usr/local/lscp' - - install.preFlightsChecks.call(command, self.distro, '[installLSCPD]', - 'Install LSCPD', - 1, 0, os.EX_OSERR) - - if self.distro == centos: - command = 'groupadd lscpd' - install.preFlightsChecks.call(command, self.distro, '[installLSCPD]', - 'Install LSCPD', - 1, 0, os.EX_OSERR) - # Added group in useradd for Ubuntu - - command = 'usermod -a -G lscpd lscpd' - install.preFlightsChecks.call(command, self.distro, '[installLSCPD]', - 'Install LSCPD', - 1, 0, os.EX_OSERR) - - command = 'usermod -a -G lsadm lscpd' - install.preFlightsChecks.call(command, self.distro, '[installLSCPD]', - 'Install LSCPD', - 1, 0, os.EX_OSERR) - - os.mkdir('/usr/local/lscp/cyberpanel') - - InstallCyberPanel.stdOut("LSCPD successfully installed!", 1) - - except BaseException, msg: - logging.InstallLog.writeToFile(str(msg) + " [startPowerDNS]") - def Main(cwd, mysql, distro, ent, serial = None): @@ -809,6 +733,4 @@ def Main(cwd, mysql, distro, ent, serial = None): installer.installPowerDNS() installer.installPowerDNSConfigurations(InstallCyberPanel.mysqlPassword, mysql) - installer.startPowerDNS() - - installer.installLSCPD() \ No newline at end of file + installer.startPowerDNS() \ No newline at end of file diff --git a/install/lscp.tar.gz b/install/lscp.tar.gz index 705445bfc..c346f5bee 100644 Binary files a/install/lscp.tar.gz and b/install/lscp.tar.gz differ diff --git a/install/mysqlUtilities.py b/install/mysqlUtilities.py index 7d9bc6ee2..bdab9c3d4 100644 --- a/install/mysqlUtilities.py +++ b/install/mysqlUtilities.py @@ -19,7 +19,7 @@ class mysqlUtilities: command = 'mysql -u root -p' + password + ' -e "' + createDB + '"' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: return 0 @@ -29,7 +29,7 @@ class mysqlUtilities: command = 'mysql -u root -p' + password + ' -e "' + createUser + '"' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: return 0 @@ -37,7 +37,7 @@ class mysqlUtilities: dropDB = "GRANT ALL PRIVILEGES ON " + dbname + ".* TO '" + dbuser + "'@'localhost'" command = 'mysql -u root -p' + password + ' -e "' + dropDB + '"' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: return 0 diff --git a/install/test.py b/install/test.py index 9ec32ec81..a4ef8ee01 100644 --- a/install/test.py +++ b/install/test.py @@ -9,7 +9,7 @@ def installCertBot(): cmd.append("install") cmd.append("certbot") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) installCertBot() \ No newline at end of file diff --git a/install/unInstall.py b/install/unInstall.py index 794456d35..5d14440c1 100644 --- a/install/unInstall.py +++ b/install/unInstall.py @@ -44,7 +44,7 @@ class unInstallCyberPanel: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) shutil.rmtree("/etc/postfix") shutil.rmtree("etc/dovecot") @@ -66,7 +66,7 @@ class unInstallCyberPanel: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) shutil.rmtree("/var/lib/mysql") os.remove("/etc/my.cnf") @@ -88,7 +88,7 @@ class unInstallCyberPanel: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) shutil.rmtree("/usr/local/lsws") @@ -122,7 +122,7 @@ class unInstallCyberPanel: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) shutil.rmtree("/etc/pure-ftpd") @@ -141,7 +141,7 @@ class unInstallCyberPanel: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) shutil.rmtree("/etc/pdns") @@ -160,7 +160,7 @@ class unInstallCyberPanel: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) shutil.rmtree("/etc/pdns") diff --git a/loginSystem/views.py b/loginSystem/views.py index 6ae88bfc6..cf66976fc 100644 --- a/loginSystem/views.py +++ b/loginSystem/views.py @@ -181,6 +181,30 @@ def loadLoginPage(request): newFWRule = FirewallRules(name="ftp", proto="tcp", port="21") newFWRule.save() + newFWRule = FirewallRules(name="smtp", proto="tcp", port="25") + newFWRule.save() + + newFWRule = FirewallRules(name="smtps", proto="tcp", port="587") + newFWRule.save() + + newFWRule = FirewallRules(name="ssmtp", proto="tcp", port="465") + newFWRule.save() + + newFWRule = FirewallRules(name="pop3", proto="tcp", port="110") + newFWRule.save() + + newFWRule = FirewallRules(name="imap", proto="tcp", port="143") + newFWRule.save() + + newFWRule = FirewallRules(name="simap", proto="tcp", port="993") + newFWRule.save() + + newFWRule = FirewallRules(name="dns", proto="udp", port="53") + newFWRule.save() + + newFWRule = FirewallRules(name="dnstcp", proto="tcp", port="53") + newFWRule.save() + newFWRule = FirewallRules(name="ftptls", proto="tcp", port="40110-40210") newFWRule.save() diff --git a/mailServer/mailserverManager.py b/mailServer/mailserverManager.py index ba214f82b..9d8c55b5c 100644 --- a/mailServer/mailserverManager.py +++ b/mailServer/mailserverManager.py @@ -23,6 +23,7 @@ from plogical.acl import ACLManager import os from plogical.dnsUtilities import DNS from loginSystem.models import Administrator +from plogical.processUtilities import ProcessUtilities class MailServerManager: @@ -76,7 +77,7 @@ class MailServerManager: execPath = execPath + " createEmailAccount --domain " + domainName + " --userName " \ + userName + " --password " + password - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'status': 1, 'createEmailStatus': 1, 'error_message': "None"} @@ -391,13 +392,13 @@ class MailServerManager: try: path = "/etc/opendkim/keys/" + domainName + "/default.txt" command = "sudo cat " + path - output = ProcessUtilities.outputExecutioner(shlex.split(command)) + output = ProcessUtilities.outputExecutioner(command) leftIndex = output.index('(') + 2 rightIndex = output.rindex(')') - 1 path = "/etc/opendkim/keys/" + domainName + "/default.private" command = "sudo cat " + path - privateKey = ProcessUtilities.outputExecutioner(shlex.split(command)) + privateKey = ProcessUtilities.outputExecutioner(command) data_ret = {'status': 1, 'fetchStatus': 1, 'keysAvailable': 1, 'publicKey': output[leftIndex:rightIndex], 'privateKey': privateKey, 'dkimSuccessMessage': 'Keys successfully fetched!', @@ -428,7 +429,7 @@ class MailServerManager: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" execPath = execPath + " generateKeys --domain " + domainName - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) admin = Administrator.objects.get(pk=userID) DNS.dnsTemplate(domainName, admin) @@ -444,7 +445,7 @@ class MailServerManager: path = "/etc/opendkim/keys/" + domainName + "/default.txt" command = "sudo cat " + path - output = ProcessUtilities.outputExecutioner(shlex.split(command)) + output = ProcessUtilities.outputExecutioner(command) leftIndex = output.index('(') + 2 rightIndex = output.rindex(')') - 1 @@ -492,15 +493,14 @@ class MailServerManager: def installStatusOpenDKIM(self): try: command = "sudo cat " + mailUtilities.installLogPath - installStatus = ProcessUtilities.outputExecutioner(shlex.split(command)) + installStatus = subprocess.check_output(shlex.split(command)) if installStatus.find("[200]") > -1: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py" - execPath = execPath + " configureOpenDKIM" - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: pass diff --git a/managePHP/views.py b/managePHP/views.py index a99dd1cd1..5f57d3690 100644 --- a/managePHP/views.py +++ b/managePHP/views.py @@ -1273,10 +1273,13 @@ def submitExtensionRequest(request): type = data['type'] if type == "install": - phpUtilities.initiateInstall(extensionName) - + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/phpUtilities.py" + execPath = execPath + " installPHPExtension --extension " + extensionName else: - phpUtilities.initiateRemoval(extensionName) + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/phpUtilities.py" + execPath = execPath + " unInstallPHPExtension --extension " + extensionName + + ProcessUtilities.popenExecutioner(execPath) final_json = json.dumps({'extensionRequestStatus': 1, 'error_message': "None"}) return HttpResponse(final_json) @@ -1448,7 +1451,8 @@ def getCurrentPHPConfig(request): upload_max_filesize = "" max_input_time = "" - data = open(path, 'r').readlines() + command = "sudo cat " + path + data = ProcessUtilities.outputExecutioner(command).split('\n') for items in data: if items.find("allow_url_fopen") > -1 and items.find("=") > -1: @@ -1549,10 +1553,9 @@ def savePHPConfigBasic(request): ## execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/phpUtilities.py" - execPath = execPath + " savePHPConfigBasic --phpVers " + phpVers + " --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 - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'saveStatus': 1} @@ -1598,7 +1601,8 @@ def getCurrentAdvancedPHPConfig(request): completeName = str(initial) + '.' + str(final) path = "/usr/local/lsws/ls" + phpVers + "/etc/php/" + completeName + "/litespeed/php.ini" - configData = open(path, "r").read() + command = "sudo cat " + path + configData = ProcessUtilities.outputExecutioner(command) status = {"fetchStatus": 1, "configData": configData} final_json = json.dumps(status) @@ -1641,16 +1645,13 @@ def savePHPConfigAdvance(request): tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) vhost = open(tempPath, "w") - vhost.write(data['configData']) - vhost.close() execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/phpUtilities.py" - execPath = execPath + " savePHPConfigAdvance --phpVers " + path + " --tempPath " + tempPath - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: status = {"saveStatus": 1, "configData": data['configData']} diff --git a/manageSSL/views.py b/manageSSL/views.py index f0aa267aa..01f3b798d 100644 --- a/manageSSL/views.py +++ b/manageSSL/views.py @@ -12,6 +12,7 @@ import shlex import subprocess from plogical.acl import ACLManager from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging +from plogical.processUtilities import ProcessUtilities # Create your views here. @@ -76,7 +77,7 @@ def issueSSL(request): execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" execPath = execPath + " issueSSL --virtualHostName " + virtualHost + " --administratorEmail " + adminEmail + " --path " + path - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: pass @@ -148,10 +149,8 @@ def obtainHostNameSSL(request): ## ssl issue execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " issueSSLForHostName --virtualHostName " + virtualHost + " --path " + path - - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {"status": 1, "SSL": 1, @@ -218,10 +217,8 @@ def obtainMailServerSSL(request): ## ssl issue execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " issueSSLForMailServer --virtualHostName " + virtualHost + " --path " + path - - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {"status": 1, "SSL": 1, diff --git a/manageServices/serviceManager.py b/manageServices/serviceManager.py index e2de90d4d..a78dd1105 100644 --- a/manageServices/serviceManager.py +++ b/manageServices/serviceManager.py @@ -12,7 +12,7 @@ class ServiceManager: type = self.extraArgs['type'] path = '/etc/pdns/pdns.conf' - data = ProcessUtilities.outputExecutioner(shlex.split('sudo cat ' + path)).splitlines() + data = subprocess.check_output(shlex.split('sudo cat ' + path)).splitlines() if type == 'MASTER': counter = 0 diff --git a/manageServices/views.py b/manageServices/views.py index fd13e15b8..d9d4f0f36 100644 --- a/manageServices/views.py +++ b/manageServices/views.py @@ -12,6 +12,7 @@ import subprocess, shlex from plogical.acl import ACLManager from models import PDNSStatus from .serviceManager import ServiceManager +from plogical.processUtilities import ProcessUtilities # Create your views here. @@ -174,10 +175,10 @@ def saveStatus(request): sm.managePDNS() command = 'sudo systemctl enable pdns' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo systemctl restart pdns' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) else: @@ -186,10 +187,10 @@ def saveStatus(request): pdns.save() command = 'sudo systemctl stop pdns' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo systemctl disable pdns' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) elif service == 'postfix': @@ -199,13 +200,13 @@ def saveStatus(request): writeToFile = open(servicePath, 'w+') writeToFile.close() command = 'sudo systemctl start postfix' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) else: command = 'sudo systemctl stop postfix' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo systemctl disable postfix' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) try: os.remove(servicePath) @@ -223,13 +224,13 @@ def saveStatus(request): writeToFile = open(servicePath, 'w+') writeToFile.close() command = 'sudo systemctl start ' + serviceName - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) else: command = 'sudo systemctl stop ' + serviceName - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo systemctl disable ' + serviceName - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) try: os.remove(servicePath) diff --git a/plogical/CyberCPLogFileWriter.py b/plogical/CyberCPLogFileWriter.py index b93c2eb79..15f991e94 100644 --- a/plogical/CyberCPLogFileWriter.py +++ b/plogical/CyberCPLogFileWriter.py @@ -31,7 +31,7 @@ class CyberCPLogFileWriter: def readLastNFiles(numberOfLines,fileName): try: - lastFewLines = ProcessUtilities.outputExecutioner(["tail", "-n",str(numberOfLines),fileName]) + lastFewLines = subprocess.check_output(["tail", "-n",str(numberOfLines),fileName]) return lastFewLines diff --git a/plogical/applicationInstaller.py b/plogical/applicationInstaller.py index 392b5fd92..503661159 100644 --- a/plogical/applicationInstaller.py +++ b/plogical/applicationInstaller.py @@ -16,7 +16,7 @@ from databases.models import Databases from installUtilities import installUtilities import shutil from plogical.mailUtilities import mailUtilities - +from plogical.processUtilities import ProcessUtilities class ApplicationInstaller(multi.Thread): @@ -48,13 +48,13 @@ class ApplicationInstaller(multi.Thread): def installWPCLI(self): try: command = 'sudo wget https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo chmod +x wp-cli.phar' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo mv wp-cli.phar /usr/bin/wp' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) except BaseException, msg: logging.writeToFile( str(msg) + ' [ApplicationInstaller.installWPCLI]') @@ -94,13 +94,13 @@ class ApplicationInstaller(multi.Thread): try: if os.path.exists("/etc/lsb-release"): command = 'apt -y install git' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) else: command = 'sudo yum -y install http://repo.iotti.biz/CentOS/7/noarch/lux-release-7-1.noarch.rpm' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo yum install git -y' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) except BaseException, msg: logging.writeToFile( str(msg) + ' [ApplicationInstaller.installGit]') @@ -158,9 +158,9 @@ class ApplicationInstaller(multi.Thread): try: command = 'sudo wp --info' - res = ProcessUtilities.executioner(shlex.split(command)) + res = ProcessUtilities.executioner(command) - if res == 1: + if res == 0: self.installWPCLI() except subprocess.CalledProcessError: self.installWPCLI() @@ -235,7 +235,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(finalPath): command = 'sudo mkdir -p ' + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## checking for directories/files @@ -249,7 +249,7 @@ class ApplicationInstaller(multi.Thread): statusFile.close() command = "sudo wp core download --allow-root --path=" + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## @@ -258,7 +258,7 @@ class ApplicationInstaller(multi.Thread): statusFile.close() command = "sudo wp core config --dbname=" + dbName + " --dbuser=" + dbUser + " --dbpass=" + dbPassword + " --dbhost=localhost --dbprefix=wp_ --allow-root --path=" + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) if home == '0': path = self.extraArgs['path'] @@ -267,7 +267,7 @@ class ApplicationInstaller(multi.Thread): finalURL = domainName command = 'sudo wp core install --url="http://' + finalURL + '" --title="' + blogTitle + '" --admin_user="' + adminUser + '" --admin_password="' + adminPassword + '" --admin_email="' + adminEmail + '" --allow-root --path=' + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## @@ -276,21 +276,20 @@ class ApplicationInstaller(multi.Thread): statusFile.close() command = "sudo wp plugin install litespeed-cache --allow-root --path=" + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) statusFile = open(tempStatusPath, 'w') statusFile.writelines('Activating LSCache Plugin,90') statusFile.close() command = "sudo wp plugin activate litespeed-cache --allow-root --path=" + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) statusFile = open(tempStatusPath, 'w') statusFile.writelines("Successfully Installed. [200]") @@ -307,8 +306,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(homeDir): command = "sudo chown -R " + externalApp + ":" + externalApp + " " + homeDir - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) try: mysqlUtilities.deleteDatabase(dbName, dbUser) @@ -406,7 +404,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(finalPath): command = 'sudo mkdir -p ' + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## checking for directories/files @@ -420,13 +418,13 @@ class ApplicationInstaller(multi.Thread): statusFile.close() command = "sudo wget https://download.prestashop.com/download/releases/prestashop_1.7.4.2.zip" - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = "sudo unzip -o prestashop_1.7.4.2.zip -d " + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = "sudo unzip -o " + finalPath + "prestashop.zip -d " + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## @@ -449,22 +447,20 @@ class ApplicationInstaller(multi.Thread): " --db_server=localhost --db_name=" + dbName + " --db_user=" + dbUser + " --db_password=" + dbPassword \ + " --name='" + shopName + "' --firstname=" + firstName + " --lastname=" + lastName + \ " --email=" + email + " --password=" + password - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## command = "sudo rm -rf " + finalPath + "install" - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) command = "sudo rm -f prestashop_1.7.4.2.zip" - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) statusFile = open(tempStatusPath, 'w') statusFile.writelines("Successfully Installed. [200]") @@ -479,8 +475,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(homeDir): command = "sudo chown -R " + externalApp + ":" + externalApp + " " + homeDir - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) try: mysqlUtilities.deleteDatabase(dbName, dbUser) @@ -512,9 +507,9 @@ class ApplicationInstaller(multi.Thread): try: command = 'sudo git --help' - res = ProcessUtilities.executioner(shlex.split(command)) + res = ProcessUtilities.executioner(command) - if res == 1: + if res == 0: statusFile = open(tempStatusPath, 'w') statusFile.writelines('Installing GIT..,0') statusFile.close() @@ -561,7 +556,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(finalPath): command = 'sudo mkdir -p ' + finalPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## checking for directories/files @@ -578,8 +573,7 @@ class ApplicationInstaller(multi.Thread): try: command = 'sudo GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=no" git clone --depth 1 --no-single-branch git@' + defaultProvider +'.com:' + username + '/' + reponame + '.git -b ' + branch + ' ' + finalPath - logging.writeToFile(command) - ProcessUtilities.outputExecutioner(shlex.split(command)) + ProcessUtilities.executioner(command) except subprocess.CalledProcessError, msg: statusFile = open(tempStatusPath, 'w') statusFile.writelines('Failed to clone repository, make sure you deployed your key to repository. [404]') @@ -589,8 +583,7 @@ class ApplicationInstaller(multi.Thread): ## command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) vhost.addRewriteRules(domainName) installUtilities.reStartLiteSpeed() @@ -633,7 +626,7 @@ class ApplicationInstaller(multi.Thread): return 0 command = 'sudo git --git-dir=' + finalPath + '.git --work-tree=' + finalPath +' pull' - ProcessUtilities.outputExecutioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## @@ -641,8 +634,7 @@ class ApplicationInstaller(multi.Thread): externalApp = website.externalApp command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - cmd = shlex.split(command) - ProcessUtilities.executioner(cmd) + ProcessUtilities.executioner(command) return 0 @@ -674,16 +666,15 @@ class ApplicationInstaller(multi.Thread): command = 'sudo rm -rf ' + finalPath - ProcessUtilities.outputExecutioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo mkdir ' + finalPath - ProcessUtilities.outputExecutioner(shlex.split(command)) + ProcessUtilities.executioner(command) ## command = "sudo chown -R " + externalApp + ":" + externalApp + " " + finalPath - cmd = shlex.split(command) - ProcessUtilities.executioner(cmd) + ProcessUtilities.executioner(command) gitPath = '/home/cyberpanel/' + domain + '.git' @@ -730,8 +721,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists("staging.zip"): command = 'wget --no-check-certificate https://github.com/joomla/joomla-cms/archive/staging.zip -P ' + finalPath - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) else: statusFile = open(tempStatusPath, 'w') statusFile.writelines("File already exists." + " [404]") @@ -739,14 +729,12 @@ class ApplicationInstaller(multi.Thread): return 0 command = 'unzip ' + finalPath + 'staging.zip -d ' + finalPath - cmd = shlex.split(command) + ProcessUtilities.executioner(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) os.remove(finalPath + 'staging.zip') command = 'cp -r ' + finalPath + 'joomla-cms-staging/. ' + finalPath - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) shutil.rmtree(finalPath + "joomla-cms-staging") os.rename(finalPath + "installation/configuration.php-dist", finalPath + "configuration.php") @@ -816,7 +804,7 @@ class ApplicationInstaller(multi.Thread): f2.close() # Restore SQL - proc = ProcessUtilities.popenExecutioner(["mysql", "--user=%s" % dbUser, "--password=%s" % dbPassword, dbName], + proc = subprocess.Popen(["mysql", "--user=%s" % dbUser, "--password=%s" % dbPassword, dbName], stdin=subprocess.PIPE, stdout=subprocess.PIPE) usercreation = """INSERT INTO `%susers` @@ -832,8 +820,7 @@ class ApplicationInstaller(multi.Thread): shutil.rmtree(finalPath + "installation") command = "sudo chown -R " + virtualHostUser + ":" + virtualHostUser + " " + finalPath - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) vhost.addRewriteRules(domainName) @@ -851,8 +838,7 @@ class ApplicationInstaller(multi.Thread): if not os.path.exists(homeDir): command = "sudo chown -R " + virtualHostUser + ":" + virtualHostUser + " " + homeDir - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) try: mysqlUtilities.deleteDatabase(dbName, dbUser) @@ -881,11 +867,11 @@ class ApplicationInstaller(multi.Thread): try: command = 'sudo git --git-dir=' + finalPath + '/.git checkout -b ' + githubBranch - ProcessUtilities.outputExecutioner(shlex.split(command)) + ProcessUtilities.executioner(command) except: try: command = 'sudo git --git-dir=' + finalPath + '/.git checkout ' + githubBranch - ProcessUtilities.outputExecutioner(shlex.split(command)) + ProcessUtilities.executioner(command) except subprocess.CalledProcessError, msg: logging.writeToFile('Failed to change branch: ' + str(msg)) return 0 diff --git a/plogical/backupSchedule.py b/plogical/backupSchedule.py index ff970f1b6..c010124ee 100644 --- a/plogical/backupSchedule.py +++ b/plogical/backupSchedule.py @@ -111,7 +111,7 @@ class backupSchedule: writeToFile = open(backupLogPath, "a") command = "sudo scp -o StrictHostKeyChecking=no -P "+port+" -i /root/.ssh/cyberpanel " + backupPath + " root@"+IPAddress+":/home/backup/" + ipAddressLocal + "/" + time.strftime("%a-%b") + "/" - ProcessUtilities.executioner(shlex.split(command), stdout=writeToFile) + subprocess.call(shlex.split(command), stdout=writeToFile) ## Remove backups already sent to remote destinations @@ -162,7 +162,7 @@ class backupSchedule: command = "sudo ssh -o StrictHostKeyChecking=no -p " + port + " -i /root/.ssh/cyberpanel root@" + ipAddress + " mkdir -p /home/backup/" + ipAddressLocal + "/" + time.strftime( "%a-%b") - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) pass for virtualHost in os.listdir("/home"): diff --git a/plogical/backupUtilities.py b/plogical/backupUtilities.py index 4ee2bb034..318cbfd8d 100644 --- a/plogical/backupUtilities.py +++ b/plogical/backupUtilities.py @@ -638,7 +638,7 @@ class backupUtilities: ## Change permissions command = "chmod -r vmail:vmail " + emailHome - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except: pass @@ -656,7 +656,7 @@ class backupUtilities: command = "chown -R " + externalApp + ":" + externalApp + " " + websiteHome cmd = shlex.split(command) - ProcessUtilities.executioner(cmd) + subprocess.call(cmd) except BaseException, msg: status = os.path.join(completPath, 'status') @@ -778,7 +778,7 @@ class backupUtilities: @staticmethod def checkIfHostIsUp(IPAddress): try: - if ProcessUtilities.outputExecutioner(['ping', IPAddress, '-c 1']).find("0% packet loss") > -1: + if subprocess.check_output(['ping', IPAddress, '-c 1']).find("0% packet loss") > -1: return 1 else: return 0 @@ -807,22 +807,22 @@ class backupUtilities: index = checkConn.expect(expectation) if index == 0: - ProcessUtilities.executioner(['kill', str(checkConn.pid)]) + subprocess.call(['kill', str(checkConn.pid)]) logging.CyberCPLogFileWriter.writeToFile("Remote Server is not able to authenticate for transfer to initiate, IP Address:" + IPAddress) return [0,"Remote Server is not able to authenticate for transfer to initiate."] elif index == 1: - ProcessUtilities.executioner(['kill', str(checkConn.pid)]) + subprocess.call(['kill', str(checkConn.pid)]) logging.CyberCPLogFileWriter.writeToFile( "Remote Server is not able to authenticate for transfer to initiate, IP Address:" + IPAddress) return [0, "Remote Server is not able to authenticate for transfer to initiate."] elif index == 2: - ProcessUtilities.executioner(['kill', str(checkConn.pid)]) + subprocess.call(['kill', str(checkConn.pid)]) return [1, "None"] elif index == 4: - ProcessUtilities.executioner(['kill', str(checkConn.pid)]) + subprocess.call(['kill', str(checkConn.pid)]) return [1, "None"] else: - ProcessUtilities.executioner(['kill', str(checkConn.pid)]) + subprocess.call(['kill', str(checkConn.pid)]) return [1, "None"] except pexpect.TIMEOUT, msg: @@ -907,13 +907,13 @@ class backupUtilities: try: command = "sudo ssh -o StrictHostKeyChecking=no -p "+ port +" -i /root/.ssh/cyberpanel root@"+IPAddress+" mkdir /home/backup" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "sudo ssh -o StrictHostKeyChecking=no -p " + port + " -i /root/.ssh/cyberpanel root@" + IPAddress + ' "cat /root/.ssh/authorized_keys /root/.ssh/temp > /root/.ssh/authorized_temp"' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "sudo ssh -o StrictHostKeyChecking=no -p " + port + " -i /root/.ssh/cyberpanel root@" + IPAddress + ' "cat /root/.ssh/authorized_temp > /root/.ssh/authorized_keys"' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createBackupDir]") @@ -923,7 +923,7 @@ class backupUtilities: def host_key_verification(IPAddress): try: command = 'sudo ssh-keygen -R ' + IPAddress - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) return 1 except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [host_key_verification]") diff --git a/plogical/cronUtil.py b/plogical/cronUtil.py new file mode 100644 index 000000000..fc098bd32 --- /dev/null +++ b/plogical/cronUtil.py @@ -0,0 +1,190 @@ +import CyberCPLogFileWriter as logging +import subprocess +import shlex +import thread +import installUtilities +import argparse +import os +from mailUtilities import mailUtilities +from processUtilities import ProcessUtilities +from random import randint + +class CronUtil: + + @staticmethod + def getWebsiteCron(externalApp): + try: + + if ProcessUtilities.decideDistro() == ProcessUtilities.centos: + cronPath = "/var/spool/cron/" + externalApp + else: + cronPath = "/var/spool/cron/crontabs/" + externalApp + + cmd = 'sudo test -e ' + cronPath + ' && echo Exists' + output = os.popen(cmd).read() + + if "Exists" not in output: + print "0,Not Exists" + return 1 + + try: + f = subprocess.check_output(["sudo", "crontab", "-u", externalApp, "-l"]) + print f + except BaseException, msg: + print "0," + str(msg) + return 1 + + except BaseException, msg: + print "0," + str(msg) + + @staticmethod + def saveCronChanges(externalApp, finalCron, line): + try: + + tempPath = "/home/cyberpanel/" + externalApp + str(randint(10000, 99999)) + ".cron.tmp" + + output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) + + if "no crontab for" in output: + print "0,crontab file does not exists for user" + return 1 + + with open(tempPath, "w+") as file: + file.write(output) + + # Confirming that directory is read/writable + o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) + if o is not 0: + print "0,Error Changing Permissions" + return 1 + + with open(tempPath, 'r') as file: + data = file.readlines() + + data[line] = finalCron + '\n' + + with open(tempPath, 'w') as file: + file.writelines(data) + + output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", externalApp, tempPath]) + + os.remove(tempPath) + if output != 0: + print "0,Incorrect Syntax cannot be accepted." + return 1 + + print "1,None" + except BaseException, msg: + print "0," + str(msg) + + @staticmethod + def remCronbyLine(externalApp, line): + try: + line -= 1 + + output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) + + if "no crontab for" in output: + print "0,No Cron exists for this user" + return 1 + + tempPath = "/home/cyberpanel/" + externalApp + str(randint(10000, 99999)) + ".cron.tmp" + + with open(tempPath, "w+") as file: + file.write(output) + + # Confirming that directory is read/writable + o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) + if o is not 0: + print "0,Error Changing Permissions" + return 1 + + with open(tempPath, 'r') as file: + data = file.readlines() + + removedLine = data.pop(line) + + with open(tempPath, 'w') as file: + file.writelines(data) + + output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", externalApp, tempPath]) + + os.remove(tempPath) + if output != 0: + print "0,Incorrect Syntax cannot be accepted" + return 1 + + print "1," + removedLine + except BaseException, msg: + print "0," + str(msg) + + @staticmethod + def addNewCron(externalApp, finalCron): + try: + + try: + output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) + except: + try: + subprocess.call(('sudo', 'crontab', '-u', externalApp, '-')) + except: + print "0,Unable to initialise crontab file for user" + return 1 + + output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) + + if "no crontab for" in output: + echo = subprocess.Popen((['cat', '/dev/null']), stdout=subprocess.PIPE) + subprocess.call(('sudo', 'crontab', '-u', externalApp, '-'), stdin=echo.stdout) + echo.wait() + echo.stdout.close() + output = subprocess.check_output(["sudo", "/usr/bin/crontab", "-u", externalApp, "-l"]) + if "no crontab for" in output: + print "0,Unable to initialise crontab file for user" + return 1 + + tempPath = "/home/cyberpanel/" + externalApp + str(randint(10000, 99999)) + ".cron.tmp" + + with open(tempPath, "a") as file: + file.write(output + finalCron + "\n") + + output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", externalApp, tempPath]) + + os.remove(tempPath) + if output != 0: + print "0,Incorrect Syntax cannot be accepted" + return 1 + + print "1,None" + except BaseException, msg: + print "0," + str(msg) + + + +def main(): + + parser = argparse.ArgumentParser(description='CyberPanel Installer') + parser.add_argument('function', help='Specific a function to call!') + + parser.add_argument("--externalApp", help="externalApp") + parser.add_argument("--line", help="") + parser.add_argument("--finalCron", help="") + parser.add_argument("--tempPath", help="Temporary path to file where PHP is storing data!") + + + args = parser.parse_args() + + if args.function == "getWebsiteCron": + CronUtil.getWebsiteCron(args.externalApp) + elif args.function == "saveCronChanges": + CronUtil.saveCronChanges(args.externalApp, args.finalCron, int(args.line)) + elif args.function == "remCronbyLine": + CronUtil.remCronbyLine(args.externalApp, int(args.line)) + elif args.function == "addNewCron": + CronUtil.addNewCron(args.externalApp, args.finalCron) + + + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/plogical/csf.py b/plogical/csf.py index 5fb21e7cc..ce3f648fd 100644 --- a/plogical/csf.py +++ b/plogical/csf.py @@ -141,7 +141,7 @@ class CSF(multi.Thread): currentSettings = {} command = 'sudo cat /etc/csf/csf.conf' - output = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + 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: @@ -167,7 +167,7 @@ class CSF(multi.Thread): currentSettings['firewallStatus'] = 0 command = 'sudo iptables -nv -L' - output = ProcessUtilities.outputExecutioner(shlex.split(command)) + output = ProcessUtilities.outputExecutioner(command) if output.find('0.0.0.0/0') > -1: currentSettings['firewallStatus'] = 1 @@ -259,10 +259,10 @@ class CSF(multi.Thread): def allowIP(ipAddress): try: command = 'sudo csf -dr ' + ipAddress - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo csf -a ' + ipAddress - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[allowIP]") @@ -272,10 +272,10 @@ class CSF(multi.Thread): try: command = 'sudo csf -tr ' + ipAddress - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo csf -d ' + ipAddress - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[blockIP]") diff --git a/plogical/dnsUtilities.py b/plogical/dnsUtilities.py index c6e146e3d..209cd2717 100644 --- a/plogical/dnsUtilities.py +++ b/plogical/dnsUtilities.py @@ -326,7 +326,7 @@ class DNS: path = "/etc/opendkim/keys/" + topLevelDomain + "/default.txt" command = "sudo cat " + path - output = ProcessUtilities.outputExecutioner(shlex.split(command)) + output = subprocess.check_output(shlex.split(command)) leftIndex = output.index('(') + 2 rightIndex = output.rindex(')') - 1 diff --git a/plogical/findBWUsage.py b/plogical/findBWUsage.py index 708979ef6..1a88816fe 100644 --- a/plogical/findBWUsage.py +++ b/plogical/findBWUsage.py @@ -127,7 +127,7 @@ class findBWUsage: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: logging.CyberCPLogFileWriter.writeToFile("1440 [setup_cron]") diff --git a/plogical/firewallUtilities.py b/plogical/firewallUtilities.py index 2538e41ac..a7db987fe 100644 --- a/plogical/firewallUtilities.py +++ b/plogical/firewallUtilities.py @@ -1,8 +1,14 @@ -import subprocess -import CyberCPLogFileWriter as logging -import shlex -from processUtilities import ProcessUtilities - +#!/usr/local/CyberCP/bin/python2 +import os +import os.path +import sys +import django +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() +import plogical.CyberCPLogFileWriter as logging +import argparse +from plogical.processUtilities import ProcessUtilities class FirewallUtilities: @@ -18,9 +24,8 @@ class FirewallUtilities: @staticmethod def doCommand(command): try: - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) - if FirewallUtilities.resFailed(res): + res = ProcessUtilities.executioner(command) + if res == 0: logging.CyberCPLogFileWriter.writeToFile("Failed to apply rule: " + command + " Error #" + str(res)) return 0 @@ -33,7 +38,6 @@ class FirewallUtilities: return 1 - @staticmethod def addRule(proto,port,ipAddress): ruleFamily = 'rule family="ipv4"' @@ -70,7 +74,7 @@ class FirewallUtilities: command = "sudo firewall-cmd --permanent --zone=public --remove-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'" - if not FirewallUtilities.doCommand(command): + if ProcessUtilities.executioner(command) == 0: return 0 ruleFamily = 'rule family="ipv6"' @@ -78,12 +82,155 @@ class FirewallUtilities: command = "sudo firewall-cmd --permanent --zone=public --remove-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'" - if not FirewallUtilities.doCommand(command): + if ProcessUtilities.executioner(command) == 0: return 0 command = 'sudo firewall-cmd --reload' - if not FirewallUtilities.doCommand(command): + if ProcessUtilities.executioner(command) == 0: return 0 - return 1 \ No newline at end of file + return 1 + + @staticmethod + def saveSSHConfigs(type, sshPort, rootLogin): + try: + if type == "1": + + command = 'sudo semanage port -a -t ssh_port_t -p tcp ' + sshPort + ProcessUtilities.normalExecutioner(command) + + FirewallUtilities.addRule('tcp', sshPort, "0.0.0.0/0") + + + if rootLogin == "1": + rootLogin = "PermitRootLogin yes\n" + else: + rootLogin = "PermitRootLogin no\n" + + sshPort = "Port " + sshPort + "\n" + + pathToSSH = "/etc/ssh/sshd_config" + + data = open(pathToSSH, 'r').readlines() + + writeToFile = open(pathToSSH, "w") + + for items in data: + if items.find("PermitRootLogin") > -1: + if items.find("Yes") > -1 or items.find("yes"): + writeToFile.writelines(rootLogin) + continue + elif items.find("Port") > -1: + writeToFile.writelines(sshPort) + else: + writeToFile.writelines(items) + writeToFile.close() + + command = 'sudo systemctl restart sshd' + ProcessUtilities.normalExecutioner(command) + + print "1,None" + + except BaseException, msg: + print "0," + str(msg) + + @staticmethod + def addSSHKey(tempPath): + try: + key = open(tempPath, 'r').read() + + sshDir = "/root/.ssh" + + pathToSSH = "/root/.ssh/authorized_keys" + + if os.path.exists(sshDir): + pass + else: + os.mkdir(sshDir) + + if os.path.exists(pathToSSH): + pass + else: + sshFile = open(pathToSSH, 'w') + sshFile.writelines("#Created by CyberPanel\n") + sshFile.close() + + presenseCheck = 0 + try: + data = open(pathToSSH, "r").readlines() + for items in data: + if items.find(key) > -1: + presenseCheck = 1 + except: + pass + + if presenseCheck == 0: + writeToFile = open(pathToSSH, 'a') + writeToFile.writelines("#Added by CyberPanel\n") + writeToFile.writelines("\n") + writeToFile.writelines(key) + writeToFile.writelines("\n") + writeToFile.close() + + if os.path.split(tempPath): + os.remove(tempPath) + + print "1,None" + + except BaseException, msg: + print "0," + str(msg) + + @staticmethod + def deleteSSHKey(key): + try: + keyPart = key.split(" ")[1] + pathToSSH = "/root/.ssh/authorized_keys" + + data = open(pathToSSH, 'r').readlines() + + writeToFile = open(pathToSSH, "w") + + for items in data: + if items.find("ssh-rsa") > -1 and items.find(keyPart) > -1: + continue + else: + writeToFile.writelines(items) + + writeToFile.close() + + print "1,None" + + except BaseException, msg: + print "0," + str(msg) + + +def main(): + + parser = argparse.ArgumentParser(description='CyberPanel Installer') + parser.add_argument('function', help='Specific a function to call!') + + ## Litespeed Tuning Arguments + + parser.add_argument("--tempPath", help="Temporary path to file where PHP is storing data!") + + parser.add_argument("--type", help="Type") + parser.add_argument("--sshPort", help="SSH Port") + parser.add_argument("--rootLogin", help="Root Login") + parser.add_argument("--key", help="Key") + + + args = parser.parse_args() + + if args.function == "saveSSHConfigs": + FirewallUtilities.saveSSHConfigs(args.type, args.sshPort, args.rootLogin) + elif args.function == "addSSHKey": + FirewallUtilities.addSSHKey(args.tempPath) + elif args.function == "deleteSSHKey": + FirewallUtilities.deleteSSHKey(args.key) + + + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/plogical/ftpUtilities.py b/plogical/ftpUtilities.py index c2cf62602..a1e49d19c 100644 --- a/plogical/ftpUtilities.py +++ b/plogical/ftpUtilities.py @@ -21,7 +21,6 @@ from datetime import datetime class FTPUtilities: - @staticmethod def createNewFTPAccount(udb,upass,username,password,path): try: @@ -32,7 +31,7 @@ class FTPUtilities: cmd.append("ftpuser:2001") cmd.append(path) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print "Permissions not changed." else: @@ -58,7 +57,7 @@ class FTPUtilities: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print "Permissions not changed." @@ -72,7 +71,7 @@ class FTPUtilities: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: return 0 @@ -96,7 +95,7 @@ class FTPUtilities: command = "chown " + externalApp + ":" + externalApp + " " + path cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) return 1,'None' diff --git a/plogical/installUtilities.py b/plogical/installUtilities.py index 652e4f541..f8b93d00f 100644 --- a/plogical/installUtilities.py +++ b/plogical/installUtilities.py @@ -19,7 +19,7 @@ class installUtilities: cmd.append("-y") cmd.append("install") cmd.append("epel-release") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") @@ -47,7 +47,7 @@ class installUtilities: cmd.append("rpm") cmd.append("-ivh") cmd.append("http://rpms.litespeedtech.com/centos/litespeed-repo-1.1-1.el7.noarch.rpm") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") print(" Could not add Litespeed repo " ) @@ -78,7 +78,7 @@ class installUtilities: cmd.append("install") cmd.append("openlitespeed-1.4.26") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: @@ -111,7 +111,7 @@ class installUtilities: cmd.append("/usr/local/lsws/bin/lswsctrl") cmd.append("start") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") @@ -136,15 +136,13 @@ class installUtilities: @staticmethod def reStartLiteSpeed(): try: - FNULL = open(os.devnull, 'w') if ProcessUtilities.decideServer() == ProcessUtilities.OLS: command = "sudo systemctl restart lsws" else: command = "sudo /usr/local/lsws/bin/lswsctrl restart" - cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ProcessUtilities.executioner(command) except OSError, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [reStartLiteSpeed]") @@ -165,7 +163,7 @@ class installUtilities: command = "sudo /usr/local/lsws/bin/lswsctrl restart" cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") @@ -216,7 +214,7 @@ class installUtilities: cmd.append("groupinstall") cmd.append("lsphp-all") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") @@ -310,7 +308,7 @@ class installUtilities: cmd.append("remove") cmd.append("openlitespeed-1.4.26") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") @@ -338,7 +336,7 @@ class installUtilities: cmd.append("remove") cmd.append("lsphp*") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") @@ -380,7 +378,7 @@ class installUtilities: cmd.append("start") cmd.append("mariadb") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") @@ -416,7 +414,7 @@ class installUtilities: cmd.append("install") cmd.append("mariadb-server") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") @@ -456,7 +454,7 @@ class installUtilities: cmd.append("enable") cmd.append("mariadb") - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 1: print("###############################################") diff --git a/plogical/mailUtilities.py b/plogical/mailUtilities.py index 2c82d9e38..aaf09f8e9 100644 --- a/plogical/mailUtilities.py +++ b/plogical/mailUtilities.py @@ -80,13 +80,13 @@ class mailUtilities: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) command = 'chown -R lscpd:lscpd /usr/local/lscp/cyberpanel/rainloop/data/_data_' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) ## After effects ends @@ -159,18 +159,18 @@ class mailUtilities: FNULL = open(os.devnull, 'w') command = "opendkim-genkey -D /etc/opendkim/keys/" + virtualHostName + " -d " + virtualHostName + " -s default" - ProcessUtilities.executioner(shlex.split(command),stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(shlex.split(command),stdout=FNULL, stderr=subprocess.STDOUT) ## Fix permissions command = "chown -R root:opendkim /etc/opendkim/keys/" + virtualHostName - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "chmod 640 /etc/opendkim/keys/" + virtualHostName + "/default.private" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "chmod 644 /etc/opendkim/keys/" + virtualHostName + "/default.txt" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) ## Edit key file @@ -202,10 +202,10 @@ class mailUtilities: ## Restart postfix and OpenDKIM command = "systemctl restart opendkim" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "systemctl restart postfix" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) return 1, "None" @@ -221,7 +221,7 @@ class mailUtilities: path = "/etc/opendkim.conf" command = "sudo cat " + path - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if res == 1: return 0 @@ -285,15 +285,15 @@ milter_default_action = accept #### Restarting Postfix and OpenDKIM command = "systemctl start opendkim" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "systemctl enable opendkim" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) ## command = "systemctl start postfix" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) print "1,None" return @@ -316,14 +316,14 @@ milter_default_action = accept FNULL = open(os.devnull, 'w') command = "sudo mkdir " + mailUtilities.cyberPanelHome - ProcessUtilities.executioner(shlex.split(command), stdout=FNULL) + subprocess.call(shlex.split(command), stdout=FNULL) command = "sudo chown -R cyberpanel:cyberpanel " + mailUtilities.cyberPanelHome - ProcessUtilities.executioner(shlex.split(command), stdout=FNULL) + subprocess.call(shlex.split(command), stdout=FNULL) except: FNULL = open(os.devnull, 'w') command = "sudo chown -R cyberpanel:cyberpanel " + mailUtilities.cyberPanelHome - ProcessUtilities.executioner(shlex.split(command), stdout=FNULL) + subprocess.call(shlex.split(command), stdout=FNULL) except BaseException,msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [checkHome]") @@ -339,7 +339,7 @@ milter_default_action = accept cmd = shlex.split(command) with open(mailUtilities.installLogPath, 'w') as f: - res = ProcessUtilities.executioner(cmd, stdout=f) + res = subprocess.call(cmd, stdout=f) if res == 1: writeToFile = open(mailUtilities.installLogPath, 'a') @@ -363,10 +363,10 @@ milter_default_action = accept def restartServices(): try: command = 'systemctl restart postfix' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = 'systemctl restart dovecot' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except BaseException,msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [restartServices]") @@ -384,7 +384,7 @@ milter_default_action = accept cmd = shlex.split(command) with open(mailUtilities.spamassassinInstallLogPath, 'w') as f: - res = ProcessUtilities.executioner(cmd, stdout=f) + res = subprocess.call(cmd, stdout=f) if res == 1: writeToFile = open(mailUtilities.spamassassinInstallLogPath, 'a') @@ -411,7 +411,7 @@ milter_default_action = accept path = "/etc/mail/spamassassin/local.cf" command = "sudo cat " + path - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if res == 1: return 0 @@ -443,21 +443,21 @@ milter_default_action = accept command = "groupadd spamd" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "useradd -g spamd -s /bin/false -d /var/log/spamassassin spamd" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) ## command = "chown spamd:spamd /var/log/spamassassin" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "systemctl enable spamassassin" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "systemctl start spamassassin" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) ## Configuration to postfix @@ -478,7 +478,7 @@ milter_default_action = accept writeToFile.close() command = 'systemctl restart postfix' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) print "1,None" @@ -531,7 +531,7 @@ milter_default_action = accept conf.close() command = 'systemctl restart spamassassin' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) print "1,None" return @@ -552,10 +552,10 @@ milter_default_action = accept shutil.copy("/usr/local/CyberCP/postfixSenderPolicy/cpecs.service", "/etc/systemd/system/cpecs.service") command = 'systemctl enable cpecs' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = 'systemctl start cpecs' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) writeToFile = open(postfixPath, 'a') writeToFile.writelines('smtpd_data_restrictions = check_policy_service unix:/var/log/policyServerSocket\n') @@ -563,7 +563,7 @@ milter_default_action = accept writeToFile.close() command = 'systemctl restart postfix' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) else: data = open(postfixPath, 'r').readlines() @@ -580,10 +580,10 @@ milter_default_action = accept writeToFile.close() command = 'systemctl stop cpecs' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = 'systemctl restart postfix' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) print "1,None" return diff --git a/plogical/modSec.py b/plogical/modSec.py index a0cb6797a..29dc137e7 100644 --- a/plogical/modSec.py +++ b/plogical/modSec.py @@ -10,13 +10,13 @@ from mailUtilities import mailUtilities from processUtilities import ProcessUtilities class modSec: + installLogPath = "/home/cyberpanel/modSecInstallLog" tempRulesFile = "/home/cyberpanel/tempModSecRules" mirrorPath = "cyberpanel.net" - @staticmethod - def installModSec(install, modSecInstall): + def installModSec(): try: mailUtilities.checkHome() @@ -29,7 +29,7 @@ class modSec: cmd = shlex.split(command) with open(modSec.installLogPath, 'w') as f: - res = ProcessUtilities.executioner(cmd, stdout=f) + res = subprocess.call(cmd, stdout=f) if res == 1: writeToFile = open(modSec.installLogPath, 'a') @@ -215,7 +215,6 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf str(msg) + " [saveModSecRules]") print "0," + str(msg) - @staticmethod def setupComodoRules(): try: @@ -230,7 +229,7 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf os.remove('comodo.tar.gz') command = "wget https://" + modSec.mirrorPath + "/modsec/comodo.tar.gz" - result = ProcessUtilities.executioner(shlex.split(command)) + result = subprocess.call(shlex.split(command)) if result == 1: return 0 @@ -250,13 +249,13 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf os.remove('cpanel_litespeed_vendor') command = "wget https://waf.comodo.com/api/cpanel_litespeed_vendor" - result = ProcessUtilities.executioner(shlex.split(command)) + result = subprocess.call(shlex.split(command)) if result == 1: return 0 command = "unzip cpanel_litespeed_vendor -d " + extractLocation - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) return 1 @@ -334,16 +333,16 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf os.remove('cpanel_litespeed_vendor') command = "wget https://waf.comodo.com/api/cpanel_litespeed_vendor" - result = ProcessUtilities.executioner(shlex.split(command)) + result = subprocess.call(shlex.split(command)) if result == 1: return 0 command = "unzip cpanel_litespeed_vendor -d " + extractLocation - result = ProcessUtilities.executioner(shlex.split(command)) + result = subprocess.call(shlex.split(command)) command = 'sudo chown -R lsadm:lsadm /usr/local/lsws/conf' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) print "1,None" return @@ -398,7 +397,7 @@ modsecurity_rules_file /usr/local/lsws/conf/modsec/rules.conf os.remove('owasp.tar.gz') command = "wget https://" + modSec.mirrorPath + "/modsec/owasp.tar.gz" - result = ProcessUtilities.executioner(shlex.split(command)) + result = subprocess.call(shlex.split(command)) if result == 1: return 0 @@ -573,6 +572,8 @@ def main(): if args.function == "installModSecConfigs": modSec.installModSecConfigs() + elif args.function == "installModSec": + modSec.installModSec() elif args.function == "saveModSecConfigs": modSec.saveModSecConfigs(args.tempConfigPath) elif args.function == "saveModSecRules": diff --git a/plogical/mysqlUtilities.py b/plogical/mysqlUtilities.py index ea00366e4..9e79a4462 100644 --- a/plogical/mysqlUtilities.py +++ b/plogical/mysqlUtilities.py @@ -72,8 +72,8 @@ class mysqlUtilities: return 0 cursor.execute("CREATE DATABASE " + dbname) - cursor.execute("CREATE USER '" +dbuser+ "'@'localhost' IDENTIFIED BY '"+dbpassword+"'") - cursor.execute("GRANT ALL PRIVILEGES ON " +dbname+ ".* TO '" +dbuser+ "'@'localhost'") + cursor.execute("CREATE USER '" + dbuser + "'@'localhost' IDENTIFIED BY '"+dbpassword+"'") + cursor.execute("GRANT ALL PRIVILEGES ON " + dbname + ".* TO '" + dbuser + "'@'localhost'") connection.close() return 1 @@ -83,6 +83,42 @@ class mysqlUtilities: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[createDatabase]") return 0 + @staticmethod + def createDBUser(dbuser, dbpassword): + try: + + connection, cursor = mysqlUtilities.setupConnection() + + if connection == 0: + return 0 + + cursor.execute("CREATE DATABASE " + dbuser) + cursor.execute("CREATE USER '" + dbuser + "'@'localhost' IDENTIFIED BY '" + dbpassword + "'") + + return 1 + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[createDBUser]") + return 0 + + @staticmethod + def allowGlobalUserAccess(globalUser, dbName): + try: + + connection, cursor = mysqlUtilities.setupConnection() + + if connection == 0: + return 0 + + cursor.execute("GRANT ALL PRIVILEGES ON " + dbName + ".* TO '" + globalUser + "'@'localhost'") + connection.close() + + return 1 + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[createDatabase]") + return 0 + @staticmethod def deleteDatabase(dbname, dbuser): try: @@ -116,7 +152,7 @@ class mysqlUtilities: cmd = shlex.split(command) with open(tempStoragePath+"/"+databaseName+'.sql', 'w') as f: - res = ProcessUtilities.executioner(cmd,stdout=f) + res = subprocess.call(cmd,stdout=f) if res == 1: logging.CyberCPLogFileWriter.writeToFile("Database: "+databaseName + "could not be backed! [createDatabaseBackup]") @@ -143,7 +179,7 @@ class mysqlUtilities: with open(tempStoragePath + "/" + databaseName + '.sql', 'r') as f: - res = ProcessUtilities.executioner(cmd, stdin=f) + res = subprocess.call(cmd, stdin=f) if res == 1: logging.CyberCPLogFileWriter.writeToFile("Could not restore MYSQL database: " +databaseName +"! [restoreDatabaseBackup]") @@ -347,7 +383,7 @@ class mysqlUtilities: command = 'sudo mv /etc/my.cnf.bak /etc/my.cnf' else: command = 'sudo mv /etc/mysql/my.cnf.bak /etc/mysql//my.cnf' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) logging.CyberCPLogFileWriter.writeToFile(str(msg)) return 0, str(msg) @@ -383,7 +419,7 @@ class mysqlUtilities: except BaseException, msg: command = 'sudo mv /etc/my.cnf.bak /etc/my.cnf' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) logging.CyberCPLogFileWriter.writeToFile(str(msg)) return 0, str(msg) @@ -608,4 +644,23 @@ class mysqlUtilities: except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[showStatus]") + return 0 + + @staticmethod + def changePassword(userName, dbPassword): + try: + + connection, cursor = mysqlUtilities.setupConnection() + + if connection == 0: + return 0 + + cursor.execute("use mysql") + cursor.execute("SET PASSWORD FOR '" + userName + "'@'localhost' = PASSWORD('" + dbPassword + "')") + connection.close() + + return 1 + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[mysqlUtilities.changePassword]") return 0 \ No newline at end of file diff --git a/plogical/phpUtilities.py b/plogical/phpUtilities.py index 26bfc8b1d..b267941f6 100644 --- a/plogical/phpUtilities.py +++ b/plogical/phpUtilities.py @@ -27,7 +27,7 @@ class phpUtilities: try: with open(phpUtilities.installLogPath, 'w') as f: - ProcessUtilities.executioner(cmd, stdout=f) + subprocess.call(cmd, stdout=f) writeToFile = open(phpUtilities.installLogPath, 'a') writeToFile.writelines("PHP Extension Installed.\n") @@ -59,7 +59,7 @@ class phpUtilities: try: with open(phpUtilities.installLogPath, 'w') as f: - ProcessUtilities.executioner(cmd, stdout=f) + subprocess.call(cmd, stdout=f) writeToFile = open(phpUtilities.installLogPath, 'a') writeToFile.writelines("PHP Extension Removed.\n") @@ -178,6 +178,7 @@ def main(): parser.add_argument("--upload_max_filesize", help="Process Soft Limit for PHP!") parser.add_argument("--max_input_time", help="Process Hard Limit for PHP!") parser.add_argument("--post_max_size", help="Process Hard Limit for PHP!") + parser.add_argument("--extension", help="Process Hard Limit for PHP!") ## Litespeed Tuning Arguments @@ -192,6 +193,12 @@ def main(): elif args.function == "savePHPConfigAdvance": phpUtilities.savePHPConfigAdvance(args.phpVers, args.tempPath) + elif args.function == "installPHPExtension": + phpUtilities.installPHPExtension(args.extension, args.extension) + + elif args.function == "unInstallPHPExtension": + phpUtilities.unInstallPHPExtension(args.extension, args.extension) + diff --git a/plogical/processUtilities.py b/plogical/processUtilities.py index e539604dc..0345cd33a 100644 --- a/plogical/processUtilities.py +++ b/plogical/processUtilities.py @@ -39,7 +39,7 @@ class ProcessUtilities: command = "sudo /usr/local/lsws/bin/lswsctrl restart" cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 0: return 1 @@ -58,7 +58,7 @@ class ProcessUtilities: command = "sudo /usr/local/lsws/bin/lswsctrl stop" cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) if res == 0: return 1 @@ -68,6 +68,17 @@ class ProcessUtilities: except subprocess.CalledProcessError, msg: logging.writeToFile(str(msg) + "[stopLitespeed]") + @staticmethod + def normalExecutioner(command): + try: + res = subprocess.call(shlex.split(command)) + if res == 0: + return 1 + else: + return 0 + except BaseException, msg: + return 0 + @staticmethod def killLiteSpeed(): try: @@ -107,7 +118,7 @@ class ProcessUtilities: def containerCheck(): try: command = 'sudo cat /etc/cgrules.conf' - result = ProcessUtilities.executioner(shlex.split(command)) + result = subprocess.call(shlex.split(command)) if result == 1: return 0 else: @@ -118,6 +129,7 @@ class ProcessUtilities: @staticmethod def executioner(command): try: + logging.writeToFile(command) res = subprocess.call(shlex.split(command)) if res == 0: return 1 @@ -128,11 +140,23 @@ class ProcessUtilities: @staticmethod def outputExecutioner(command): - return subprocess.check_output(shlex.split(command)) + if type(command) == str or type(command) == unicode: + logging.writeToFile(command) + return subprocess.check_output(shlex.split(command)) + else: + command = " ".join(command) + logging.writeToFile(command + " join") + return subprocess.check_output(shlex.split(command)) @staticmethod def popenExecutioner(command): - return subprocess.Popen(shlex.split(command)) + if type(command) == str or type(command) == unicode: + logging.writeToFile(command) + return subprocess.Popen(shlex.split(command)) + else: + command = " ".join(command) + logging.writeToFile(command) + return subprocess.Popen(shlex.split(command)) diff --git a/plogical/remoteBackup.py b/plogical/remoteBackup.py index 45a1577b8..e45f11bda 100644 --- a/plogical/remoteBackup.py +++ b/plogical/remoteBackup.py @@ -220,7 +220,7 @@ class remoteBackup: ## complete path is a path to the file need to send command = 'sudo rsync -avz -e "ssh -i /root/.ssh/cyberpanel -o StrictHostKeyChecking=no" ' + completedPathToSend + ' root@' + IPAddress + ':/home/backup/transfer-'+folderNumber - ProcessUtilities.executioner(shlex.split(command), stdout=writeToFile) + subprocess.call(shlex.split(command), stdout=writeToFile) os.remove(completedPathToSend) except BaseException, msg: diff --git a/plogical/remoteTransferUtilities.py b/plogical/remoteTransferUtilities.py index 1200b6b6f..c8dfa758a 100644 --- a/plogical/remoteTransferUtilities.py +++ b/plogical/remoteTransferUtilities.py @@ -213,7 +213,7 @@ class remoteTransferUtilities: ## complete path is a path to the file need to send command = "sudo scp -o StrictHostKeyChecking=no -i /root/.ssh/cyberpanel " + completedPathToSend + " root@" + IPAddress + ":/home/backup/transfer-" + folderNumber + "/" - ProcessUtilities.executioner(shlex.split(command), stdout=writeToFile) + subprocess.call(shlex.split(command), stdout=writeToFile) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startBackup]") diff --git a/plogical/sslUtilities.py b/plogical/sslUtilities.py index dee1d399a..d2508f47d 100644 --- a/plogical/sslUtilities.py +++ b/plogical/sslUtilities.py @@ -236,14 +236,14 @@ class sslUtilities: if not os.path.exists(acmePath): command = 'wget -O - https://get.acme.sh | sh' - ProcessUtilities.executioner(command, shell=True) + subprocess.call(command, shell=True) if aliasDomain == None: existingCertPath = '/etc/letsencrypt/live/' + virtualHostName if not os.path.exists(existingCertPath): command = 'mkdir -p ' + existingCertPath - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) try: logging.CyberCPLogFileWriter.writeToFile("Trying to obtain SSL for: " + virtualHostName + " and: www." + virtualHostName) @@ -252,7 +252,7 @@ class sslUtilities: + ' --cert-file ' + existingCertPath + '/cert.pem' + ' --key-file ' + existingCertPath + '/privkey.pem' \ + ' --fullchain-file ' + existingCertPath + '/fullchain.pem' + ' -w ' + sslpath + ' --force' - output = ProcessUtilities.outputExecutioner(shlex.split(command)) + output = subprocess.check_output(shlex.split(command)) logging.CyberCPLogFileWriter.writeToFile("Successfully obtained SSL for: " + virtualHostName + " and: www." + virtualHostName) @@ -265,7 +265,7 @@ class sslUtilities: command = acmePath + " --issue -d " + virtualHostName + ' --cert-file ' + existingCertPath \ + '/cert.pem' + ' --key-file ' + existingCertPath + '/privkey.pem' \ + ' --fullchain-file ' + existingCertPath + '/fullchain.pem' + ' -w ' + sslpath + ' --force' - output = ProcessUtilities.outputExecutioner(shlex.split(command)) + output = subprocess.check_output(shlex.split(command)) logging.CyberCPLogFileWriter.writeToFile("Successfully obtained SSL for: " + virtualHostName) except subprocess.CalledProcessError: logging.CyberCPLogFileWriter.writeToFile('Failed to obtain SSL, issuing self-signed SSL for: ' + virtualHostName) @@ -275,7 +275,7 @@ class sslUtilities: existingCertPath = '/etc/letsencrypt/live/' + virtualHostName if not os.path.exists(existingCertPath): command = 'mkdir -p ' + existingCertPath - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) try: logging.CyberCPLogFileWriter.writeToFile( @@ -286,7 +286,7 @@ class sslUtilities: + ' --cert-file ' + existingCertPath + '/cert.pem' + ' --key-file ' + existingCertPath + '/privkey.pem' \ + ' --fullchain-file ' + existingCertPath + '/fullchain.pem' + ' -w ' + sslpath + ' --force' - output = ProcessUtilities.outputExecutioner(shlex.split(command)) + output = subprocess.check_output(shlex.split(command)) logging.CyberCPLogFileWriter.writeToFile( "Successfully obtained SSL for: " + virtualHostName + ", www." + virtualHostName + ", " + aliasDomain + "and www." + aliasDomain + ",") diff --git a/plogical/tuning.py b/plogical/tuning.py index 4953439e6..5694149fb 100644 --- a/plogical/tuning.py +++ b/plogical/tuning.py @@ -15,7 +15,7 @@ class tuning: try: dataToReturn = {} command = "sudo cat /usr/local/lsws/conf/httpd_config.conf" - datas = ProcessUtilities.outputExecutioner(shlex.split(command)).split("\n") + datas = ProcessUtilities.outputExecutioner(command).split("\n") for items in datas: if items.find("maxConnections")>-1: @@ -58,7 +58,7 @@ class tuning: dataToReturn = {} command = "sudo cat /usr/local/lsws/conf/httpd_config.xml" - datas = ProcessUtilities.outputExecutioner(shlex.split(command)) + datas = ProcessUtilities.outputExecutioner(command) comTree = ElementTree.fromstring(datas) tuningData = comTree.find('tuning') @@ -187,7 +187,7 @@ class tuning: path = installUtilities.Server_root_path + "/conf/vhosts/"+virtualHost+"/vhost.conf" command = "sudo cat "+path - datas = ProcessUtilities.outputExecutioner(shlex.split(command)).split("\n") + datas = ProcessUtilities.outputExecutioner(command).split("\n") dataToReturn = {} @@ -230,7 +230,7 @@ class tuning: else: try: command = "sudo cat /usr/local/lsws/conf/httpd_config.xml" - datas = ProcessUtilities.outputExecutioner(shlex.split(command)) + datas = ProcessUtilities.outputExecutioner(command) comTree = ElementTree.fromstring(datas) extProcessorList = comTree.findall('extProcessorList/extProcessor') diff --git a/plogical/upgrade.py b/plogical/upgrade.py index 51ad50731..da126984f 100644 --- a/plogical/upgrade.py +++ b/plogical/upgrade.py @@ -35,7 +35,7 @@ class Upgrade: try: count = 0 while True: - res = ProcessUtilities.executioner(shlex.split(command)) + res = subprocess.call(shlex.split(command)) if res != 0: count = count + 1 Upgrade.stdOut(component + ' failed, trying again, try number: ' + str(count), 0) @@ -89,7 +89,7 @@ class Upgrade: ## env_path = '/usr/local/CyberCP' - ProcessUtilities.executioner(['virtualenv', env_path]) + subprocess.call(['virtualenv', env_path]) activate_this = os.path.join(env_path, 'bin', 'activate_this.py') execfile(activate_this, dict(__file__=activate_this)) @@ -990,11 +990,17 @@ WantedBy=multi-user.target""" Upgrade.stdOut("Fixing permissions..") - command = 'chown -R cyberpanel:cyberpanel /usr/local/CyberCP' + command = "find /usr/local/CyberCP -type d -exec chmod 0755 {} \;" Upgrade.executioner(command, 'chown core code', 0) - command = 'chown -R cyberpanel:cyberpanel /usr/local/lscp' - Upgrade.executioner(command, 'chown lscp', 0) + command = "find /usr/local/CyberCP -type f -exec chmod 0644 {} \;" + Upgrade.executioner(command, 'chown core code', 0) + + command = "chmod -R 755 /usr/local/CyberCP/bin" + Upgrade.executioner(command, 'chown core code', 0) + + command = "chown -R root:root /usr/local/CyberCP" + Upgrade.executioner(command, 'chown core code', 0) command = 'chown -R lscpd:lscpd /usr/local/lscp/cyberpanel' Upgrade.executioner(command, 'chown static content', 0) diff --git a/plogical/upgradeCritical.py b/plogical/upgradeCritical.py index 1df6719d6..8a1fded6b 100644 --- a/plogical/upgradeCritical.py +++ b/plogical/upgradeCritical.py @@ -11,7 +11,7 @@ class UpgradeCritical: try: FNULL = open(os.devnull, 'w') - res = ProcessUtilities.executioner(shlex.split(command), stdout=FNULL) + res = subprocess.call(shlex.split(command), stdout=FNULL) if res == 0: return 1 else: @@ -26,7 +26,6 @@ class UpgradeCritical: command = "DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade pdns-server pdns-backend-mysql install dovecot-imapd dovecot-pop3d postfix-mysql pure-ftpd postfix dovecot-mysql -y" UpgradeCritical.executioner(command) else: - command = "yum update" UpgradeCritical.executioner(command) diff --git a/plogical/vhost.py b/plogical/vhost.py index 2396e1947..3269060cc 100644 --- a/plogical/vhost.py +++ b/plogical/vhost.py @@ -39,15 +39,15 @@ class vhost: command = "adduser " + virtualHostUser + " -M -d " + path cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) command = "groupadd " + virtualHostUser cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) command = "usermod -a -G " + virtualHostUser + " " + virtualHostUser cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addingUsers]") @@ -60,7 +60,7 @@ class vhost: try: command = 'chmod 711 /home' cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except: pass @@ -69,11 +69,11 @@ class vhost: command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + path cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) command = "chmod 711 " + path cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except OSError, msg: logging.CyberCPLogFileWriter.writeToFile( @@ -85,7 +85,7 @@ class vhost: command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + pathHTML cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except OSError, msg: logging.CyberCPLogFileWriter.writeToFile( @@ -97,7 +97,7 @@ class vhost: command = "chown " + "lscpd" + ":" + "lscpd" + " " + pathLogs cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) if ProcessUtilities.decideServer() == ProcessUtilities.OLS: @@ -106,7 +106,7 @@ class vhost: command = "chmod -R 755 " + pathLogs cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except OSError, msg: logging.CyberCPLogFileWriter.writeToFile( @@ -127,7 +127,7 @@ class vhost: command = "chown " + "lsadm" + ":" + "lsadm" + " " + completePathToConfigFile cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except IOError, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectories]]") @@ -149,13 +149,13 @@ class vhost: command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + "/home/" + virtualHostName + "/public_html/index.html" cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) vhostPath = vhost.Server_root + "/conf/vhosts" command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [finalizeVhostCreation]") @@ -332,7 +332,7 @@ class vhost: ## Delete mail accounts command = "sudo rm -rf /home/vmail/" + virtualHostName - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to remove virtual host configuration from main configuration file.]") return 0 @@ -368,7 +368,7 @@ class vhost: ## Delete mail accounts command = "sudo rm -rf /home/vmail/" + virtualHostName - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile( str(msg) + " [Not able to remove virtual host configuration from main configuration file.]") @@ -596,7 +596,7 @@ class vhost: try: command = 'sudo chown -R cyberpanel:cyberpanel ' + path cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) @@ -607,7 +607,7 @@ class vhost: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) @@ -673,12 +673,12 @@ class vhost: command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + path + "/index.html" cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) vhostPath = vhost.Server_root + "/conf/vhosts" command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [finalizeDomainCreation]") @@ -696,7 +696,7 @@ class vhost: os.makedirs(path) command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + path cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except OSError, msg: logging.CyberCPLogFileWriter.writeToFile( str(msg) + "329 [Not able to create directories for virtual host [createDirectoryForDomain]]") diff --git a/plogical/virtualHostUtilities.py b/plogical/virtualHostUtilities.py index fc95715b5..6108892b2 100644 --- a/plogical/virtualHostUtilities.py +++ b/plogical/virtualHostUtilities.py @@ -166,10 +166,10 @@ class virtualHostUtilities: def getAccessLogs(fileName, page): try: - numberOfTotalLines = int(ProcessUtilities.outputExecutioner(["wc", "-l", fileName]).split(" ")[0]) + numberOfTotalLines = int(subprocess.check_output(["wc", "-l", fileName]).split(" ")[0]) if numberOfTotalLines < 25: - data = ProcessUtilities.outputExecutioner(["cat", fileName]) + data = subprocess.check_output(["cat", fileName]) else: if page == 1: end = numberOfTotalLines @@ -199,10 +199,10 @@ class virtualHostUtilities: def getErrorLogs(fileName, page): try: - numberOfTotalLines = int(ProcessUtilities.outputExecutioner(["wc", "-l", fileName]).split(" ")[0]) + numberOfTotalLines = int(subprocess.check_output(["wc", "-l", fileName]).split(" ")[0]) if numberOfTotalLines < 25: - data = ProcessUtilities.outputExecutioner(["cat", fileName]) + data = subprocess.check_output(["cat", fileName]) else: if page == 1: end = numberOfTotalLines @@ -303,13 +303,13 @@ class virtualHostUtilities: if not os.path.exists("latest.tar.gz"): command = 'wget --no-check-certificate http://wordpress.org/latest.tar.gz -O latest.tar.gz' cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) command = 'tar -xzvf latest.tar.gz -C ' + finalPath cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) ## Get plugin @@ -318,13 +318,13 @@ class virtualHostUtilities: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) command = 'unzip litespeed-cache.1.1.5.1.zip -d ' + finalPath cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) root = finalPath @@ -368,7 +368,7 @@ class virtualHostUtilities: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) vhost.addRewriteRules(domainName) @@ -392,7 +392,7 @@ class virtualHostUtilities: os.mkdir(homeDir) command = "chown -R " + virtualHostUser + ":" + virtualHostUser + " " + homeDir cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) print "0," + str(msg) return @@ -454,7 +454,7 @@ class virtualHostUtilities: command = 'systemctl restart lscpd' cmd = shlex.split(command) - ProcessUtilities.executioner(cmd) + subprocess.call(cmd) print "1,None" return 1,'None' @@ -838,7 +838,7 @@ class virtualHostUtilities: pathToStoreSSL = '/etc/letsencrypt/live/' + virtualHost command = 'mkdir -p ' + pathToStoreSSL - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem" pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem" @@ -863,7 +863,7 @@ class virtualHostUtilities: command = "chown " + "lsadm" + ":" + "lsadm" + " " + pathToStoreSSL cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) print "1,None" @@ -1002,7 +1002,7 @@ class virtualHostUtilities: def getDiskUsage(path, totalAllowed): try: - totalUsageInMB = ProcessUtilities.outputExecutioner(["sudo", "du", "-hs", path, "--block-size=1M"]).split()[0] + totalUsageInMB = subprocess.check_output(["sudo", "du", "-hs", path, "--block-size=1M"]).split()[0] percentage = float(100) / float(totalAllowed) @@ -1021,7 +1021,7 @@ class virtualHostUtilities: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) @@ -1033,7 +1033,7 @@ class virtualHostUtilities: cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + res = subprocess.call(cmd) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) diff --git a/plogical/website.py b/plogical/website.py index 9e955e508..3a5c596b6 100644 --- a/plogical/website.py +++ b/plogical/website.py @@ -167,7 +167,7 @@ class WebsiteManager: + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) + \ ' --websiteOwner ' + websiteOwner + ' --package ' + packageName + ' --tempStatusPath ' + tempStatusPath - subprocess.Popen(shlex.split(execPath)) + ProcessUtilities.popenExecutioner(execPath) time.sleep(2) data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", 'tempStatusPath': tempStatusPath} @@ -215,7 +215,7 @@ class WebsiteManager: + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ + admin.userName + ' --tempStatusPath ' + tempStatusPath - subprocess.Popen(shlex.split(execPath)) + ProcessUtilities.popenExecutioner(execPath) time.sleep(2) data_ret = {'status': 1, 'createWebSiteStatus': 1, 'error_message': "None", 'tempStatusPath': tempStatusPath} @@ -296,7 +296,7 @@ class WebsiteManager: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName - ProcessUtilities.outputExecutioner(shlex.split(execPath)) + ProcessUtilities.popenExecutioner(execPath) data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} json_data = json.dumps(data_ret) @@ -321,7 +321,7 @@ class WebsiteManager: execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" execPath = execPath + " deleteDomain --virtualHostName " + websiteName - ProcessUtilities.outputExecutioner(shlex.split(execPath)) + ProcessUtilities.outputExecutioner(execPath) data_ret = {'status': 1, 'websiteDeleteStatus': 1, 'error_message': "None"} json_data = json.dumps(data_ret) @@ -346,18 +346,17 @@ class WebsiteManager: if state == "Suspend": confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName command = "sudo mv " + confPath + " " + confPath + "-suspended" - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.popenExecutioner(command) installUtilities.reStartLiteSpeed() website.state = 0 else: confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName command = "sudo mv " + confPath + "-suspended" + " " + confPath - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath - cmd = shlex.split(command) - ProcessUtilities.executioner(cmd) + ProcessUtilities.popenExecutioner(command) installUtilities.reStartLiteSpeed() website.state = 1 @@ -503,19 +502,10 @@ class WebsiteManager: completePathToConfigFile = confPath + "/vhost.conf" execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + ProcessUtilities.popenExecutioner(execPath) - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'status': 0, 'saveStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## php changes ends + #### newOwner = Administrator.objects.get(userName=newUser) @@ -574,7 +564,7 @@ class WebsiteManager: execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( website.package.bandwidth) - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = subprocess.check_output(shlex.split(execPath)) bwData = output.split(",") except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) @@ -639,7 +629,7 @@ class WebsiteManager: execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( website.package.bandwidth) - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = subprocess.check_output(shlex.split(execPath)) bwData = output.split(",") except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) @@ -695,7 +685,7 @@ class WebsiteManager: execPath = execPath + " getAccessLogs --path " + fileName + " --page " + str(page) - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: final_json = json.dumps( @@ -754,10 +744,9 @@ class WebsiteManager: ## get Logs execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " getErrorLogs --path " + fileName + " --page " + str(page) - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: final_json = json.dumps( @@ -783,7 +772,7 @@ class WebsiteManager: filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" command = 'sudo cat ' + filePath - configData = ProcessUtilities.outputExecutioner(shlex.split(command)) + configData = ProcessUtilities.outputExecutioner(command) if len(configData) == 0: status = {'status': 0, "configstatus": 0, "error_message": "Configuration file is currently empty!"} @@ -822,10 +811,9 @@ class WebsiteManager: ## save configuration data execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: status = {"configstatus": 1} @@ -905,10 +893,9 @@ class WebsiteManager: ## save configuration data execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveRewriteRules --virtualHostName " + self.domain + " --path " + filePath + " --tempPath " + tempPath - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: status = {"rewriteStatus": 1, 'error_message': output} @@ -950,10 +937,8 @@ class WebsiteManager: ## writing data temporary to file execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath - - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'sslStatus': 1, 'error_message': "None"} @@ -983,17 +968,9 @@ class WebsiteManager: completePathToConfigFile = confPath + "/vhost.conf" execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'status': 1, 'changePHP': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + output = ProcessUtilities.popenExecutioner(execPath) data_ret = {'status': 1, 'changePHP': 1, 'error_message': "None"} json_data = json.dumps(data_ret) @@ -1020,28 +997,19 @@ class WebsiteManager: json_data = json.dumps(dic) return HttpResponse(json_data) - if ProcessUtilities.decideDistro() == ProcessUtilities.centos: - cronPath = "/var/spool/cron/" + website.externalApp - else: - cronPath = "/var/spool/cron/crontabs/" + website.externalApp - - cmd = 'sudo test -e ' + cronPath + ' && echo Exists' - output = os.popen(cmd).read() - - if "Exists" not in output: - data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": {}} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) crons = [] - try: - # f = ProcessUtilities.outputExecutioner(["sudo", "cat", cronPath]) - f = ProcessUtilities.outputExecutioner(["sudo", "crontab", "-u", website.externalApp, "-l"]) - except subprocess.CalledProcessError as error: - dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} - json_data = json.dumps(dic) - return HttpResponse(json_data) + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " getWebsiteCron --externalApp " + website.externalApp + + f = ProcessUtilities.outputExecutioner(execPath) + + if f.find("0,") > -1: + data_ret = {'getWebsiteCron': 0, "user": website.externalApp, "crons": {}} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + counter = 0 for line in f.split("\n"): if line: @@ -1089,11 +1057,8 @@ class WebsiteManager: line -= 1 website = Websites.objects.get(domain=self.domain) - cronPath = "/var/spool/cron/" + website.externalApp - crons = [] - try: - # f = ProcessUtilities.outputExecutioner(["sudo", "cat", cronPath]) + # f = subprocess.check_output(["sudo", "cat", cronPath]) f = ProcessUtilities.outputExecutioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, "-l"]) print f except subprocess.CalledProcessError as error: @@ -1157,51 +1122,26 @@ class WebsiteManager: website = Websites.objects.get(domain=self.domain) - tempPath = "/home/cyberpanel/" + website.externalApp + str(randint(10000, 99999)) + ".cron.tmp" - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - output = ProcessUtilities.outputExecutioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, "-l"]) - if "no crontab for" in output: - data_ret = {'addNewCron': 0, 'error_message': 'crontab file does not exists for user'} + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " saveCronChanges --externalApp " + website.externalApp + " --line " + str(line) + " --finalCron '" + finalCron + "'" + output = ProcessUtilities.outputExecutioner(execPath) + + if output.find("1,") > -1: + data_ret = {"getWebsiteCron": 1, + "user": website.externalApp, + "cron": finalCron, + "line": line} final_json = json.dumps(data_ret) return HttpResponse(final_json) + else: + dic = {'getWebsiteCron': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) - with open(tempPath, "w+") as file: - file.write(output) - - # Confirming that directory is read/writable - o = ProcessUtilities.executioner(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) - if o is not 0: - data_ret = {'addNewCron': 0, 'error_message': 'Error Changing Permissions'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - with open(tempPath, 'r') as file: - data = file.readlines() - - data[line] = finalCron + '\n' - - with open(tempPath, 'w') as file: - file.writelines(data) - - output = ProcessUtilities.executioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, tempPath]) - - os.remove(tempPath) - if output != 0: - data_ret = {'addNewCron': 0, 'error_message': 'Incorrect Syntax cannot be accepted.'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": finalCron, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) except BaseException, msg: - print msg dic = {'getWebsiteCron': 0, 'error_message': str(msg)} json_data = json.dumps(dic) return HttpResponse(json_data) @@ -1219,52 +1159,27 @@ class WebsiteManager: else: return ACLManager.loadErrorJson('addNewCron', 0) - line -= 1 website = Websites.objects.get(domain=self.domain) - output = ProcessUtilities.outputExecutioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, "-l"]) + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " remCronbyLine --externalApp " + website.externalApp + " --line " + str( + line) + output = ProcessUtilities.outputExecutioner(execPath) - if "no crontab for" in output: - data_ret = {'addNewCron': 0, 'error_message': 'No Cron exists for this user'} + if output.find("1,") > -1: + data_ret = {"remCronbyLine": 1, + "user": website.externalApp, + "removeLine": output.split(',')[1], + "line": line} final_json = json.dumps(data_ret) return HttpResponse(final_json) + else: + dic = {'remCronbyLine': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) - tempPath = "/home/cyberpanel/" + website.externalApp + str(randint(10000, 99999)) + ".cron.tmp" - with open(tempPath, "w+") as file: - file.write(output) - - # Confirming that directory is read/writable - o = ProcessUtilities.executioner(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) - if o is not 0: - data_ret = {'addNewCron': 0, 'error_message': 'Error Changing Permissions'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - with open(tempPath, 'r') as file: - data = file.readlines() - - removedLine = data.pop(line) - - with open(tempPath, 'w') as file: - file.writelines(data) - - output = ProcessUtilities.executioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, tempPath]) - - os.remove(tempPath) - if output != 0: - data_ret = {'addNewCron': 0, 'error_message': 'Incorrect Syntax cannot be accepted'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - data_ret = {"remCronbyLine": 1, - "user": website.externalApp, - "removeLine": removedLine, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) except BaseException, msg: - print msg dic = {'remCronbyLine': 0, 'error_message': str(msg)} json_data = json.dumps(dic) return HttpResponse(json_data) @@ -1290,51 +1205,25 @@ class WebsiteManager: website = Websites.objects.get(domain=self.domain) - try: - output = ProcessUtilities.outputExecutioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, "-l"]) - except: - try: - ProcessUtilities.executioner(('sudo', 'crontab', '-u', website.externalApp, '-')) - except: - data_ret = {'addNewCron': 0, 'error_message': 'Unable to initialise crontab file for user'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - output = ProcessUtilities.outputExecutioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, "-l"]) - - if "no crontab for" in output: - echo = subprocess.Popen((['cat', '/dev/null']), stdout=subprocess.PIPE) - ProcessUtilities.executioner(('sudo', 'crontab', '-u', website.externalApp, '-'), stdin=echo.stdout) - echo.wait() - echo.stdout.close() - output = ProcessUtilities.outputExecutioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, "-l"]) - if "no crontab for" in output: - data_ret = {'addNewCron': 0, 'error_message': 'Unable to initialise crontab file for user'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - tempPath = "/home/cyberpanel/" + website.externalApp + str(randint(10000, 99999)) + ".cron.tmp" - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - with open(tempPath, "a") as file: - file.write(output + finalCron + "\n") + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/cronUtil.py" + execPath = execPath + " addNewCron --externalApp " + website.externalApp + " --finalCron '" + finalCron + "'" + output = ProcessUtilities.outputExecutioner(execPath) - output = ProcessUtilities.executioner(["sudo", "/usr/bin/crontab", "-u", website.externalApp, tempPath]) - - os.remove(tempPath) - if output != 0: - data_ret = {'addNewCron': 0, 'error_message': 'Incorrect Syntax cannot be accepted'} + if output.find("1,") > -1: + data_ret = {"addNewCron": 1, + "user": website.externalApp, + "cron": finalCron} final_json = json.dumps(data_ret) return HttpResponse(final_json) + else: + dic = {'addNewCron': 0, 'error_message': output} + json_data = json.dumps(dic) + return HttpResponse(json_data) + - data_ret = {"addNewCron": 1, - "user": website.externalApp, - "cron": finalCron} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) except BaseException, msg: - print msg dic = {'addNewCron': 0, 'error_message': str(msg)} json_data = json.dumps(dic) return HttpResponse(json_data) @@ -1363,7 +1252,7 @@ class WebsiteManager: execPath = execPath + " createAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --ssl " + str( ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: pass @@ -1405,10 +1294,9 @@ class WebsiteManager: ## Create Configurations execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " issueAliasSSL --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} @@ -1441,10 +1329,8 @@ class WebsiteManager: ## Create Configurations execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain - - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} @@ -1475,17 +1361,8 @@ class WebsiteManager: return ACLManager.loadErrorJson('changeOpenBasedir', 0) execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " changeOpenBasedir --virtualHostName '" + self.domain + "' --openBasedirValue " + openBasedirValue - - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'status': 0, 'changeOpenBasedir': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + output = ProcessUtilities.popenExecutioner(execPath) data_ret = {'status': 1, 'changeOpenBasedir': 1, 'error_message': "None"} json_data = json.dumps(data_ret) @@ -1566,7 +1443,7 @@ class WebsiteManager: if lastLine.find('[200]') > -1: command = 'sudo rm -f ' + statusFile - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) data_ret = {'abort': 1, 'installStatus': 1, 'installationProgress': "100", 'currentStatus': 'Successfully Installed.'} json_data = json.dumps(data_ret) @@ -1802,7 +1679,7 @@ Host gitlab.com ProcessUtilities.executioner(command) command = 'sudo cat /root/.ssh/git.pub' - deploymentKey = ProcessUtilities.outputExecutioner(shlex.split(command)).strip('\n') + deploymentKey = ProcessUtilities.outputExecutioner(command) return render(request, 'websiteFunctions/setupGit.html', {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) diff --git a/pluginInstaller/pluginInstaller.py b/pluginInstaller/pluginInstaller.py index d86e1e50e..ad83cf20e 100644 --- a/pluginInstaller/pluginInstaller.py +++ b/pluginInstaller/pluginInstaller.py @@ -26,7 +26,7 @@ class pluginInstaller: def extractPlugin(pluginName): pathToPlugin = pluginName + '.zip' command = 'unzip ' + pathToPlugin + ' -d /usr/local/CyberCP' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) @staticmethod def upgradingSettingsFile(pluginName): @@ -65,7 +65,7 @@ class pluginInstaller: pluginFile = pluginPath + '/' + pluginName command = 'touch ' + pluginFile - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) @staticmethod def addInterfaceLink(pluginName): @@ -87,15 +87,15 @@ class pluginInstaller: currentDir = os.getcwd() command = "rm -rf /usr/local/lscp/cyberpanel/static" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) os.chdir('/usr/local/CyberCP') command = "python manage.py collectstatic --noinput" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = "mv /usr/local/CyberCP/static /usr/local/lscp/cyberpanel" - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) os.chdir(currentDir) @@ -106,10 +106,10 @@ class pluginInstaller: if os.path.exists(pluginHome + '/pre_install'): command = 'chmod +x ' + pluginHome + '/pre_install' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = pluginHome + '/pre_install' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) @staticmethod def postScript(pluginName): @@ -117,10 +117,10 @@ class pluginInstaller: if os.path.exists(pluginHome + '/post_install'): command = 'chmod +x ' + pluginHome + '/post_install' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) command = pluginHome + '/post_install' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) @staticmethod @@ -286,7 +286,7 @@ class pluginInstaller: @staticmethod def restartGunicorn(): command = 'systemctl restart gunicorn.socket' - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) diff --git a/serverLogs/views.py b/serverLogs/views.py index 555cd150b..f2908544d 100644 --- a/serverLogs/views.py +++ b/serverLogs/views.py @@ -11,6 +11,7 @@ import subprocess import shlex from plogical.virtualHostUtilities import virtualHostUtilities from plogical.acl import ACLManager +from plogical.processUtilities import ProcessUtilities # Create your views here. @@ -139,7 +140,7 @@ def getLogsFromFile(request): try: command = "sudo tail -50 " + fileName - fewLinesOfLogFile = ProcessUtilities.outputExecutioner(shlex.split(command)) + fewLinesOfLogFile = ProcessUtilities.outputExecutioner(command) status = {"status": 1, "logstatus": 1, "logsdata": fewLinesOfLogFile} final_json = json.dumps(status) return HttpResponse(final_json) @@ -172,10 +173,9 @@ def clearLogFile(request): fileName = data['fileName'] execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/serverLogs.py" - execPath = execPath + " cleanLogFile --fileName " + fileName - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'cleanStatus': 1, 'error_message': "None"} diff --git a/serverStatus/serverStatusUtil.py b/serverStatus/serverStatusUtil.py index 262460013..9dcfd25f4 100644 --- a/serverStatus/serverStatusUtil.py +++ b/serverStatus/serverStatusUtil.py @@ -24,7 +24,7 @@ class ServerStatusUtil: @staticmethod def executioner(command, statusFile): try: - res = ProcessUtilities.executioner(shlex.split(command), stdout=statusFile, stderr=statusFile) + res = subprocess.call(shlex.split(command), stdout=statusFile, stderr=statusFile) if res == 1: return 0 else: @@ -94,7 +94,7 @@ class ServerStatusUtil: try: command = 'chown -R lsadm:lsadm ' + confPath - ProcessUtilities.executioner(shlex.split(command)) + subprocess.call(shlex.split(command)) except: pass @@ -172,7 +172,7 @@ class ServerStatusUtil: FNULL = open(os.devnull, 'w') command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) @@ -209,7 +209,7 @@ class ServerStatusUtil: FNULL = open(os.devnull, 'w') command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath cmd = shlex.split(command) - ProcessUtilities.executioner(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg)) diff --git a/serverStatus/views.py b/serverStatus/views.py index fe4dea6f5..9f9730493 100644 --- a/serverStatus/views.py +++ b/serverStatus/views.py @@ -60,7 +60,7 @@ def litespeedStatus(request): else: loadedModules.append(items) - except subprocess.CalledProcessError, msg: + except BaseException, 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.", @@ -143,6 +143,7 @@ def getFurtherDataFromLogFile(request): return ACLManager.loadErrorJson('logstatus', 0) fewLinesOfLogFile = logging.CyberCPLogFileWriter.readLastNFiles(50, logging.CyberCPLogFileWriter.fileName) + fewLinesOfLogFile = str(fewLinesOfLogFile) status = {"logstatus": 1, "logsdata": fewLinesOfLogFile} final_json = json.dumps(status) @@ -193,7 +194,7 @@ def servicesStatus(request): mailStatus = [] dockerStatus = [] - processlist = ProcessUtilities.outputExecutioner(['ps', '-A']) + processlist = subprocess.check_output(['ps', '-A']) def getServiceStats(service): if service in processlist: @@ -308,20 +309,8 @@ def servicesAction(request): service = 'pure-ftpd' command = 'sudo systemctl %s %s' % (action, service) - cmd = shlex.split(command) - res = ProcessUtilities.executioner(cmd) + ProcessUtilities.executioner(command) - p = subprocess.Popen(cmd, stdout=subprocess.PIPE) - result = p.communicate()[0] - - if res != 0: - final_dic = {'serviceAction': 0, "error_message": "Error while performing action"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - 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)} @@ -349,7 +338,7 @@ def switchTOLSWS(request): execPath = "sudo /usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/serverStatus/serverStatusUtil.py" execPath = execPath + " switchTOLSWS --licenseKey " + data['licenseKey'] - subprocess.Popen(shlex.split(execPath)) + ProcessUtilities.popenExecutioner(execPath) time.sleep(2) data_ret = {'status': 1, 'error_message': "None", } @@ -366,7 +355,7 @@ def switchTOLSWSStatus(request): try: command = 'sudo cat ' + serverStatusUtil.ServerStatusUtil.lswsInstallStatusPath - output = ProcessUtilities.outputExecutioner(shlex.split(command)) + output = ProcessUtilities.outputExecutioner(command) if output.find('[404]') > -1: data_ret = {'abort': 1, 'requestStatus': output, 'installed': 0} @@ -400,10 +389,10 @@ def licenseStatus(request): return ACLManager.loadErrorJson('status', 0) command = 'sudo cat /usr/local/lsws/conf/serial.no' - serial = ProcessUtilities.outputExecutioner(shlex.split(command)) + serial = ProcessUtilities.outputExecutioner(command) command = 'sudo /usr/local/lsws/bin/lshttpd -V' - expiration = ProcessUtilities.outputExecutioner(shlex.split(command)) + expiration = ProcessUtilities.outputExecutioner(command) final_dic = {'status': 1, "erroMessage": 0, 'lsSerial': serial, 'lsexpiration': expiration} final_json = json.dumps(final_dic) @@ -435,7 +424,7 @@ def changeLicense(request): newKey = data['newKey'] command = 'sudo chown -R cyberpanel:cyberpanel /usr/local/lsws/conf' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) serialPath = '/usr/local/lsws/conf/serial.no' serialFile = open(serialPath, 'w') @@ -443,13 +432,13 @@ def changeLicense(request): serialFile.close() command = 'sudo chown -R lsadm:lsadm /usr/local/lsws/conf' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo /usr/local/lsws/bin/lshttpd -r' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) command = 'sudo /usr/local/lsws/bin/lswsctrl restart' - ProcessUtilities.executioner(shlex.split(command)) + ProcessUtilities.executioner(command) final_dic = {'status': 1, "erroMessage": 'None'} final_json = json.dumps(final_dic) @@ -488,7 +477,7 @@ def topProcessesStatus(request): try: with open("/home/cyberpanel/top", "w") as outfile: - ProcessUtilities.executioner("sudo top -n1 -b", shell=True, stdout=outfile) + subprocess.call("top -n1 -b", shell=True, stdout=outfile) data = open('/home/cyberpanel/top', 'r').readlines() @@ -574,7 +563,7 @@ def topProcessesStatus(request): ## CPU Details command = 'sudo cat /proc/cpuinfo' - output = ProcessUtilities.outputExecutioner(shlex.split(command)).splitlines() + output = subprocess.check_output(shlex.split(command)).splitlines() import psutil diff --git a/static/databases/databases.js b/static/databases/databases.js index 22f246d91..e13d25977 100644 --- a/static/databases/databases.js +++ b/static/databases/databases.js @@ -4,7 +4,7 @@ /* Java script code to create database */ -app.controller('createDatabase', function($scope,$http) { +app.controller('createDatabase', function ($scope, $http) { $scope.createDatabaseLoading = true; $scope.dbDetails = true; @@ -14,103 +14,99 @@ app.controller('createDatabase', function($scope,$http) { $scope.generatedPasswordView = true; - $scope.showDetailsBoxes = function(){ + $scope.showDetailsBoxes = function () { $scope.dbDetails = false; }; - $scope.createDatabase = function(){ + $scope.createDatabase = function () { - $scope.createDatabaseLoading = false; + $scope.createDatabaseLoading = false; + $scope.dbDetails = false; + $scope.databaseCreationFailed = true; + $scope.databaseCreated = true; + $scope.couldNotConnect = true; + + + var databaseWebsite = $scope.databaseWebsite; + var dbName = $scope.dbName; + var dbUsername = $scope.dbUsername; + var dbPassword = $scope.dbPassword; + var webUserName = ""; + + // getting website username + + webUserName = databaseWebsite.replace(/-/g, ''); + webUserName = webUserName.split(".")[0]; + + if (webUserName.length > 5) { + webUserName = webUserName.substring(0, 4); + } + + var url = "/dataBases/submitDBCreation"; + + + var data = { + webUserName: webUserName, + databaseWebsite: databaseWebsite, + dbName: dbName, + dbUsername: dbUsername, + dbPassword: dbPassword + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.createDBStatus == 1) { + + $scope.createDatabaseLoading = true; $scope.dbDetails = false; $scope.databaseCreationFailed = true; - $scope.databaseCreated = true; + $scope.databaseCreated = false; $scope.couldNotConnect = true; - var databaseWebsite = $scope.databaseWebsite; - var dbName = $scope.dbName; - var dbUsername = $scope.dbUsername; - var dbPassword = $scope.dbPassword; - var webUserName = ""; + } - // getting website username - - webUserName = databaseWebsite.replace(/-/g, ''); - webUserName = webUserName.split(".")[0]; - - if(webUserName.length > 5){ - webUserName = webUserName.substring(0,4); - } - - var url = "/dataBases/submitDBCreation"; + else { - var data = { - webUserName:webUserName, - databaseWebsite:databaseWebsite, - dbName:dbName, - dbUsername:dbUsername, - dbPassword:dbPassword - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $scope.createDatabaseLoading = true; + $scope.dbDetails = false; + $scope.databaseCreationFailed = false; + $scope.databaseCreated = true; + $scope.couldNotConnect = true; + $scope.errorMessage = response.data.error_message; - function ListInitialDatas(response) { + } - if(response.data.createDBStatus == 1){ - - $scope.createDatabaseLoading = true; - $scope.dbDetails = false; - $scope.databaseCreationFailed = true; - $scope.databaseCreated = false; - $scope.couldNotConnect = true; - - - } - - else - { - - - $scope.createDatabaseLoading = true; - $scope.dbDetails = false; - $scope.databaseCreationFailed = false; - $scope.databaseCreated = true; - $scope.couldNotConnect = true; - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.createDatabaseLoading = true; - $scope.dbDetails = true; - $scope.databaseCreationFailed = true; - $scope.databaseCreated = true; - $scope.couldNotConnect = false; - } - + } + function cantLoadInitialDatas(response) { + $scope.createDatabaseLoading = true; + $scope.dbDetails = true; + $scope.databaseCreationFailed = true; + $scope.databaseCreated = true; + $scope.couldNotConnect = false; + } }; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.dbPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.dbPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -122,7 +118,7 @@ app.controller('createDatabase', function($scope,$http) { /* Java script code to delete database */ -app.controller('deleteDatabase', function($scope,$http) { +app.controller('deleteDatabase', function ($scope, $http) { $scope.deleteDatabaseLoading = true; $scope.fetchedDatabases = true; @@ -131,153 +127,147 @@ app.controller('deleteDatabase', function($scope,$http) { $scope.couldNotConnect = true; - $scope.fetchDatabases = function(){ + $scope.fetchDatabases = function () { - $scope.deleteDatabaseLoading = false; - $scope.fetchedDatabases = true; + $scope.deleteDatabaseLoading = false; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = true; + $scope.couldNotConnect = true; + + + var databaseWebsite = $scope.databaseWebsite; + + var url = "/dataBases/fetchDatabases"; + + + var data = { + databaseWebsite: databaseWebsite, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.fetchStatus == 1) { + + + $scope.dbnames = JSON.parse(response.data.data); + + + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = false; $scope.databaseDeletionFailed = true; $scope.databaseDeleted = true; $scope.couldNotConnect = true; - var databaseWebsite = $scope.databaseWebsite; + } - var url = "/dataBases/fetchDatabases"; + else { + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = false; + $scope.databaseDeleted = true; + $scope.couldNotConnect = true; - var data = { - databaseWebsite:databaseWebsite, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $scope.errorMessage = response.data.error_message; - function ListInitialDatas(response) { + } - if(response.data.fetchStatus == 1){ + } + + function cantLoadInitialDatas(response) { + + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = true; + $scope.couldNotConnect = false; - $scope.dbnames = JSON.parse(response.data.data); - - - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = false; - $scope.databaseDeletionFailed = true; - $scope.databaseDeleted = true; - $scope.couldNotConnect = true; - - - - } - - else - { - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = true; - $scope.databaseDeletionFailed = false; - $scope.databaseDeleted = true; - $scope.couldNotConnect = true; - - - - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = true; - $scope.databaseDeletionFailed = true; - $scope.databaseDeleted = true; - $scope.couldNotConnect = false; - - - } + } }; - $scope.deleteDatabase = function(){ + $scope.deleteDatabase = function () { - $scope.deleteDatabaseLoading = false; - $scope.fetchedDatabases = true; + $scope.deleteDatabaseLoading = false; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = true; + $scope.couldNotConnect = true; + + + var databaseWebsite = $scope.databaseWebsite; + + var url = "/dataBases/submitDatabaseDeletion"; + + + var data = { + dbName: $scope.selectedDB, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.deleteStatus == 1) { + + + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = false; $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = false; + $scope.couldNotConnect = true; + + + } + + else { + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = false; $scope.databaseDeleted = true; $scope.couldNotConnect = true; - var databaseWebsite = $scope.databaseWebsite; - - var url = "/dataBases/submitDatabaseDeletion"; + $scope.errorMessage = response.data.error_message; - var data = { - dbName:$scope.selectedDB, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + } - function ListInitialDatas(response) { + } + + function cantLoadInitialDatas(response) { + + $scope.deleteDatabaseLoading = true; + $scope.fetchedDatabases = true; + $scope.databaseDeletionFailed = true; + $scope.databaseDeleted = true; + $scope.couldNotConnect = false; - if(response.data.deleteStatus == 1){ - - - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = false; - $scope.databaseDeletionFailed = true; - $scope.databaseDeleted = false; - $scope.couldNotConnect = true; - - - - } - - else - { - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = true; - $scope.databaseDeletionFailed = false; - $scope.databaseDeleted = true; - $scope.couldNotConnect = true; - - - - $scope.errorMessage = response.data.error_message; - - - } - - - - } - function cantLoadInitialDatas(response) { - - $scope.deleteDatabaseLoading = true; - $scope.fetchedDatabases = true; - $scope.databaseDeletionFailed = true; - $scope.databaseDeleted = true; - $scope.couldNotConnect = false; - - - } + } }; @@ -289,7 +279,7 @@ app.controller('deleteDatabase', function($scope,$http) { /* Java script code to list databases */ -app.controller('listDBs', function($scope,$http) { +app.controller('listDBs', function ($scope, $http) { $scope.recordsFetched = true; $scope.passwordChanged = true; @@ -303,161 +293,161 @@ app.controller('listDBs', function($scope,$http) { var globalDBUsername = ""; $scope.fetchDBs = function () { - populateCurrentRecords(); + populateCurrentRecords(); }; $scope.changePassword = function (dbUsername) { - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.dbLoading = true; - $scope.dbAccounts = false; - $scope.changePasswordBox = false; - $scope.notificationsBox = true; - $scope.dbUsername = dbUsername; + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.dbLoading = true; + $scope.dbAccounts = false; + $scope.changePasswordBox = false; + $scope.notificationsBox = true; + $scope.dbUsername = dbUsername; - globalDBUsername = dbUsername; + globalDBUsername = dbUsername; }; $scope.changePasswordBtn = function () { - $scope.dbLoading = false; - $scope.passwordChanged = true; + $scope.dbLoading = false; + $scope.passwordChanged = true; - url = "/dataBases/changePassword"; + url = "/dataBases/changePassword"; - var data = { - dbUserName:globalDBUsername, - dbPassword: $scope.dbPassword, - }; + var data = { + dbUserName: globalDBUsername, + dbPassword: $scope.dbPassword, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.changePasswordStatus == 1){ - $scope.notificationsBox = false; - $scope.passwordChanged = false; - $scope.dbLoading = true; - $scope.domainFeteched = $scope.selectedDomain; + if (response.data.changePasswordStatus == 1) { + $scope.notificationsBox = false; + $scope.passwordChanged = false; + $scope.dbLoading = true; + $scope.domainFeteched = $scope.selectedDomain; - } - else{ - $scope.notificationsBox = false; - $scope.canNotChangePassword = false; - $scope.dbLoading = true; - $scope.canNotChangePassword = false; - $scope.errorMessage = response.data.error_message; - } + } + else { + $scope.notificationsBox = false; + $scope.canNotChangePassword = false; + $scope.dbLoading = true; + $scope.canNotChangePassword = false; + $scope.errorMessage = response.data.error_message; + } - } - function cantLoadInitialDatas(response) { - $scope.notificationsBox = false; - $scope.couldNotConnect = false; - $scope.dbLoading = true; + } - } + function cantLoadInitialDatas(response) { + $scope.notificationsBox = false; + $scope.couldNotConnect = false; + $scope.dbLoading = true; - }; + } - function populateCurrentRecords(){ - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.dbLoading = false; - $scope.dbAccounts = true; - $scope.changePasswordBox = true; - $scope.notificationsBox = true; + }; - var selectedDomain = $scope.selectedDomain; + function populateCurrentRecords() { + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.dbLoading = false; + $scope.dbAccounts = true; + $scope.changePasswordBox = true; + $scope.notificationsBox = true; - url = "/dataBases/fetchDatabases"; + var selectedDomain = $scope.selectedDomain; - var data = { - databaseWebsite:selectedDomain, - }; + url = "/dataBases/fetchDatabases"; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var data = { + databaseWebsite: selectedDomain, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = JSON.parse(response.data.data); - $scope.recordsFetched = false; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.dbLoading = true; - $scope.dbAccounts = false; - $scope.changePasswordBox = true; - $scope.notificationsBox = false; + $scope.recordsFetched = false; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.dbLoading = true; + $scope.dbAccounts = false; + $scope.changePasswordBox = true; + $scope.notificationsBox = false; - $scope.domainFeteched = $scope.selectedDomain; + $scope.domainFeteched = $scope.selectedDomain; - } - else{ - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = true; - $scope.dbLoading = true; - $scope.dbAccounts = true; - $scope.changePasswordBox = true; - $scope.notificationsBox = true; + } + else { + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = true; + $scope.dbLoading = true; + $scope.dbAccounts = true; + $scope.changePasswordBox = true; + $scope.notificationsBox = true; - $scope.errorMessage = response.data.error_message; - } + $scope.errorMessage = response.data.error_message; + } - } - function cantLoadInitialDatas(response) { - $scope.recordsFetched = true; - $scope.passwordChanged = true; - $scope.canNotChangePassword = true; - $scope.couldNotConnect = false; - $scope.dbLoading = true; - $scope.dbAccounts = true; - $scope.changePasswordBox = true; - $scope.notificationsBox = true; + } - } + function cantLoadInitialDatas(response) { + $scope.recordsFetched = true; + $scope.passwordChanged = true; + $scope.canNotChangePassword = true; + $scope.couldNotConnect = false; + $scope.dbLoading = true; + $scope.dbAccounts = true; + $scope.changePasswordBox = true; + $scope.notificationsBox = true; - } + } + + } //// $scope.generatedPasswordView = true; $scope.generatePassword = function () { - $scope.generatedPasswordView = false; - $scope.dbPassword = randomPassword(12); + $scope.generatedPasswordView = false; + $scope.dbPassword = randomPassword(12); }; $scope.usePassword = function () { @@ -467,4 +457,40 @@ app.controller('listDBs', function($scope,$http) { }); -/* Java script code to list database ends here */ \ No newline at end of file +/* Java script code to list database ends here */ + + +app.controller('phpMyAdmin', function ($scope, $http, $window) { + + function setupPHPMYAdminSession() { + + url = "/dataBases/setupPHPMYAdminSession"; + + var data = {}; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.status === 1) { + $window.location.href = '/phpmyadmin'; + } + else {} + + } + + function cantLoadInitialDatas(response) {} + + } + setupPHPMYAdminSession(); + +}); \ No newline at end of file diff --git a/test.php b/test.php new file mode 100644 index 000000000..e69de29bb diff --git a/tuning/tuning.py b/tuning/tuning.py index 3773a7b39..6f42cf603 100644 --- a/tuning/tuning.py +++ b/tuning/tuning.py @@ -118,10 +118,8 @@ class tuningManager: gzipCompression = data['gzipCompression'] execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/tuning.py" - execPath = execPath + " saveTuningDetails --maxConn " + maxConn + " --maxSSLConn " + maxSSLConn + " --connTime " + connTime + " --keepAlive " + keepAlive + " --inMemCache '" + inMemCache + "' --gzipCompression " + gzipCompression - - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'fetch_status': 1, 'error_message': "None", 'tuneStatus': 1} @@ -163,10 +161,9 @@ class tuningManager: persistConn = data['persistConn'] execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/tuning.py" - execPath = execPath + " tunePHP --virtualHost " + domainSelection + " --initTimeout " + initTimeout + " --maxConns " + maxConns + " --memSoftLimit " + memSoftLimit + " --memHardLimit '" + memHardLimit + "' --procSoftLimit " + procSoftLimit + " --procHardLimit " + procHardLimit + " --persistConn " + persistConn - output = ProcessUtilities.outputExecutioner(shlex.split(execPath)) + output = ProcessUtilities.outputExecutioner(execPath) if output.find("1,None") > -1: data_ret = {'tuneStatus': 1, 'fetch_status': 0, 'error_message': "None"}