mirror of
https://github.com/usmannasir/cyberpanel.git
synced 2025-11-07 13:56:01 +01:00
improved installer. bug fix to ssh and backups
This commit is contained in:
@@ -63,6 +63,7 @@ INSTALLED_APPS = [
|
||||
'emailPremium',
|
||||
'emailMarketing',
|
||||
'cloudAPI',
|
||||
'highAvailability'
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
|
||||
@@ -262,6 +262,7 @@ def fetchSSHkey(request):
|
||||
data = subprocess.check_output(shlex.split(execPath))
|
||||
|
||||
data_ret = {
|
||||
'status': 1,
|
||||
'pubKeyStatus': 1,
|
||||
'error_message': "None",
|
||||
'pubKey':data
|
||||
@@ -270,6 +271,7 @@ def fetchSSHkey(request):
|
||||
return HttpResponse(json_data)
|
||||
else:
|
||||
data_ret = {
|
||||
'status' : 0,
|
||||
'pubKeyStatus': 0,
|
||||
'error_message': "Could not authorize access to API."
|
||||
}
|
||||
@@ -277,7 +279,7 @@ def fetchSSHkey(request):
|
||||
return HttpResponse(json_data)
|
||||
|
||||
except BaseException, msg:
|
||||
data = {'pubKeyStatus': 0,'error_message': str(msg)}
|
||||
data = {'status' : 0, 'pubKeyStatus': 0,'error_message': str(msg)}
|
||||
json_data = json.dumps(data)
|
||||
return HttpResponse(json_data)
|
||||
|
||||
|
||||
@@ -17,6 +17,11 @@ from packages.packagesManager import PackagesManager
|
||||
from plogical.processUtilities import ProcessUtilities
|
||||
from firewall.firewallManager import FirewallManager
|
||||
from serverLogs.views import getLogsFromFile
|
||||
from random import randint
|
||||
from highAvailability.haManager import HAManager
|
||||
from plogical.httpProc import httpProc
|
||||
from api.views import fetchSSHkey
|
||||
import os
|
||||
|
||||
class CloudManager:
|
||||
def __init__(self, data=None, admin = None):
|
||||
@@ -742,3 +747,86 @@ class CloudManager:
|
||||
return obtainMailServerSSL(request)
|
||||
except BaseException, msg:
|
||||
return self.ajaxPre(0, str(msg))
|
||||
|
||||
def setupManager(self, request):
|
||||
try:
|
||||
request.session['userID'] = self.admin.pk
|
||||
tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999))
|
||||
self.data['tempStatusPath'] = tempStatusPath
|
||||
|
||||
ham = HAManager(request, self.data, 'setupNode')
|
||||
ham.start()
|
||||
|
||||
data = {}
|
||||
data['tempStatusPath'] = tempStatusPath
|
||||
|
||||
proc = httpProc(request, None)
|
||||
return proc.ajax(1, None, data)
|
||||
|
||||
except BaseException, msg:
|
||||
return self.ajaxPre(0, str(msg))
|
||||
|
||||
def fetchManagerTokens(self, request):
|
||||
try:
|
||||
request.session['userID'] = self.admin.pk
|
||||
ham = HAManager(request, self.data, 'fetchManagerTokens')
|
||||
return ham.fetchManagerTokens()
|
||||
|
||||
except BaseException, msg:
|
||||
return self.ajaxPre(0, str(msg))
|
||||
|
||||
def addWorker(self, request):
|
||||
try:
|
||||
request.session['userID'] = self.admin.pk
|
||||
ham = HAManager(request, self.data, 'fetchManagerTokens')
|
||||
return ham.addWorker()
|
||||
|
||||
except BaseException, msg:
|
||||
return self.ajaxPre(0, str(msg))
|
||||
|
||||
def fetchSSHKey(self, request):
|
||||
try:
|
||||
pubKey = os.path.join("/root", ".ssh", 'cyberpanel.pub')
|
||||
execPath = "sudo cat " + pubKey
|
||||
data = subprocess.check_output(shlex.split(execPath))
|
||||
|
||||
data_ret = {
|
||||
'status': 1,
|
||||
'error_message': "None",
|
||||
'pubKey': data
|
||||
}
|
||||
json_data = json.dumps(data_ret)
|
||||
return HttpResponse(json_data)
|
||||
except BaseException, msg:
|
||||
return self.ajaxPre(0, str(msg))
|
||||
|
||||
def putSSHkeyFunc(self, request):
|
||||
try:
|
||||
fm = FirewallManager(request)
|
||||
return fm.addSSHKey(self.admin.pk, self.data)
|
||||
except BaseException, msg:
|
||||
return self.ajaxPre(0, str(msg))
|
||||
|
||||
def leaveSwarm(self, request):
|
||||
try:
|
||||
request.session['userID'] = self.admin.pk
|
||||
ham = HAManager(request, self.data, 'leaveSwarm')
|
||||
return ham.leaveSwarm()
|
||||
except BaseException, msg:
|
||||
return self.ajaxPre(0, str(msg))
|
||||
|
||||
def setUpDataNode(self, request):
|
||||
try:
|
||||
request.session['userID'] = self.admin.pk
|
||||
ham = HAManager(request, self.data, 'setUpDataNode')
|
||||
return ham.setUpDataNode()
|
||||
except BaseException, msg:
|
||||
return self.ajaxPre(0, str(msg))
|
||||
|
||||
def submitEditCluster(self, request):
|
||||
try:
|
||||
request.session['userID'] = self.admin.pk
|
||||
ham = HAManager(request, self.data, 'submitEditCluster')
|
||||
return ham.submitEditCluster()
|
||||
except BaseException, msg:
|
||||
return self.ajaxPre(0, str(msg))
|
||||
|
||||
@@ -161,6 +161,22 @@ def router(request):
|
||||
return cm.getLogsFromFile(request)
|
||||
elif controller == 'serverSSL':
|
||||
return cm.serverSSL(request)
|
||||
elif controller == 'setupNode':
|
||||
return cm.setupManager(request)
|
||||
elif controller == 'fetchManagerTokens':
|
||||
return cm.fetchManagerTokens(request)
|
||||
elif controller == 'addWorker':
|
||||
return cm.addWorker(request)
|
||||
elif controller == 'fetchSSHKey':
|
||||
return cm.fetchSSHKey(request)
|
||||
elif controller == 'putSSHkeyFunc':
|
||||
return cm.putSSHkeyFunc(request)
|
||||
elif controller == 'leaveSwarm':
|
||||
return cm.leaveSwarm(request)
|
||||
elif controller == 'setUpDataNode':
|
||||
return cm.setUpDataNode(request)
|
||||
elif controller == 'submitEditCluster':
|
||||
return cm.submitEditCluster(request)
|
||||
else:
|
||||
return cm.ajaxPre(0, 'This function is not available in your version of CyberPanel.')
|
||||
|
||||
|
||||
@@ -5,8 +5,6 @@ from django.db import models
|
||||
from mailServer.models import Domains, EUsers
|
||||
# Create your models here.
|
||||
|
||||
|
||||
|
||||
class DomainLimits(models.Model):
|
||||
domain = models.ForeignKey(Domains, on_delete=models.CASCADE)
|
||||
limitStatus = models.IntegerField(default=0)
|
||||
|
||||
@@ -350,12 +350,17 @@ class FirewallManager:
|
||||
if items.find("ssh-rsa") > -1:
|
||||
keydata = items.split(" ")
|
||||
|
||||
try:
|
||||
key = "ssh-rsa " + keydata[1][:50] + " .. " + keydata[2]
|
||||
|
||||
try:
|
||||
userName = keydata[2][:keydata[2].index("@")]
|
||||
except:
|
||||
userName = keydata[2]
|
||||
except:
|
||||
key = "ssh-rsa " + keydata[1][:50]
|
||||
userName = ''
|
||||
|
||||
|
||||
|
||||
dic = {'userName': userName,
|
||||
'key': key,
|
||||
@@ -569,7 +574,18 @@ class FirewallManager:
|
||||
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")
|
||||
|
||||
0
highAvailability/__init__.py
Normal file
0
highAvailability/__init__.py
Normal file
6
highAvailability/admin.py
Normal file
6
highAvailability/admin.py
Normal file
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
||||
8
highAvailability/apps.py
Normal file
8
highAvailability/apps.py
Normal file
@@ -0,0 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class HighavailabilityConfig(AppConfig):
|
||||
name = 'highAvailability'
|
||||
245
highAvailability/haManager.py
Normal file
245
highAvailability/haManager.py
Normal file
@@ -0,0 +1,245 @@
|
||||
#!/usr/local/CyberCP/bin/python2
|
||||
import os.path
|
||||
import sys
|
||||
import django
|
||||
sys.path.append('/usr/local/CyberCP')
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
|
||||
django.setup()
|
||||
import subprocess, shlex
|
||||
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
|
||||
from plogical.httpProc import httpProc
|
||||
from plogical.processUtilities import ProcessUtilities
|
||||
from plogical.acl import ACLManager
|
||||
import threading as multi
|
||||
import argparse
|
||||
from plogical.firewallUtilities import FirewallUtilities
|
||||
from firewall.models import FirewallRules
|
||||
|
||||
|
||||
class HAManager(multi.Thread):
|
||||
|
||||
def __init__(self, request = None, data = None, function = None):
|
||||
multi.Thread.__init__(self)
|
||||
self.request = request
|
||||
self.data = data
|
||||
self.function = function
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
if self.function == 'setupNode':
|
||||
self.setupNode()
|
||||
elif self.function == 'addManager':
|
||||
self.setupNode()
|
||||
except BaseException, msg:
|
||||
logging.writeToFile( str(msg) + ' [HAManager.run]')
|
||||
|
||||
def setupNode(self):
|
||||
try:
|
||||
|
||||
if ProcessUtilities.decideDistro() == ProcessUtilities.centos:
|
||||
mesg = 'Clusters are only supported on Ubuntu 18.04. [404]'
|
||||
logging.statusWriter(self.data['tempStatusPath'], mesg)
|
||||
return 0
|
||||
|
||||
userID = self.request.session['userID']
|
||||
currentACL = ACLManager.loadedACL(userID)
|
||||
|
||||
if currentACL['admin'] == 0:
|
||||
mesg = 'Only administrators can create clusters. [404]'
|
||||
logging.statusWriter(self.data['tempStatusPath'], mesg)
|
||||
return 0
|
||||
|
||||
logging.statusWriter(self.data['tempStatusPath'], 'Setting up node in progress..')
|
||||
|
||||
commands = self.data['commands']
|
||||
|
||||
for command in commands:
|
||||
try:
|
||||
result = subprocess.call(command, shell=True)
|
||||
if result != 0:
|
||||
logging.writeToFile(command + ' Failed.')
|
||||
except BaseException:
|
||||
logging.statusWriter(self.data['tempStatusPath'], command + ' Failed. [404]')
|
||||
return 0
|
||||
|
||||
try:
|
||||
FirewallUtilities.addRule('tcp', '2377', "0.0.0.0/0")
|
||||
fwRule = FirewallRules(name="Docker", port='2377', proto="tcp")
|
||||
fwRule.save()
|
||||
except:
|
||||
pass
|
||||
|
||||
mesg = 'Node successfully configured. [200]'
|
||||
logging.statusWriter(self.data['tempStatusPath'], mesg)
|
||||
|
||||
except BaseException, msg:
|
||||
logging.writeToFile(str(msg))
|
||||
logging.statusWriter(self.data['tempStatusPath'], str(msg) + '. [404]')
|
||||
|
||||
def fetchManagerTokens(self):
|
||||
try:
|
||||
|
||||
proc = httpProc(self.request, None, None)
|
||||
|
||||
userID = self.request.session['userID']
|
||||
currentACL = ACLManager.loadedACL(userID)
|
||||
|
||||
if currentACL['admin'] == 0:
|
||||
return proc.ajax(0, 'Only administrators can create clusters.')
|
||||
|
||||
ipFile = "/etc/cyberpanel/machineIP"
|
||||
f = open(ipFile)
|
||||
ipData = f.read()
|
||||
ipAddress = ipData.split('\n', 1)[0]
|
||||
|
||||
command = 'sudo docker swarm init --advertise-addr ' + ipAddress
|
||||
ProcessUtilities.executioner(command)
|
||||
|
||||
managerToken = ''
|
||||
workerToken = ''
|
||||
|
||||
command = "sudo docker swarm join-token manager"
|
||||
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 = subprocess.check_output(shlex.split(command)).splitlines()
|
||||
|
||||
for items in output:
|
||||
if items.find('--token') > -1:
|
||||
workerToken = items.split(' ')[-2]
|
||||
|
||||
data = {}
|
||||
data['managerToken'] = managerToken
|
||||
data['workerToken'] = workerToken
|
||||
|
||||
return proc.ajax(1, None, data)
|
||||
|
||||
except BaseException, msg:
|
||||
proc = httpProc(self.request, None, None)
|
||||
return proc.ajax(0, None, str(msg))
|
||||
|
||||
def addWorker(self):
|
||||
try:
|
||||
|
||||
proc = httpProc(self.request, None, None)
|
||||
|
||||
userID = self.request.session['userID']
|
||||
currentACL = ACLManager.loadedACL(userID)
|
||||
|
||||
if currentACL['admin'] == 0:
|
||||
return proc.ajax(0, 'Only administrators can create clusters.')
|
||||
|
||||
token = self.data['token']
|
||||
ipAddress = self.data['ipAddress']
|
||||
command = 'sudo docker swarm join --token ' + token + ' ' + ipAddress + ':2377'
|
||||
|
||||
if ProcessUtilities.executioner(command) == 0:
|
||||
return proc.ajax(0, 'Failed to join as worker.')
|
||||
|
||||
return proc.ajax(1, None)
|
||||
|
||||
except BaseException, msg:
|
||||
proc = httpProc(self.request, None, None)
|
||||
return proc.ajax(0, None, str(msg))
|
||||
|
||||
def leaveSwarm(self):
|
||||
try:
|
||||
|
||||
userID = self.request.session['userID']
|
||||
currentACL = ACLManager.loadedACL(userID)
|
||||
proc = httpProc(self.request, None, None)
|
||||
|
||||
if currentACL['admin'] == 0:
|
||||
return proc.ajax(0, 'Only administrators can create clusters.')
|
||||
|
||||
commands = self.data['commands']
|
||||
|
||||
for command in commands:
|
||||
try:
|
||||
result = subprocess.call(command, shell=True)
|
||||
if result != 0:
|
||||
logging.writeToFile(command + ' Failed.')
|
||||
except BaseException, msg:
|
||||
logging.writeToFile(command + 'Failed.')
|
||||
return 0
|
||||
|
||||
except BaseException, msg:
|
||||
logging.writeToFile(str(msg))
|
||||
|
||||
def setUpDataNode(self):
|
||||
try:
|
||||
|
||||
userID = self.request.session['userID']
|
||||
currentACL = ACLManager.loadedACL(userID)
|
||||
proc = httpProc(self.request, None, None)
|
||||
|
||||
if currentACL['admin'] == 0:
|
||||
return proc.ajax(0, 'Only administrators can create clusters.')
|
||||
|
||||
composePath = '/home/cyberpanel/composePath'
|
||||
|
||||
if not os.path.exists(composePath):
|
||||
os.mkdir(composePath)
|
||||
|
||||
composeFile = composePath + '/docker-compose.yml'
|
||||
|
||||
compose = open(composeFile, 'w')
|
||||
for items in self.data['composeData']:
|
||||
compose.writelines(items)
|
||||
compose.close()
|
||||
|
||||
return proc.ajax(1, None)
|
||||
|
||||
except BaseException, msg:
|
||||
logging.writeToFile(str(msg))
|
||||
proc = httpProc(self.request, None, None)
|
||||
return proc.ajax(0, str(msg))
|
||||
|
||||
def submitEditCluster(self):
|
||||
try:
|
||||
|
||||
userID = self.request.session['userID']
|
||||
currentACL = ACLManager.loadedACL(userID)
|
||||
proc = httpProc(self.request, None, None)
|
||||
|
||||
if currentACL['admin'] == 0:
|
||||
return proc.ajax(0, 'Only administrators can create clusters.')
|
||||
|
||||
composePath = '/home/cyberpanel/composePath'
|
||||
composeFile = composePath + '/docker-compose.yml'
|
||||
|
||||
data = open(composeFile, 'r').readlines()
|
||||
compose = open(composeFile, 'w')
|
||||
for items in data:
|
||||
if items.find('replicas') > -1:
|
||||
compose.writelines(' replicas: ' + str(self.data['containers']) + '\n')
|
||||
elif items.find('memory') > -1:
|
||||
compose.writelines(' memory: ' + self.data['containerRam'] + '\n')
|
||||
elif items.find('cpus:') > -1:
|
||||
compose.writelines(' cpus: "' + self.data['containerCPU'] + '"\n')
|
||||
else:
|
||||
compose.writelines(items)
|
||||
compose.close()
|
||||
|
||||
return proc.ajax(1, None)
|
||||
|
||||
except BaseException, msg:
|
||||
logging.writeToFile(str(msg))
|
||||
proc = httpProc(self.request, None, None)
|
||||
return proc.ajax(0, str(msg))
|
||||
|
||||
def main():
|
||||
|
||||
parser = argparse.ArgumentParser(description='CyberPanel HA Manager')
|
||||
parser.add_argument('function', help='Specific a function to call!')
|
||||
parser.add_argument('--id', help='ID!')
|
||||
parser.add_argument('--ipAddress', help='IP Address!')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
0
highAvailability/migrations/__init__.py
Normal file
0
highAvailability/migrations/__init__.py
Normal file
6
highAvailability/models.py
Normal file
6
highAvailability/models.py
Normal file
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
||||
6
highAvailability/tests.py
Normal file
6
highAvailability/tests.py
Normal file
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
0
highAvailability/urls.py
Normal file
0
highAvailability/urls.py
Normal file
6
highAvailability/views.py
Normal file
6
highAvailability/views.py
Normal file
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
||||
@@ -57,7 +57,7 @@ class preFlightsChecks:
|
||||
def resFailed(distro, res):
|
||||
if distro == ubuntu and res != 0:
|
||||
return True
|
||||
elif distro == centos and res == 1:
|
||||
elif distro == centos and res != 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -76,7 +76,7 @@ class preFlightsChecks:
|
||||
if do_exit:
|
||||
fatal_message = '. Fatal error, see /var/log/installLogs.txt for full details'
|
||||
|
||||
preFlightsChecks.stdOut("We are not able to " + message + ' return code: ' + str(res) +
|
||||
preFlightsChecks.stdOut("[ERROR] We are not able to " + message + ' return code: ' + str(res) +
|
||||
fatal_message + " " + bracket, 1, do_exit, code)
|
||||
return False
|
||||
else:
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,43 +1,11 @@
|
||||
|
||||
import pexpect
|
||||
import installLog as logging
|
||||
import subprocess, shlex
|
||||
|
||||
class mysqlUtilities:
|
||||
|
||||
@staticmethod
|
||||
def SendQuery(user, password, dbname, query):
|
||||
try:
|
||||
expectation = "Enter password:"
|
||||
securemysql = pexpect.spawn("mysql -u "+user+" -p")
|
||||
securemysql.expect(expectation)
|
||||
securemysql.sendline(password)
|
||||
|
||||
expectation = ["Access denied for user", "Welcome to the MariaDB monitor"]
|
||||
index = securemysql.expect(expectation)
|
||||
if index == 0:
|
||||
return "Wrong Password"
|
||||
else:
|
||||
|
||||
securemysql.sendline("USE "+dbname+";")
|
||||
expectation = "Database changed"
|
||||
securemysql.expect(expectation)
|
||||
|
||||
expectation = "Query OK"
|
||||
securemysql.sendline(query);
|
||||
securemysql.expect(expectation)
|
||||
|
||||
securemysql.sendline("exit");
|
||||
|
||||
securemysql.wait()
|
||||
return 1
|
||||
except pexpect.EOF, msg:
|
||||
logging.InstallLog.writeToFile(str(msg) + " Exception EOF [SendQuery]")
|
||||
except BaseException, msg:
|
||||
logging.InstallLog.writeToFile(str(msg) + "[SendQuery]")
|
||||
|
||||
|
||||
@staticmethod
|
||||
def createDatabase(dbname,dbuser,dbpassword):
|
||||
def createDatabase(dbname, dbuser, dbpassword):
|
||||
|
||||
try:
|
||||
|
||||
@@ -47,98 +15,33 @@ class mysqlUtilities:
|
||||
data = f.read()
|
||||
password = data.split('\n', 1)[0]
|
||||
|
||||
expectation = "Enter password:"
|
||||
securemysql = pexpect.spawn("mysql -u root -p")
|
||||
securemysql.expect(expectation)
|
||||
securemysql.sendline(password)
|
||||
createDB = "CREATE DATABASE " + dbname
|
||||
|
||||
expectation = ["Access denied for user", "Welcome to the MariaDB monitor"]
|
||||
command = 'mysql -u root -p' + password + ' -e "' + createDB + '"'
|
||||
cmd = shlex.split(command)
|
||||
res = subprocess.call(cmd)
|
||||
|
||||
index = securemysql.expect(expectation)
|
||||
if res == 1:
|
||||
return 0
|
||||
|
||||
if index == 0:
|
||||
return "Wrong root Password"
|
||||
createUser = "CREATE USER '" + dbuser + "'@'localhost' IDENTIFIED BY '" + dbpassword + "'"
|
||||
|
||||
command = 'mysql -u root -p' + password + ' -e "' + createUser + '"'
|
||||
|
||||
cmd = shlex.split(command)
|
||||
res = subprocess.call(cmd)
|
||||
|
||||
if res == 1:
|
||||
return 0
|
||||
else:
|
||||
securemysql.sendline("CREATE DATABASE "+dbname+";")
|
||||
dropDB = "GRANT ALL PRIVILEGES ON " + dbname + ".* TO '" + dbuser + "'@'localhost'"
|
||||
command = 'mysql -u root -p' + password + ' -e "' + dropDB + '"'
|
||||
cmd = shlex.split(command)
|
||||
res = subprocess.call(cmd)
|
||||
|
||||
expectation = ["database exists","Query OK"]
|
||||
index = securemysql.expect(expectation)
|
||||
if res == 1:
|
||||
return 0
|
||||
|
||||
|
||||
if index == 0:
|
||||
return "This database already exists, please choose another name."
|
||||
elif index == 1:
|
||||
securemysql.sendline("CREATE USER '" +dbuser+ "'@'localhost' IDENTIFIED BY '"+dbpassword+"';")
|
||||
expectation = ["CREATE USER failed","Query OK"]
|
||||
|
||||
index = securemysql.expect(expectation)
|
||||
|
||||
if index == 0:
|
||||
securemysql.sendline("DROP DATABASE IF EXISTS "+dbname+";")
|
||||
return "This user already exists, please choose another user."
|
||||
else:
|
||||
securemysql.sendline("GRANT ALL PRIVILEGES ON " +dbname+ ".* TO '" +dbuser+ "'@'localhost';")
|
||||
expectation = "Query OK"
|
||||
securemysql.expect(expectation)
|
||||
securemysql.sendline("exit")
|
||||
securemysql.wait()
|
||||
return 1
|
||||
except pexpect.EOF, msg:
|
||||
logging.InstallLog.writeToFile(str(msg) + " Exception EOF [createDatabase]")
|
||||
except BaseException, msg:
|
||||
logging.InstallLog.writeToFile(str(msg) + "[createDatabase]")
|
||||
|
||||
@staticmethod
|
||||
def createDatabaseCyberPanel(dbname,dbuser,dbpassword, mysql):
|
||||
|
||||
try:
|
||||
|
||||
passFile = "/etc/cyberpanel/mysqlPassword"
|
||||
|
||||
f = open(passFile)
|
||||
data = f.read()
|
||||
password = data.split('\n', 1)[0]
|
||||
|
||||
expectation = "Enter password:"
|
||||
if mysql == 'Two':
|
||||
securemysql = pexpect.spawn("mysql --host=127.0.0.1 --port=3307 -u root -p")
|
||||
else:
|
||||
securemysql = pexpect.spawn("mysql -u root -p", timeout=5)
|
||||
securemysql.expect(expectation)
|
||||
securemysql.sendline(password)
|
||||
|
||||
expectation = ["Access denied for user", "Welcome to the MariaDB monitor"]
|
||||
|
||||
index = securemysql.expect(expectation)
|
||||
|
||||
if index == 0:
|
||||
return "Wrong root Password"
|
||||
else:
|
||||
securemysql.sendline("CREATE DATABASE "+dbname+";")
|
||||
|
||||
expectation = ["database exists","Query OK"]
|
||||
index = securemysql.expect(expectation)
|
||||
|
||||
|
||||
if index == 0:
|
||||
return "This database already exists, please choose another name."
|
||||
elif index == 1:
|
||||
securemysql.sendline("CREATE USER '" +dbuser+ "'@'localhost' IDENTIFIED BY '"+dbpassword+"';")
|
||||
expectation = ["CREATE USER failed","Query OK"]
|
||||
|
||||
index = securemysql.expect(expectation)
|
||||
|
||||
if index == 0:
|
||||
securemysql.sendline("DROP DATABASE IF EXISTS "+dbname+";")
|
||||
return "This user already exists, please choose another user."
|
||||
else:
|
||||
securemysql.sendline("GRANT ALL PRIVILEGES ON " +dbname+ ".* TO '" +dbuser+ "'@'localhost';")
|
||||
expectation = "Query OK"
|
||||
securemysql.expect(expectation)
|
||||
securemysql.sendline("exit")
|
||||
securemysql.wait()
|
||||
return 1
|
||||
except pexpect.EOF, msg:
|
||||
logging.InstallLog.writeToFile(str(msg) + " Exception EOF [createDatabase]")
|
||||
except BaseException, msg:
|
||||
logging.InstallLog.writeToFile(str(msg) + "[createDatabase]")
|
||||
return 0
|
||||
@@ -436,7 +436,8 @@ class ApplicationInstaller(multi.Thread):
|
||||
|
||||
if home == '0':
|
||||
path = self.extraArgs['path']
|
||||
finalURL = domainName + '/' + path
|
||||
#finalURL = domainName + '/' + path
|
||||
finalURL = domainName
|
||||
else:
|
||||
finalURL = domainName
|
||||
|
||||
|
||||
37
plogical/httpProc.py
Normal file
37
plogical/httpProc.py
Normal file
@@ -0,0 +1,37 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
from django.shortcuts import render, HttpResponse
|
||||
import json
|
||||
|
||||
class httpProc:
|
||||
def __init__(self, request, templateName, data = None):
|
||||
self.request = request
|
||||
self.templateName = templateName
|
||||
self.data = data
|
||||
|
||||
def renderPre(self):
|
||||
if self.data == None:
|
||||
return render(self.request, self.templateName)
|
||||
else:
|
||||
return render(self.request, self.templateName, self.data)
|
||||
def ajaxPre(self, status, errorMessage, success = None):
|
||||
final_dic = {'status': status, 'error_message': errorMessage, 'success': success}
|
||||
final_json = json.dumps(final_dic)
|
||||
return HttpResponse(final_json)
|
||||
|
||||
def ajax(self, status, errorMessage, data = None):
|
||||
if data == None:
|
||||
finalDic = {'status': status, 'error_message': errorMessage}
|
||||
finalJson = json.dumps(finalDic)
|
||||
return HttpResponse(finalJson)
|
||||
else:
|
||||
finalDic = {}
|
||||
finalDic['status'] = status
|
||||
finalDic['error_message'] = errorMessage
|
||||
|
||||
for key, value in data.iteritems():
|
||||
finalDic[key] = value
|
||||
|
||||
finalJson = json.dumps(finalDic)
|
||||
return HttpResponse(finalJson)
|
||||
|
||||
@@ -8,90 +8,62 @@ import subprocess
|
||||
import shlex
|
||||
from websiteFunctions.models import Websites
|
||||
from databases.models import Databases
|
||||
import MySQLdb as mysql
|
||||
|
||||
|
||||
class mysqlUtilities:
|
||||
|
||||
|
||||
@staticmethod
|
||||
def createDatabase(dbname,dbuser,dbpassword):
|
||||
|
||||
def setupConnection():
|
||||
try:
|
||||
|
||||
passFile = "/etc/cyberpanel/mysqlPassword"
|
||||
|
||||
f = open(passFile)
|
||||
data = f.read()
|
||||
password = data.split('\n', 1)[0]
|
||||
|
||||
createDB = "CREATE DATABASE "+dbname
|
||||
conn = mysql.connect(user='root', passwd=password)
|
||||
cursor = conn.cursor()
|
||||
return conn, cursor
|
||||
|
||||
command = 'sudo mysql -u root -p' + password + ' -e "' + createDB + '"'
|
||||
cmd = shlex.split(command)
|
||||
res = subprocess.call(cmd)
|
||||
except BaseException, msg:
|
||||
logging.CyberCPLogFileWriter.writeToFile(str(msg))
|
||||
return 0, 0
|
||||
|
||||
if res == 1:
|
||||
logging.CyberCPLogFileWriter.writeToFile("Can not create Database: " +dbname)
|
||||
|
||||
@staticmethod
|
||||
def createDatabase(dbname,dbuser,dbpassword):
|
||||
try:
|
||||
|
||||
connection, cursor = mysqlUtilities.setupConnection()
|
||||
|
||||
if connection == 0:
|
||||
return 0
|
||||
|
||||
createUser = "CREATE USER '" +dbuser+ "'@'localhost' IDENTIFIED BY '"+dbpassword+"'"
|
||||
|
||||
command = 'sudo mysql -u root -p' + password + ' -e "' + createUser + '"'
|
||||
|
||||
cmd = shlex.split(command)
|
||||
res = subprocess.call(cmd)
|
||||
|
||||
if res == 1:
|
||||
logging.CyberCPLogFileWriter.writeToFile("Can not create Database User: " + dbuser)
|
||||
## reverting the db creation which was created earlier
|
||||
mysqlUtilities.deleteDatabase(dbname,dbuser)
|
||||
return 0
|
||||
else:
|
||||
dropDB = "GRANT ALL PRIVILEGES ON " +dbname+ ".* TO '" +dbuser+ "'@'localhost'"
|
||||
command = 'sudo mysql -u root -p' + password + ' -e "' + dropDB + '"'
|
||||
cmd = shlex.split(command)
|
||||
res = subprocess.call(cmd)
|
||||
|
||||
if res == 1:
|
||||
mysqlUtilities.deleteDatabase(dbname, dbuser)
|
||||
logging.CyberCPLogFileWriter.writeToFile("Can not grant privileges to user: " + dbuser)
|
||||
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'")
|
||||
connection.close()
|
||||
|
||||
return 1
|
||||
|
||||
except BaseException, msg:
|
||||
mysqlUtilities.deleteDatabase(dbname, dbuser)
|
||||
logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[createDatabase]")
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def deleteDatabase(dbname, dbuser):
|
||||
|
||||
try:
|
||||
|
||||
passFile = "/etc/cyberpanel/mysqlPassword"
|
||||
connection, cursor = mysqlUtilities.setupConnection()
|
||||
|
||||
f = open(passFile)
|
||||
data = f.read()
|
||||
password = data.split('\n', 1)[0]
|
||||
|
||||
dropDB = "DROP DATABASE " + dbname
|
||||
command = 'sudo mysql -u root -p' + password + ' -e "' + dropDB + '"'
|
||||
cmd = shlex.split(command)
|
||||
res = subprocess.call(cmd)
|
||||
|
||||
|
||||
if res == 1:
|
||||
logging.CyberCPLogFileWriter.writeToFile("Can not delete Database: " + dbname)
|
||||
if connection == 0:
|
||||
return 0
|
||||
else:
|
||||
dropUser = "DROP USER '"+dbuser+"'@'localhost'"
|
||||
command = 'sudo mysql -u root -p' + password + ' -e "' + dropUser + '"'
|
||||
cmd = shlex.split(command)
|
||||
res = subprocess.call(cmd)
|
||||
|
||||
if res == 1:
|
||||
logging.CyberCPLogFileWriter.writeToFile("Can not delete Database User: " + dbuser)
|
||||
return 0
|
||||
cursor.execute("DROP DATABASE " + dbname)
|
||||
cursor.execute("DROP USER '"+dbuser+"'@'localhost'")
|
||||
connection.close()
|
||||
|
||||
return 1
|
||||
|
||||
@@ -121,7 +93,7 @@ class mysqlUtilities:
|
||||
|
||||
return 1
|
||||
except BaseException, msg:
|
||||
logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[createDatabase]")
|
||||
logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[createDatabaseBackup]")
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
@@ -146,21 +118,20 @@ class mysqlUtilities:
|
||||
logging.CyberCPLogFileWriter.writeToFile("Could not restore MYSQL database: " +databaseName +"! [restoreDatabaseBackup]")
|
||||
return 0
|
||||
|
||||
passwordCMD = "use mysql;SET PASSWORD FOR '"+databaseName+"'@'localhost' = '"+dbPassword+"';FLUSH PRIVILEGES;"
|
||||
connection, cursor = mysqlUtilities.setupConnection()
|
||||
|
||||
command = 'sudo mysql -u root -p'+password+' -e "'+passwordCMD+'"'
|
||||
cmd = shlex.split(command)
|
||||
res = subprocess.call(cmd)
|
||||
|
||||
if res == 1:
|
||||
logging.CyberCPLogFileWriter.writeToFile("Could not change password for MYSQL user: " + databaseName + "! [restoreDatabaseBackup]")
|
||||
if connection == 0:
|
||||
return 0
|
||||
|
||||
passwordCMD = "use mysql;SET PASSWORD FOR '" + databaseName + "'@'localhost' = '" + dbPassword + "';FLUSH PRIVILEGES;"
|
||||
|
||||
cursor.execute(passwordCMD)
|
||||
connection.close()
|
||||
|
||||
return 1
|
||||
except BaseException, msg:
|
||||
logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[restoreDatabaseBackup]")
|
||||
|
||||
|
||||
@staticmethod
|
||||
def submitDBCreation(dbName, dbUsername, dbPassword, databaseWebsite):
|
||||
try:
|
||||
|
||||
@@ -72,10 +72,10 @@ class ProcessUtilities:
|
||||
def executioner(command):
|
||||
try:
|
||||
res = subprocess.call(shlex.split(command))
|
||||
if res == 1:
|
||||
return 0
|
||||
else:
|
||||
if res == 0:
|
||||
return 1
|
||||
else:
|
||||
return 0
|
||||
except BaseException, msg:
|
||||
return 0
|
||||
|
||||
|
||||
@@ -54,9 +54,15 @@ class vhost:
|
||||
@staticmethod
|
||||
def createDirectories(path, virtualHostUser, pathHTML, pathLogs, confPath, completePathToConfigFile):
|
||||
try:
|
||||
|
||||
FNULL = open(os.devnull, 'w')
|
||||
|
||||
try:
|
||||
command = 'chmod 711 /home'
|
||||
cmd = shlex.split(command)
|
||||
subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT)
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
os.makedirs(path)
|
||||
|
||||
@@ -64,6 +70,10 @@ class vhost:
|
||||
cmd = shlex.split(command)
|
||||
subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT)
|
||||
|
||||
command = "chmod 711 " + path
|
||||
cmd = shlex.split(command)
|
||||
subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT)
|
||||
|
||||
except OSError, msg:
|
||||
logging.CyberCPLogFileWriter.writeToFile(
|
||||
str(msg) + " [27 Not able create to directories for virtual host [createDirectories]]")
|
||||
@@ -606,7 +616,6 @@ class vhost:
|
||||
return 0
|
||||
return 1
|
||||
|
||||
|
||||
@staticmethod
|
||||
def deleteCoreConf(virtualHostName, numberOfSites):
|
||||
if ProcessUtilities.decideServer() == ProcessUtilities.OLS:
|
||||
@@ -778,7 +787,6 @@ class vhost:
|
||||
print 0, str(msg)
|
||||
return [0, str(msg) + " [IO Error with per host config file [changePHP]]"]
|
||||
|
||||
|
||||
@staticmethod
|
||||
def addRewriteRules(virtualHostName, fileName=None):
|
||||
try:
|
||||
|
||||
@@ -1102,8 +1102,6 @@ def main():
|
||||
parser.add_argument('--openBasedirValue', help='open_base dir protection value!')
|
||||
parser.add_argument('--tempStatusPath', help='Temporary Status file path.')
|
||||
|
||||
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.function == "createVirtualHost":
|
||||
|
||||
@@ -145,7 +145,12 @@ class WebsiteManager:
|
||||
phpSelection = data['phpSelection']
|
||||
packageName = data['package']
|
||||
websiteOwner = data['websiteOwner']
|
||||
try:
|
||||
HA = data['HA']
|
||||
externalApp = 'nobody'
|
||||
except:
|
||||
externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:7]
|
||||
|
||||
tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999))
|
||||
|
||||
## Create Configurations
|
||||
|
||||
@@ -66,12 +66,12 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ng-hide="installationDetailsForm" class="form-group">
|
||||
<!--<div ng-hide="installationDetailsForm" class="form-group">
|
||||
<label class="col-sm-3 control-label">{% trans "Path" %}</label>
|
||||
<div class="col-sm-6">
|
||||
<input placeholder="Leave emtpy to install in website home directory. (Without preceding slash)" type="text" class="form-control" ng-model="installPath">
|
||||
</div>
|
||||
</div>
|
||||
</div>-->
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user