Run CyberPanel as user cyberpanel

This commit is contained in:
usmannasir 2017-11-05 03:02:51 +05:00
parent a0ddb0d556
commit 9b5ec7d12f
31 changed files with 3775 additions and 305 deletions

View File

@ -21,5 +21,6 @@ urlpatterns = [
url(r'^cyberPanelVersion', views.cyberPanelVersion, name='cyberPanelVersion'), url(r'^cyberPanelVersion', views.cyberPanelVersion, name='cyberPanelVersion'),
url(r'^putSSHkey', views.putSSHkey, name='putSSHkey'),
] ]

View File

@ -21,6 +21,8 @@ import signal
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
from shutil import rmtree from shutil import rmtree
from baseTemplate.models import version from baseTemplate.models import version
import subprocess
import shlex
# Create your views here. # Create your views here.
@ -336,10 +338,25 @@ def fetchSSHkey(request):
admin = Administrator.objects.get(userName=username) admin = Administrator.objects.get(userName=username)
if hashPassword.check_password(admin.password, password): if hashPassword.check_password(admin.password, password):
pubKey = "/root/.ssh/cyberpanel.pub" keyPath = "/home/cyberpanel/.ssh"
if not os.path.exists(keyPath):
os.makedirs(keyPath)
command = "ssh-keygen -f " + keyPath + "/cyberpanel -t rsa -N ''"
cmd = shlex.split(command)
res = subprocess.call(cmd)
else:
if not os.path.exists(keyPath+"/cyberpanel"):
command = "ssh-keygen -f " + keyPath + "/cyberpanel -t rsa -N ''"
cmd = shlex.split(command)
res = subprocess.call(cmd)
pubKey = keyPath + "/cyberpanel.pub"
f = open(pubKey) f = open(pubKey)
data = f.read() data = f.read()
data_ret = {'pubKeyStatus': 1, 'error_message': "None", "pubKey":data} data_ret = {'pubKeyStatus': 1, 'error_message': "None", "pubKey":data}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -367,6 +384,8 @@ def remoteTransfer(request):
admin = Administrator.objects.get(userName=username) admin = Administrator.objects.get(userName=username)
if hashPassword.check_password(admin.password, password): if hashPassword.check_password(admin.password, password):
dir = str(randint(1000, 9999)) dir = str(randint(1000, 9999))
transferRequest = rBackup.remoteBackup.remoteTransfer(ipAddress, dir,accountsToTransfer) transferRequest = rBackup.remoteBackup.remoteTransfer(ipAddress, dir,accountsToTransfer)
if transferRequest[0] == 1: if transferRequest[0] == 1:
@ -538,3 +557,71 @@ def cyberPanelVersion(request):
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
def putSSHkey(request):
try:
if request.method == 'POST':
data = json.loads(request.body)
adminUser = data['username']
adminPass = data['password']
pubKey = data['putSSHKey']
admin = Administrator.objects.get(userName=adminUser)
if hashPassword.check_password(admin.password, adminPass):
keyPath = "/home/cyberpanel/.ssh"
if not os.path.exists(keyPath):
os.makedirs(keyPath)
## writeKey
authorized_keys = keyPath+"/authorized_keys"
presenseCheck = 0
try:
data = open(authorized_keys, "r").readlines()
for items in data:
if items.find(pubKey) > -1:
presenseCheck = 1
except:
pass
if presenseCheck == 0:
writeToFile = open(authorized_keys, 'a')
writeToFile.writelines("#Added by CyberPanel\n")
writeToFile.writelines("\n")
writeToFile.writelines(pubKey)
writeToFile.writelines("\n")
writeToFile.close()
##
command = "sudo chmod g-w /home/cyberpanel"
cmd = shlex.split(command)
res = subprocess.call(cmd)
os.chmod(keyPath,0700)
os.chmod(authorized_keys, 0600)
data_ret = {"putSSHKey": 1,
'error_message': "None",}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
else:
data_ret = {"putSSHKey": 0,
'error_message': "Could not authorize access to API"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException, msg:
data_ret = {"putSSHKey": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)

View File

@ -18,7 +18,7 @@
<div ng-controller="backupDestinations" class="panel"> <div ng-controller="backupDestinations" class="panel">
<div class="panel-body"> <div class="panel-body">
<h3 class="title-hero"> <h3 class="title-hero">
{% trans "Set up Back up Destinations" %} <img ng-hide="destinationLoading" src="{% static 'images/loading.gif' %}"> {% trans "Set up Back up Destinations (SSH port should be 22 on backup server)" %} <img ng-hide="destinationLoading" src="{% static 'images/loading.gif' %}">
</h3> </h3>
<div class="example-box-wrapper"> <div class="example-box-wrapper">
@ -37,7 +37,7 @@
<div class="form-group"> <div class="form-group">
<label class="col-sm-3 control-label">{% trans "Password" %}</label> <label class="col-sm-3 control-label">{% trans "Password" %}</label>
<div class="col-sm-6"> <div class="col-sm-6">
<input type="password" class="form-control" ng-model="password" required> <input placeholder="{% trans "Remote server password for CyberPanel" %}" type="password" class="form-control" ng-model="password" required>
</div> </div>
</div> </div>
@ -59,7 +59,7 @@
<label class="col-sm-3 control-label"></label> <label class="col-sm-3 control-label"></label>
<div class="col-sm-4"> <div class="col-sm-4">
<div ng-hide="connectionFailed" class="alert alert-danger"> <div ng-hide="connectionFailed" class="alert alert-danger">
<p>{% trans "Connection to" %} {$ IPAddress $} {% trans "failed. Please delete and re-add." %}</p> <p>{% trans "Connection to" %} {$ IPAddress $} {% trans "failed. Please delete and re-add. " %} {$ errorMessage $} </p>
</div> </div>
<div ng-hide="connectionSuccess" class="alert alert-success"> <div ng-hide="connectionSuccess" class="alert alert-success">

View File

@ -20,6 +20,7 @@ import signal
import plogical.remoteBackup as rBackup import plogical.remoteBackup as rBackup
import requests import requests
from baseTemplate.models import version from baseTemplate.models import version
from plogical.virtualHostUtilities import virtualHostUtilities
def loadBackupHome(request): def loadBackupHome(request):
try: try:
@ -51,6 +52,12 @@ def restoreSite(request):
all_files = [] all_files = []
ext = ".tar.gz" ext = ".tar.gz"
command = 'sudo chown -R cyberpanel:cyberpanel '+path
cmd = shlex.split(command)
res = subprocess.call(cmd)
files = os.listdir(path) files = os.listdir(path)
for filename in files: for filename in files:
if filename.endswith(ext): if filename.endswith(ext):
@ -513,30 +520,51 @@ def submitDestinationCreation(request):
try: try:
dest.objects.get(destLoc=ipAddress) d = dest.objects.get(destLoc=ipAddress)
final_dic = {'destStatus': 0, 'error_message': "This destination already exists."} final_dic = {'destStatus': 0, 'error_message': "This destination already exists."}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
except: except:
status = backupUtil.backupUtilities.setupSSHKeys(ipAddress,password)
if status == 1: keyPath = "/home/cyberpanel/.ssh"
if not os.path.exists(keyPath):
os.makedirs(keyPath)
command = "ssh-keygen -f "+keyPath+"/cyberpanel -t rsa -N ''"
cmd = shlex.split(command)
res = subprocess.call(cmd)
pubKey = keyPath+"/cyberpanel.pub"
f = open(pubKey)
data = f.read()
finalData = json.dumps({'username': "admin", "password": password,"putSSHKey":data})
url = "https://" + ipAddress + ":8090/api/putSSHkey"
r = requests.post(url, data=finalData, verify=False)
data = json.loads(r.text)
if data['putSSHKey'] == 1:
newDest = dest(destLoc=ipAddress) newDest = dest(destLoc=ipAddress)
newDest.save() newDest.save()
writeToFile = open(destinations, "w")
writeToFile = open(destinations,"w") writeToFile.writelines(ipAddress + "\n")
writeToFile.writelines(ipAddress+"\n")
writeToFile.close() writeToFile.close()
backupUtil.backupUtilities.initiateBackupDirCreation(ipAddress) backupUtil.backupUtilities.initiateBackupDirCreation(ipAddress)
final_dic = {'destStatus': 1, 'error_message': "None"} final_dic = {'destStatus': 1, 'error_message': "None"}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
else: else:
final_dic = {'destStatus': 0, 'error_message': status} final_dic = {'destStatus': 0, 'error_message': data['error_message']}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
@ -599,17 +627,18 @@ def getConnectionStatus(request):
data = json.loads(request.body) data = json.loads(request.body)
ipAddress = data['IPAddress'] ipAddress = data['IPAddress']
if backupUtil.backupUtilities.checkConnection(ipAddress)==1: checkCon = backupUtil.backupUtilities.checkConnection(ipAddress)
if checkCon[0]==1:
final_dic = {'connStatus': 1, 'error_message': "None"} final_dic = {'connStatus': 1, 'error_message': "None"}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
else: else:
final_dic = {'connStatus': 0, 'error_message': "None"} final_dic = {'connStatus': 0, 'error_message': checkCon[1]}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
except BaseException,msg: except BaseException,msg:
final_dic = {'connStatus': 1, 'error_message': str(msg)} final_dic = {'connStatus': 1, 'error_message': str(msg)}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
@ -764,11 +793,15 @@ def submitBackupSchedule(request):
if backupDest == "Home" and backupFreq == "Daily": if backupDest == "Home" and backupFreq == "Daily":
cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py" cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py"
virtualHostUtilities.permissionControl(path)
writeToFile = open(path,'a') writeToFile = open(path,'a')
writeToFile.writelines(cronJob+"\n") writeToFile.writelines(cronJob+"\n")
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -782,11 +815,15 @@ def submitBackupSchedule(request):
elif backupDest == "Home" and backupFreq == "Weekly": elif backupDest == "Home" and backupFreq == "Weekly":
cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py " cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py "
virtualHostUtilities.permissionControl(path)
writeToFile = open(path, 'a') writeToFile = open(path, 'a')
writeToFile.writelines(cronJob + "\n") writeToFile.writelines(cronJob + "\n")
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -800,11 +837,15 @@ def submitBackupSchedule(request):
elif backupDest != "Home" and backupFreq == "Daily": elif backupDest != "Home" and backupFreq == "Daily":
cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py" cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py"
virtualHostUtilities.permissionControl(path)
writeToFile = open(path, 'a') writeToFile = open(path, 'a')
writeToFile.writelines(cronJob + "\n") writeToFile.writelines(cronJob + "\n")
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -818,11 +859,15 @@ def submitBackupSchedule(request):
elif backupDest != "Home" and backupFreq == "Weekly": 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)
writeToFile = open(path, 'a') writeToFile = open(path, 'a')
writeToFile.writelines(cronJob + "\n") writeToFile.writelines(cronJob + "\n")
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -836,11 +881,15 @@ def submitBackupSchedule(request):
if backupDest == "Home" and backupFreq == "Daily": if backupDest == "Home" and backupFreq == "Daily":
cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py" cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py"
virtualHostUtilities.permissionControl(path)
writeToFile = open(path, 'a') writeToFile = open(path, 'a')
writeToFile.writelines(cronJob + "\n") writeToFile.writelines(cronJob + "\n")
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -854,11 +903,15 @@ def submitBackupSchedule(request):
elif backupDest == "Home" and backupFreq == "Weekly": elif backupDest == "Home" and backupFreq == "Weekly":
cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py " cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py "
virtualHostUtilities.permissionControl(path)
writeToFile = open(path, 'a') writeToFile = open(path, 'a')
writeToFile.writelines(cronJob + "\n") writeToFile.writelines(cronJob + "\n")
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -872,11 +925,15 @@ def submitBackupSchedule(request):
elif backupDest != "Home" and backupFreq == "Daily": elif backupDest != "Home" and backupFreq == "Daily":
cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py" cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py"
virtualHostUtilities.permissionControl(path)
writeToFile = open(path, 'a') writeToFile = open(path, 'a')
writeToFile.writelines(cronJob + "\n") writeToFile.writelines(cronJob + "\n")
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -890,11 +947,15 @@ def submitBackupSchedule(request):
elif backupDest != "Home" and backupFreq == "Weekly": 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)
writeToFile = open(path, 'a') writeToFile = open(path, 'a')
writeToFile.writelines(cronJob + "\n") writeToFile.writelines(cronJob + "\n")
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -929,6 +990,8 @@ def scheduleDelete(request):
if backupDest == "Home" and backupFreq == "Daily": if backupDest == "Home" and backupFreq == "Daily":
virtualHostUtilities.permissionControl(path)
data = open(path, "r").readlines() data = open(path, "r").readlines()
writeToFile = open(path, 'w') writeToFile = open(path, 'w')
@ -940,7 +1003,9 @@ def scheduleDelete(request):
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -953,6 +1018,8 @@ def scheduleDelete(request):
elif backupDest == "Home" and backupFreq == "Weekly": elif backupDest == "Home" and backupFreq == "Weekly":
virtualHostUtilities.permissionControl(path)
data = open(path, "r").readlines() data = open(path, "r").readlines()
writeToFile = open(path, 'w') writeToFile = open(path, 'w')
@ -964,7 +1031,9 @@ def scheduleDelete(request):
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -977,6 +1046,8 @@ def scheduleDelete(request):
elif backupDest != "Home" and backupFreq == "Daily": elif backupDest != "Home" and backupFreq == "Daily":
virtualHostUtilities.permissionControl(path)
data = open(path, "r").readlines() data = open(path, "r").readlines()
writeToFile = open(path, 'w') writeToFile = open(path, 'w')
@ -988,7 +1059,9 @@ def scheduleDelete(request):
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -1001,6 +1074,8 @@ def scheduleDelete(request):
elif backupDest != "Home" and backupFreq == "Weekly": elif backupDest != "Home" and backupFreq == "Weekly":
virtualHostUtilities.permissionControl(path)
data = open(path, "r").readlines() data = open(path, "r").readlines()
writeToFile = open(path, 'w') writeToFile = open(path, 'w')
@ -1012,7 +1087,9 @@ def scheduleDelete(request):
writeToFile.close() writeToFile.close()
command = "systemctl restart crond" virtualHostUtilities.leaveControl(path)
command = "sudo systemctl restart crond"
subprocess.call(shlex.split(command)) subprocess.call(shlex.split(command))
@ -1099,37 +1176,51 @@ def submitRemoteBackups(request):
else: else:
final_json = json.dumps({'status': 0, 'error_message': sshkey[1]}) final_json = json.dumps({'status': 0, 'error_message': sshkey[1]})
return HttpResponse(final_json) return HttpResponse(final_json)
sshkey = sshkey[1]
pathToSSH = "/root/.ssh/authorized_keys" pubKey = sshkey[1]
if not os.path.exists("/root/.ssh"): keyPath = "/home/cyberpanel/.ssh"
os.makedirs("/root/.ssh")
if not os.path.exists(pathToSSH): if not os.path.exists(keyPath):
f = open(pathToSSH,"w") os.makedirs(keyPath)
f.close()
else:
if not os.path.exists(pathToSSH):
f = open(pathToSSH,"w")
f.close()
## writeKey
authorized_keys = keyPath + "/authorized_keys"
presenseCheck = 0 presenseCheck = 0
try:
data = open(pathToSSH,"r").readlines() data = open(authorized_keys, "r").readlines()
for items in data:
for items in data: if items.find(pubKey) > -1:
if items.find(sshkey)>-1: presenseCheck = 1
presenseCheck = 1 except:
pass
if presenseCheck == 0: if presenseCheck == 0:
writeToFile = open(pathToSSH, 'a') writeToFile = open(authorized_keys, 'a')
writeToFile.writelines("#Added by CyberPanel\n") writeToFile.writelines("#Added by CyberPanel\n")
writeToFile.writelines("\n") writeToFile.writelines("\n")
writeToFile.writelines(sshkey) writeToFile.writelines(pubKey)
writeToFile.writelines("\n") writeToFile.writelines("\n")
writeToFile.close() writeToFile.close()
##
command = "sudo chown cyberpanel:cyberpanel /home/cyberpanel"
cmd = shlex.split(command)
res = subprocess.call(cmd)
command = "sudo chmod g-w /home/cyberpanel"
cmd = shlex.split(command)
res = subprocess.call(cmd)
os.chmod(keyPath, 0700)
os.chmod(authorized_keys, 0600)
##
try: try:
finalData = json.dumps({'username': "admin","password": password}) finalData = json.dumps({'username': "admin","password": password})

View File

@ -1,7 +1,84 @@
/* Default color schemes */ /* Default color schemes */
@import url(https://fonts.googleapis.com/css?family=Raleway:300); /* Google imports */
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
/* latin-ext */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 300;
src: local('Raleway Light'), local('Raleway-Light'), url(https://fonts.gstatic.com/s/raleway/v12/ZKwULyCG95tk6mOqHQfRBCEAvth_LlrfE80CYdSH47w.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 300;
src: local('Raleway Light'), local('Raleway-Light'), url(https://fonts.gstatic.com/s/raleway/v12/-_Ctzj9b56b8RgXW8FArifk_vArhqVIZ0nv9q090hN8.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'), url(https://fonts.gstatic.com/s/opensans/v15/K88pR3goAWT7BTt32Z01mxJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'), url(https://fonts.gstatic.com/s/opensans/v15/RjgO7rYTmqiVp7vzi-Q5URJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'), url(https://fonts.gstatic.com/s/opensans/v15/LWCjsQkB6EMdfHrEVqA1KRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'), url(https://fonts.gstatic.com/s/opensans/v15/xozscpT2726on7jbcb_pAhJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'), url(https://fonts.gstatic.com/s/opensans/v15/59ZRklaO5bWGqF5A9baEERJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'), url(https://fonts.gstatic.com/s/opensans/v15/u-WUoqrET9fUeobQW7jkRRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'), url(https://fonts.gstatic.com/s/opensans/v15/cJZKeOuBrn4kERxqtaUH3VtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}
/* General */ /* General */

View File

@ -21,7 +21,7 @@
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.js"></script> <script src = "https://code.angularjs.org/1.6.5/angular.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="{% static 'baseTemplate/assets/images/icons/apple-touch-icon-144-precomposed.png' %}"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{% static 'baseTemplate/assets/images/icons/apple-touch-icon-144-precomposed.png' %}">

View File

@ -324,7 +324,7 @@ def changePassword(request):
passwordCMD = "use mysql;SET PASSWORD FOR '" + userName + "'@'localhost' = PASSWORD('" + dbPassword + "');FLUSH PRIVILEGES;" passwordCMD = "use mysql;SET PASSWORD FOR '" + userName + "'@'localhost' = PASSWORD('" + dbPassword + "');FLUSH PRIVILEGES;"
command = 'mysql -u root -p' + password + ' -e "' + passwordCMD + '"' command = 'sudo mysql -u root -p' + password + ' -e "' + passwordCMD + '"'
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)

View File

@ -95,7 +95,13 @@ class FileManager:
if not os.path.exists(path) or not path.startswith(self.root): if not os.path.exists(path) or not path.startswith(self.root):
return {'result': ''} return {'result': ''}
command = 'chown -R nobody:nobody '+path command = 'sudo chmod -R 775 '+path
cmd = shlex.split(command)
res = subprocess.call(cmd)
command = 'sudo chown -R nobody:cyberpanel ' + path
cmd = shlex.split(command) cmd = shlex.split(command)

View File

@ -150,7 +150,7 @@ def reloadFirewall(request):
if request.method == 'POST': if request.method == 'POST':
command = 'firewall-cmd --reload' command = 'sudo firewall-cmd --reload'
cmd = shlex.split(command) cmd = shlex.split(command)
@ -185,7 +185,7 @@ def startFirewall(request):
if request.method == 'POST': if request.method == 'POST':
command = 'systemctl start firewalld' command = 'sudo systemctl start firewalld'
cmd = shlex.split(command) cmd = shlex.split(command)
@ -220,7 +220,7 @@ def stopFirewall(request):
if request.method == 'POST': if request.method == 'POST':
command = 'systemctl stop firewalld' command = 'sudo systemctl stop firewalld'
cmd = shlex.split(command) cmd = shlex.split(command)
@ -302,6 +302,14 @@ def getSSHConfigs(request):
if type=="1": if type=="1":
## temporarily changing permission for sshd files
command = 'sudo chown -R cyberpanel:cyberpanel /etc/ssh/sshd_config'
cmd = shlex.split(command)
res = subprocess.call(cmd)
pathToSSH = "/etc/ssh/sshd_config" pathToSSH = "/etc/ssh/sshd_config"
@ -318,10 +326,27 @@ def getSSHConfigs(request):
if items.find("Port") > -1 and not items.find("GatewayPorts") > -1: if items.find("Port") > -1 and not items.find("GatewayPorts") > -1:
sshPort = items.split(" ")[1].strip("\n") sshPort = items.split(" ")[1].strip("\n")
## changing permission back
command = 'sudo chown -R root:root /etc/ssh/sshd_config'
cmd = shlex.split(command)
res = subprocess.call(cmd)
final_dic = {'permitRootLogin': permitRootLogin, 'sshPort': sshPort} final_dic = {'permitRootLogin': permitRootLogin, 'sshPort': sshPort}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
else: else:
## temporarily changing permission for sshd files
command = 'sudo chown -R cyberpanel:cyberpanel /root'
cmd = shlex.split(command)
res = subprocess.call(cmd)
pathToKeyFile = "/root/.ssh/authorized_keys" pathToKeyFile = "/root/.ssh/authorized_keys"
json_data = "[" json_data = "["
@ -352,6 +377,14 @@ def getSSHConfigs(request):
json_data = json_data + ']' json_data = json_data + ']'
## changing permission back
command = 'sudo chown -R root:root /root'
cmd = shlex.split(command)
res = subprocess.call(cmd)
final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data})
return HttpResponse(final_json) return HttpResponse(final_json)
@ -381,12 +414,13 @@ def saveSSHConfigs(request):
sshPort = data['sshPort'] sshPort = data['sshPort']
rootLogin = data['rootLogin'] rootLogin = data['rootLogin']
command = 'semanage port -a -t ssh_port_t -p tcp ' +sshPort command = 'sudo semanage port -a -t ssh_port_t -p tcp ' +sshPort
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
FirewallUtilities.addRule('tcp',sshPort) FirewallUtilities.addRule('tcp',sshPort)
try: try:
@ -399,6 +433,17 @@ def saveSSHConfigs(request):
newFireWallRule.save() newFireWallRule.save()
## temporarily changing permission for sshd files
command = 'sudo chown -R cyberpanel:cyberpanel /etc/ssh/sshd_config'
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
if rootLogin == True: if rootLogin == True:
rootLogin = "PermitRootLogin yes\n" rootLogin = "PermitRootLogin yes\n"
else: else:
@ -425,12 +470,22 @@ def saveSSHConfigs(request):
writeToFile.writelines(items) writeToFile.writelines(items)
writeToFile.close() writeToFile.close()
command = 'systemctl restart sshd' command = 'sudo systemctl restart sshd'
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
## changin back permissions
command = 'sudo chown -R root:root /etc/ssh/sshd_config'
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
final_dic = {'saveStatus': 1} final_dic = {'saveStatus': 1}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
@ -454,6 +509,16 @@ def deleteSSHKey(request):
data = json.loads(request.body) data = json.loads(request.body)
key = data['key'] key = data['key']
# temp change of permissions
command = 'sudo chown -R cyberpanel:cyberpanel /root'
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
keyPart = key.split(" ")[1] keyPart = key.split(" ")[1]
pathToSSH = "/root/.ssh/authorized_keys" pathToSSH = "/root/.ssh/authorized_keys"
@ -469,6 +534,16 @@ def deleteSSHKey(request):
writeToFile.writelines(items) writeToFile.writelines(items)
writeToFile.close() writeToFile.close()
# change back permissions
command = 'sudo chown -R root:root /root'
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
final_dic = {'delete_status': 1} final_dic = {'delete_status': 1}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
@ -492,6 +567,16 @@ def addSSHKey(request):
data = json.loads(request.body) data = json.loads(request.body)
key = data['key'] key = data['key']
# temp change of permissions
command = 'sudo chown -R cyberpanel:cyberpanel /root'
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
sshDir = "/root/.ssh" sshDir = "/root/.ssh"
pathToSSH = "/root/.ssh/authorized_keys" pathToSSH = "/root/.ssh/authorized_keys"
@ -516,6 +601,16 @@ def addSSHKey(request):
writeToFile.writelines("\n") writeToFile.writelines("\n")
writeToFile.close() writeToFile.close()
# change back permissions
command = 'sudo chown -R root:root /root'
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
final_dic = {'add_status': 1} final_dic = {'add_status': 1}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)

View File

@ -15,7 +15,7 @@ class FirewallUtilities:
def addRule(proto,port): def addRule(proto,port):
try: try:
if port == "21": if port == "21":
command = "firewall-cmd --add-service=ftp --permanent" command = "sudo firewall-cmd --add-service=ftp --permanent"
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
@ -26,7 +26,7 @@ class FirewallUtilities:
ruleProtocol = 'port protocol="' + proto + '"' ruleProtocol = 'port protocol="' + proto + '"'
rulePort = 'port="' + port + '"' rulePort = 'port="' + port + '"'
command = "firewall-cmd --permanent --zone=public --add-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'" command = "sudo firewall-cmd --permanent --zone=public --add-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'"
cmd = shlex.split(command) cmd = shlex.split(command)
@ -51,7 +51,7 @@ class FirewallUtilities:
def deleteRule(proto, port): def deleteRule(proto, port):
try: try:
if port=="21": if port=="21":
command = "firewall-cmd --remove-service=ftp --permanent" command = "sudo firewall-cmd --remove-service=ftp --permanent"
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
@ -62,7 +62,7 @@ class FirewallUtilities:
ruleProtocol = 'port protocol="' + proto + '"' ruleProtocol = 'port protocol="' + proto + '"'
rulePort = 'port="' + port + '"' rulePort = 'port="' + port + '"'
command = "firewall-cmd --permanent --zone=public --remove-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'" command = "sudo firewall-cmd --permanent --zone=public --remove-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'"
cmd = shlex.split(command) cmd = shlex.split(command)

View File

@ -5,8 +5,8 @@ After=network.target
[Service] [Service]
PIDFile=/run/gunicorn/pid PIDFile=/run/gunicorn/pid
User=root User=cyberpanel
Group=root Group=cyberpanel
RuntimeDirectory=gunicorn RuntimeDirectory=gunicorn
WorkingDirectory=/usr/local/CyberCP WorkingDirectory=/usr/local/CyberCP
ExecStart=/usr/bin/gunicorn --pid /run/gunicorn/gucpid \ ExecStart=/usr/bin/gunicorn --pid /run/gunicorn/gucpid \

View File

@ -18,6 +18,85 @@ class preFlightsChecks:
self.cwd = cwd self.cwd = cwd
self.server_root_path = rootPath self.server_root_path = rootPath
def setup_account_cyberpanel(self):
try:
command = "yum install sudo -y"
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = "adduser cyberpanel"
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = "usermod -aG wheel cyberpanel"
cmd = shlex.split(command)
res = subprocess.call(cmd)
###############################
path = "/etc/sudoers"
data = open(path,'r').readlines()
writeToFile = open(path,'w')
for items in data:
if items.find("wheel ALL=(ALL) NOPASSWD: ALL")>-1:
writeToFile.writelines("%wheel ALL=(ALL) NOPASSWD: ALL")
else:
writeToFile.writelines(items)
writeToFile.close()
###############################
command = "mkdir /etc/letsencrypt"
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = "chown cyberpanel:cyberpanel /etc/letsencrypt"
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = "usermod -a -G root cyberpanel"
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = "usermod -a -G nobody cyberpanel"
cmd = shlex.split(command)
res = subprocess.call(cmd)
except:
logging.InstallLog.writeToFile("[116] setup_account_cyberpanel")
def yum_update(self): def yum_update(self):
try: try:
@ -522,19 +601,23 @@ class preFlightsChecks:
def fix_selinux_issue(self): def fix_selinux_issue(self):
cmd = [] try:
cmd.append("setsebool") cmd = []
cmd.append("-P")
cmd.append("httpd_can_network_connect")
cmd.append("1")
res = subprocess.call(cmd) cmd.append("setsebool")
cmd.append("-P")
cmd.append("httpd_can_network_connect")
cmd.append("1")
if res == 1: res = subprocess.call(cmd)
if res == 1:
logging.InstallLog.writeToFile("fix_selinux_issue problem")
else:
pass
except BaseException,msg:
logging.InstallLog.writeToFile("fix_selinux_issue problem") logging.InstallLog.writeToFile("fix_selinux_issue problem")
else:
pass
def install_psmisc(self): def install_psmisc(self):
@ -599,7 +682,7 @@ class preFlightsChecks:
cmd = [] cmd = []
cmd.append("wget") cmd.append("wget")
cmd.append("http://cyberpanel.net/CyberPanel.1.5.tar.gz") cmd.append("http://cyberpanel.net/CyberPanelTemp.tar.gz")
res = subprocess.call(cmd) res = subprocess.call(cmd)
@ -618,7 +701,7 @@ class preFlightsChecks:
cmd.append("tar") cmd.append("tar")
cmd.append("zxf") cmd.append("zxf")
cmd.append("CyberPanel.1.5.tar.gz") cmd.append("CyberPanelTemp.tar.gz")
res = subprocess.call(cmd) res = subprocess.call(cmd)
@ -1375,7 +1458,7 @@ class preFlightsChecks:
def downoad_and_install_raindloop(self): def downoad_and_install_raindloop(self):
try: try:
command = 'chown -R nobody:nobody /usr/local/lscp/cyberpanel/' command = 'chown -R nobody:cyberpanel /usr/local/lscp/cyberpanel/'
cmd = shlex.split(command) cmd = shlex.split(command)
@ -1795,7 +1878,48 @@ class preFlightsChecks:
while (1): while (1):
command = 'chown -R nobody:nobody /usr/local/lsws' command = 'chown -R nobody:cyberpanel /usr/local/lsws'
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = 'chown -R nobody:cyberpanel /home'
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = "chown cyberpanel:cyberpanel /usr/local/lscp"
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = "sudo chmod -R 775 /home"
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = "sudo chmod -R 775 /usr/local/lsws"
cmd = shlex.split(command)
res = subprocess.call(cmd)
##
command = "sudo chmod -R 775 /etc/postfix"
cmd = shlex.split(command) cmd = shlex.split(command)
@ -1842,7 +1966,6 @@ def Main():
checks = preFlightsChecks("/usr/local/lsws/",args.publicip,"/usr/local",cwd) checks = preFlightsChecks("/usr/local/lsws/",args.publicip,"/usr/local",cwd)
checks.checkPythonVersion() checks.checkPythonVersion()
checks.yum_update() checks.yum_update()
checks.installCyberPanelRepo() checks.installCyberPanelRepo()
@ -1857,11 +1980,9 @@ def Main():
checks.install_pexpect() checks.install_pexpect()
checks.install_python_mysql_library() checks.install_python_mysql_library()
checks.install_wget() checks.install_wget()
checks.setup_account_cyberpanel()
checks.install_gunicorn() checks.install_gunicorn()
checks.install_psutil() checks.install_psutil()
checks.setup_gunicorn() checks.setup_gunicorn()
import installCyberPanel import installCyberPanel

View File

@ -644,7 +644,11 @@ class InstallCyberPanel:
print("###############################################") print("###############################################")
commad = "usermod -a -G cyberpanel ftpuser"
cmd = shlex.split(commad)
subprocess.call(cmd)
except OSError, msg: except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installPureFTPD]") logging.InstallLog.writeToFile(str(msg) + " [installPureFTPD]")
@ -933,27 +937,58 @@ class InstallCyberPanel:
while (1): while (1):
cmd.append("yum") if subprocess.check_output('systemd-detect-virt').find("openvz") > -1:
cmd.append("-y")
cmd.append("install")
cmd.append("certbot")
res = subprocess.call(cmd) command = "pip install pyOpenSSL==16.2.0"
if res == 1: cmd = shlex.split(command)
print("###############################################")
print(" Could not install CertBot ") subprocess.call(cmd)
print("###############################################")
logging.InstallLog.writeToFile("Certbot not installed" + " [installCertBot]") command = "pip install certbot"
count = count + 1
print("Trying again, try number: " + str(count)+"\n") cmd = shlex.split(command)
if count == 3:
subprocess.call(cmd)
if res == 1:
print("###############################################")
print(" Could not install CertBot ")
print("###############################################")
logging.InstallLog.writeToFile("Certbot not installed" + " [installCertBot]")
count = count + 1
print("Trying again, try number: " + str(count)+"\n")
if count == 3:
break
else:
print("###############################################")
print(" Certbot Installed ")
print("###############################################")
break break
else: else:
print("###############################################")
print(" Certbot Installed ") cmd.append("yum")
print("###############################################") cmd.append("-y")
break cmd.append("install")
cmd.append("certbot")
res = subprocess.call(cmd)
if res == 1:
print("###############################################")
print(" Could not install CertBot ")
print("###############################################")
logging.InstallLog.writeToFile("Certbot not installed" + " [installCertBot]")
count = count + 1
print("Trying again, try number: " + str(count)+"\n")
if count == 3:
break
else:
print("###############################################")
print(" Certbot Installed ")
print("###############################################")
break

View File

@ -8,14 +8,3 @@ class InstallLog:
file = open(InstallLog.fileName,'a') file = open(InstallLog.fileName,'a')
file.writelines(message + "\n") file.writelines(message + "\n")
file.close() file.close()
@staticmethod
def readLastNFiles(numberOfLines):
try:
lastFewLines = subprocess.check_output(["tail", "-n",str(numberOfLines),CyberCPLogFileWriter.fileName])
return lastFewLines
except subprocess.CalledProcessError,msg:
CyberCPLogFileWriter.writeToFile(str(msg) + "[readLastNFiles]")

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -289,8 +289,8 @@
<!-- WIDGETS --> <!-- WIDGETS -->
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.js"></script> <script src = "https://code.angularjs.org/1.6.5/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script> <script src="https://code.angularjs.org/1.6.5/angular-route.js"></script>
<script src="{% static 'loginSystem/login-systen.js' %}"></script> <script src="{% static 'loginSystem/login-systen.js' %}"></script>

View File

@ -63,22 +63,34 @@ def submitEmailCreation(request):
path = "/usr/local/CyberCP/install/rainloop/cyberpanel.net.ini" path = "/usr/local/CyberCP/install/rainloop/cyberpanel.net.ini"
if not os.path.exists("/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/"): if not os.path.exists("/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/"):
os.makedirs("/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/") command = 'sudo mkdir -p /usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains'
cmd = shlex.split(command)
res = subprocess.call(cmd)
finalPath = "/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/" + domain + ".ini" finalPath = "/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/" + domain + ".ini"
if not os.path.exists(finalPath): if not os.path.exists(finalPath):
shutil.copy(path,finalPath) command = 'sudo cp '+path +" "+finalPath
command = 'chown -R nobody:nobody /usr/local/lscp/rainloop' cmd = shlex.split(command)
res = subprocess.call(cmd)
command = 'sudo chown -R nobody:nobody /usr/local/lscp/rainloop'
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
command = 'chown -R nobody:nobody /usr/local/lscp/cyberpanel/rainloop/data/_data_' command = 'sudo chown -R nobody:nobody /usr/local/lscp/cyberpanel/rainloop/data/_data_'
cmd = shlex.split(command)
res = subprocess.call(cmd)
command = 'sudo chown -R vmail:vmail /home/vmail'
cmd = shlex.split(command) cmd = shlex.split(command)

View File

@ -251,7 +251,7 @@ def obtainHostNameSSL(request):
shutil.copy(srcPrivKey, destPrivKey) shutil.copy(srcPrivKey, destPrivKey)
shutil.copy(srcFullChain, destCert) shutil.copy(srcFullChain, destCert)
command = 'systemctl restart lscpd' command = 'sudo systemctl restart lscpd'
cmd = shlex.split(command) cmd = shlex.split(command)
@ -287,7 +287,7 @@ def obtainHostNameSSL(request):
shutil.copy(srcPrivKey, destPrivKey) shutil.copy(srcPrivKey, destPrivKey)
shutil.copy(srcFullChain, destCert) shutil.copy(srcFullChain, destCert)
command = 'systemctl restart lscpd' command = 'sudo systemctl restart lscpd'
cmd = shlex.split(command) cmd = shlex.split(command)

View File

@ -59,11 +59,10 @@ class backupSchedule:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startBackup]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startBackup]")
@staticmethod @staticmethod
def sendBackup(backupPath,IPAddress,writeToFile): def sendBackup(backupPath,IPAddress,writeToFile):
try: try:
command ='rsync -avz -e "ssh -i /root/.ssh/cyberpanel" '+ backupPath+ ' root@'+IPAddress+':/home/backup/'+time.strftime("%a-%b")+"/" command ='rsync -avz -e "ssh -i /home/cyberpanel/.ssh/cyberpanel -o StrictHostKeyChecking=no" '+ backupPath+ ' cyberpanel@'+IPAddress+':/home/backup/'+time.strftime("%a-%b")+"/"
subprocess.call(shlex.split(command),stdout=writeToFile) subprocess.call(shlex.split(command),stdout=writeToFile)

View File

@ -11,10 +11,13 @@ from multiprocessing import Process
import json import json
import requests import requests
import signal import signal
from installUtilities import installUtilities
class backupUtilities: class backupUtilities:
completeKeyPath = "/home/cyberpanel/.ssh"
@staticmethod @staticmethod
def startBackup(tempStoragePath,backupName,backupPath): def startBackup(tempStoragePath,backupName,backupPath):
try: try:
@ -24,6 +27,7 @@ class backupUtilities:
status = open(backupPath+'status',"w") status = open(backupPath+'status',"w")
status.write(backupName+"\n") status.write(backupName+"\n")
status.write("Making archive of home directory\n") status.write("Making archive of home directory\n")
logging.CyberCPLogFileWriter.writeToFile("Making archive of home directory")
status.close() status.close()
count = 0 count = 0
@ -42,6 +46,7 @@ class backupUtilities:
dbName = items.split('-')[0] dbName = items.split('-')[0]
status = open(backupPath + 'status', "w") status = open(backupPath + 'status', "w")
status.write(backupName + "\n") status.write(backupName + "\n")
logging.CyberCPLogFileWriter.writeToFile("Backing up database: " + dbName)
status.write("Backing up database: " + dbName) status.write("Backing up database: " + dbName)
status.close() status.close()
mysqlUtilities.mysqlUtilities.createDatabaseBackup(dbName, tempStoragePath) mysqlUtilities.mysqlUtilities.createDatabaseBackup(dbName, tempStoragePath)
@ -52,6 +57,7 @@ class backupUtilities:
status = open(backupPath + 'status', "w") status = open(backupPath + 'status', "w")
status.write(backupName + "\n") status.write(backupName + "\n")
logging.CyberCPLogFileWriter.writeToFile("completed")
status.write("completed\n") status.write("completed\n")
status.close() status.close()
@ -244,6 +250,14 @@ class backupUtilities:
status = open(completPath + '/status', "w") status = open(completPath + '/status', "w")
status.write("Done") status.write("Done")
status.close() status.close()
installUtilities.reStartLiteSpeed()
command = "sudo chown -R nobody:cyberpanel "+websiteHome
cmd = shlex.split(command)
subprocess.call(cmd)
except BaseException, msg: except BaseException, msg:
@ -260,8 +274,12 @@ class backupUtilities:
@staticmethod @staticmethod
def sendKey(IPAddress,password): def sendKey(IPAddress,password):
try: try:
if not os.path.exists(backupUtilities.completeKeyPath+"/cyberpanel"):
command = "ssh-keygen -f "+backupUtilities.completeKeyPath+"/cyberpanel -t rsa -N ''"
cmd = shlex.split(command)
res = subprocess.call(cmd)
sendKeyProc = pexpect.spawn("scp /root/.ssh/cyberpanel.pub root@"+IPAddress+":/root/.ssh/authorized_keys") sendKeyProc = pexpect.spawn("scp "+backupUtilities.completeKeyPath+"/cyberpanel.pub root@"+IPAddress+":"+backupUtilities.completeKeyPath+"/authorized_keys")
sendKeyProc.expect("password:") sendKeyProc.expect("password:")
sendKeyProc.sendline(password) sendKeyProc.sendline(password)
@ -284,7 +302,6 @@ class backupUtilities:
@staticmethod @staticmethod
def setupSSHKeys(IPAddress, password): def setupSSHKeys(IPAddress, password):
try: try:
## Checking for host verification ## Checking for host verification
backupUtilities.host_key_verification(IPAddress) backupUtilities.host_key_verification(IPAddress)
@ -299,7 +316,7 @@ class backupUtilities:
expectation.append("continue connecting (yes/no)?") expectation.append("continue connecting (yes/no)?")
expectation.append("password:") expectation.append("password:")
setupSSHKeys = pexpect.spawn("ssh root@"+IPAddress+" mkdir /root/.ssh") setupSSHKeys = pexpect.spawn("ssh cyberpanel@"+IPAddress+" mkdir "+backupUtilities.keyPath)
index = setupSSHKeys.expect(expectation) index = setupSSHKeys.expect(expectation)
@ -323,7 +340,7 @@ class backupUtilities:
## setting up keys. ## setting up keys.
if backupUtilities.sendKey(IPAddress,password) == 0: if backupUtilities.sendKey(IPAddress,password) == 0:
return "Can't setup connection, check CyberCP Main log file." return "Can't setup connection, check CyberPanel Main log file."
else: else:
return 1 return 1
@ -335,12 +352,10 @@ class backupUtilities:
## setting up keys. ## setting up keys.
if backupUtilities.sendKey(IPAddress,password) == 0: if backupUtilities.sendKey(IPAddress,password) == 0:
return "Can't setup connection, check CyberCP Main log file." return "Can't setup connection, check CyberPanel Main log file."
else: else:
return 1 return 1
print "keysInstalled"
else: else:
return "Wrong Password" return "Wrong Password"
@ -362,12 +377,11 @@ class backupUtilities:
## setting up keys. ## setting up keys.
if backupUtilities.sendKey(IPAddress,password) == 0: if backupUtilities.sendKey(IPAddress,password) == 0:
return "Can't setup connection, check CyberCP Main log file." return "Can't setup connection, check CyberPanel Main log file."
else: else:
return 1 return 1
elif innerIndex == 1: elif innerIndex == 1:
print "Created"
setupSSHKeys.wait() setupSSHKeys.wait()
## setting up keys. ## setting up keys.
@ -375,7 +389,7 @@ class backupUtilities:
## setting up keys. ## setting up keys.
if backupUtilities.sendKey(IPAddress,password) == 0: if backupUtilities.sendKey(IPAddress,password) == 0:
return "Can't setup connection, check CyberCP Main log file." return "Can't setup connection, check CyberPanel Main log file."
else: else:
return 1 return 1
@ -404,14 +418,12 @@ class backupUtilities:
@staticmethod @staticmethod
def checkConnection(IPAddress): def checkConnection(IPAddress):
try: try:
backupUtilities.verifyHostKey(IPAddress)
expectation = [] expectation = []
expectation.append("password:") expectation.append("password:")
expectation.append("Last login") expectation.append("Last login")
expectation.append(pexpect.EOF) expectation.append(pexpect.EOF)
checkConn = pexpect.spawn("ssh -i /root/.ssh/cyberpanel root@"+IPAddress, timeout=3) checkConn = pexpect.spawn("ssh -i /home/cyberpanel/.ssh/cyberpanel -o StrictHostKeyChecking=no cyberpanel@"+IPAddress, timeout=3)
index = checkConn.expect(expectation) index = checkConn.expect(expectation)
if index == 0: if index == 0:
@ -425,7 +437,7 @@ class backupUtilities:
subprocess.call(['kill', str(checkConn.pid)]) subprocess.call(['kill', str(checkConn.pid)])
logging.CyberCPLogFileWriter.writeToFile( logging.CyberCPLogFileWriter.writeToFile(
"Remote Server is not able to authenticate for transfer to initiate, IP Address:" + IPAddress) "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."] return [0, "Remote Server is not able to authenticate for transfer to initiate, IP Address:" + IPAddress]
except pexpect.TIMEOUT, msg: except pexpect.TIMEOUT, msg:
logging.CyberCPLogFileWriter.writeToFile("Timeout "+IPAddress+ " [checkConnection]") logging.CyberCPLogFileWriter.writeToFile("Timeout "+IPAddress+ " [checkConnection]")
@ -449,7 +461,7 @@ class backupUtilities:
expectation.append("continue connecting (yes/no)?") expectation.append("continue connecting (yes/no)?")
expectation.append("password:") expectation.append("password:")
setupSSHKeys = pexpect.spawn("ssh root@" + IPAddress) setupSSHKeys = pexpect.spawn("ssh cyberpanel@" + IPAddress, timeout=3)
index = setupSSHKeys.expect(expectation) index = setupSSHKeys.expect(expectation)
@ -509,7 +521,7 @@ class backupUtilities:
def createBackupDir(IPAddress,IPAddressA): def createBackupDir(IPAddress,IPAddressA):
try: try:
command = "ssh -i /root/.ssh/cyberpanel root@"+IPAddress+" mkdir /home/backup" command = "ssh -i /home/cyberpanel/.ssh/cyberpanel cyberpanel@"+IPAddress+" mkdir /home/backup"
shlex.split(command) shlex.split(command)
@ -522,6 +534,7 @@ class backupUtilities:
@staticmethod @staticmethod
def initiateBackupDirCreation(IPAddress): def initiateBackupDirCreation(IPAddress):
try: try:
backupUtilities.verifyHostKey(IPAddress)
thread.start_new_thread(backupUtilities.createBackupDir, (IPAddress,IPAddress)) thread.start_new_thread(backupUtilities.createBackupDir, (IPAddress,IPAddress))
except BaseException,msg: except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [initiateBackupDirCreation]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [initiateBackupDirCreation]")
@ -529,7 +542,7 @@ class backupUtilities:
@staticmethod @staticmethod
def host_key_verification(IPAddress): def host_key_verification(IPAddress):
try: try:
command = 'ssh-keygen -R '+IPAddress command = 'sudo ssh-keygen -R '+IPAddress
shlex.split(command) shlex.split(command)

View File

@ -20,13 +20,13 @@ class FirewallUtilities:
ruleProtocol = 'port protocol="' + proto + '"' ruleProtocol = 'port protocol="' + proto + '"'
rulePort = 'port="' + port + '"' rulePort = 'port="' + port + '"'
command = "firewall-cmd --permanent --zone=public --add-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'" command = "sudo firewall-cmd --permanent --zone=public --add-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'"
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
command = 'firewall-cmd --reload' command = 'sudo firewall-cmd --reload'
cmd = shlex.split(command) cmd = shlex.split(command)
@ -49,13 +49,13 @@ class FirewallUtilities:
ruleProtocol = 'port protocol="' + proto + '"' ruleProtocol = 'port protocol="' + proto + '"'
rulePort = 'port="' + port + '"' rulePort = 'port="' + port + '"'
command = "firewall-cmd --permanent --zone=public --remove-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'" command = "sudo firewall-cmd --permanent --zone=public --remove-rich-rule='" + ruleFamily + " " + sourceAddress + " " + ruleProtocol + " " + rulePort + " " + "accept'"
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
command = 'firewall-cmd --reload' command = 'sudo firewall-cmd --reload'
cmd = shlex.split(command) cmd = shlex.split(command)

View File

@ -2,6 +2,7 @@ import mysqlUtilities as sql
import subprocess import subprocess
import CyberCPLogFileWriter as logging import CyberCPLogFileWriter as logging
import os import os
import shlex
class FTPUtilities: class FTPUtilities:
@ -182,31 +183,29 @@ class FTPUtilities:
try: try:
cmd = [] command = "sudo chmod -R 775 " + directory
cmd.append("chmod")
cmd.append("-R") cmd = shlex.split(command)
cmd.append("774")
cmd.append(directory)
res = subprocess.call(cmd) res = subprocess.call(cmd)
if res == 1: if res == 1:
print "Permissions not changed." print "Permissions not changed."
return 0 return 0
else: else:
print "User permissions setted." print "User permissions setted."
cmd = []
cmd.append("chown")
cmd.append("-R") command = "sudo chown -R nobody:cyberpanel " + directory
cmd.append("nobody:nobody")
cmd.append(directory) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
if res == 1: if res == 1:
print "Permissions not changed."
return 0 return 0
else: else:
print "User permissions setted."
return 1 return 1
except BaseException, msg: except BaseException, msg:

View File

@ -5,6 +5,7 @@ import shutil
import pexpect import pexpect
import os import os
import thread import thread
import shlex
class installUtilities: class installUtilities:
@ -135,20 +136,39 @@ class installUtilities:
@staticmethod @staticmethod
def reStartLiteSpeed(): def reStartLiteSpeed():
try: try:
thread.start_new_thread(installUtilities.reStartOpenLiteSpeed, ("restart","restart")) command = "sudo systemctl restart lsws"
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [restartLiteSpeed]") cmd = shlex.split(command)
res = subprocess.call(cmd)
if res == 1:
print("###############################################")
print(" Could not restart Litespeed serve ")
print("###############################################")
sys.exit()
else:
print("###############################################")
print(" Litespeed Re-Started ")
print("###############################################")
except OSError, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [reStartLiteSpeed]")
return 0
except ValueError, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [reStartLiteSpeed]")
return 0
return 1
@staticmethod @staticmethod
def reStartOpenLiteSpeed(restart,orestart): def reStartOpenLiteSpeed(restart,orestart):
try: try:
cmd = [] command = "sudo systemctl restart lsws"
cmd.append("/usr/local/lsws/bin/lswsctrl") cmd = shlex.split(command)
cmd.append("restart")
res = subprocess.call(cmd) res = subprocess.call(cmd)

View File

@ -146,7 +146,7 @@ class mysqlUtilities:
data = f.read() data = f.read()
password = data.split('\n', 1)[0] password = data.split('\n', 1)[0]
command = 'mysqldump -u root -p'+password+' '+databaseName command = 'sudo mysqldump -u root -p'+password+' '+databaseName
cmd = shlex.split(command) cmd = shlex.split(command)
@ -170,7 +170,7 @@ class mysqlUtilities:
password = data.split('\n', 1)[0] password = data.split('\n', 1)[0]
command = 'mysql -u root -p' + password + ' ' + databaseName command = 'sudo mysql -u root -p' + password + ' ' + databaseName
cmd = shlex.split(command) cmd = shlex.split(command)
@ -184,7 +184,7 @@ class mysqlUtilities:
passwordCMD = "use mysql;SET PASSWORD FOR '"+databaseName+"'@'localhost' = '"+dbPassword+"';FLUSH PRIVILEGES;" passwordCMD = "use mysql;SET PASSWORD FOR '"+databaseName+"'@'localhost' = '"+dbPassword+"';FLUSH PRIVILEGES;"
command = 'mysql -u root -p'+password+' -e "'+passwordCMD+'"' command = 'sudo mysql -u root -p'+password+' -e "'+passwordCMD+'"'
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)

View File

@ -10,7 +10,7 @@ class phpUtilities:
def installPHPExtension(extension,extensions): def installPHPExtension(extension,extensions):
try: try:
command = 'yum install '+extension +' -y' command = 'sudo yum install '+extension +' -y'
cmd = shlex.split(command) cmd = shlex.split(command)
@ -36,7 +36,7 @@ class phpUtilities:
def unInstallPHPExtension(extension,extensions): def unInstallPHPExtension(extension,extensions):
try: try:
command = 'rpm --nodeps -e ' + extension + ' -v' command = 'sudo rpm --nodeps -e ' + extension + ' -v'
cmd = shlex.split(command) cmd = shlex.split(command)

View File

@ -252,7 +252,7 @@ class remoteBackup:
try: try:
## complete path is a path to the file need to send ## complete path is a path to the file need to send
command = 'rsync -avz -e "ssh -i /root/.ssh/cyberpanel" ' + completedPathToSend + ' root@' + IPAddress + ':/home/backup/transfer-'+folderNumber command = 'sudo rsync -avz -e "ssh -i /home/cyberpanel/.ssh/cyberpanel -o StrictHostKeyChecking=no" ' + completedPathToSend + ' cyberpanel@' + IPAddress + ':/home/backup/transfer-'+folderNumber
subprocess.call(shlex.split(command), stdout=writeToFile) subprocess.call(shlex.split(command), stdout=writeToFile)
except BaseException, msg: except BaseException, msg:
@ -321,6 +321,9 @@ class remoteBackup:
remoteBackup.sendBackup(completedPathToSend,ipAddress,str(folderNumber),writeToFile) remoteBackup.sendBackup(completedPathToSend,ipAddress,str(folderNumber),writeToFile)
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Sent " + completedPathToSend + " to " + ipAddress + ".\n")
writeToFile.writelines("[" + time.strftime( writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " #############################################" + "\n") "%I-%M-%S-%a-%b-%Y") + "]" + " #############################################" + "\n")
@ -347,18 +350,6 @@ class remoteBackup:
@staticmethod @staticmethod
def remoteTransfer(ipAddress, dir,accountsToTransfer): def remoteTransfer(ipAddress, dir,accountsToTransfer):
try: try:
## fix yes/no
verify = backupUtil.backupUtilities.verifyHostKey(ipAddress)
## if verification failed, return with error message
if verify[0] == 1:
pass
else:
return [0,verify[1]]
####
destination = "/home/backup/transfer-" + dir destination = "/home/backup/transfer-" + dir
backupLogPath = destination + "/backup_log" backupLogPath = destination + "/backup_log"

View File

@ -135,18 +135,17 @@ class sslUtilities:
@staticmethod @staticmethod
def obtainSSLForADomain(virtualHostName,adminEmail,sslpath): def obtainSSLForADomain(virtualHostName,adminEmail,sslpath):
try: try:
#if virtualHostName.count(".")==1: #if virtualHostName.count(".")==1:
# command = "certbot certonly -n --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName + " -d www." + virtualHostName # command = "sudo certbot certonly -n --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName + " -d www." + virtualHostName
#else: #else:
# command = "certbot certonly -n --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName # command = "sudo certbot certonly -n --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName
command = "certbot certonly -n --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName
command = "sudo certbot certonly -n --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName
expectation = [] expectation = []
@ -187,7 +186,7 @@ class sslUtilities:
pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem" pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem"
command = 'openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain command = 'sudo openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain
cmd = shlex.split(command) cmd = shlex.split(command)
@ -207,7 +206,7 @@ class sslUtilities:
pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem" pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem"
pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem" pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem"
command = 'openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain command = 'sudo openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain
cmd = shlex.split(command) cmd = shlex.split(command)
@ -267,7 +266,7 @@ class sslUtilities:
pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem" pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem"
pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem" pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem"
command = 'openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain command = 'sudo openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain
cmd = shlex.split(command) cmd = shlex.split(command)
@ -294,7 +293,7 @@ class sslUtilities:
pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem" pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem"
pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem" pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem"
command = 'openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain command = 'sudo openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain
cmd = shlex.split(command) cmd = shlex.split(command)
@ -302,6 +301,14 @@ class sslUtilities:
return 1 return 1
## fix permissions
command = 'sudo chown -R cyberpanel:cyberpanel /etc/letsencrypt'
cmd = shlex.split(command)
res = subprocess.call(cmd)
###### Copy SSL To config location ###### ###### Copy SSL To config location ######

View File

@ -5,73 +5,18 @@ from CyberCPLogFileWriter import CyberCPLogFileWriter as logging
import time import time
from backupUtilities import backupUtilities from backupUtilities import backupUtilities
import signal import signal
import shlex
import subprocess
def verifyHostKey(IPAddress): def verifyHostKey(directory):
try: command = "sudo chmod -R 775 " + directory
backupUtilities.host_key_verification(IPAddress)
password = "hello" print command
expectation = [] cmd = shlex.shlex(command)
expectation.append("continue connecting (yes/no)?") res = subprocess.call(cmd)
expectation.append("password:")
setupSSHKeys = pexpect.spawn("ssh root@" + IPAddress)
index = setupSSHKeys.expect(expectation)
if index == 0:
setupSSHKeys.sendline("yes")
setupSSHKeys.expect("password:")
setupSSHKeys.sendline(password)
expectation = []
expectation.append("password:")
expectation.append(pexpect.EOF)
innerIndex = setupSSHKeys.expect(expectation)
if innerIndex == 0:
setupSSHKeys.kill(signal.SIGTERM)
return [1, "None"]
elif innerIndex == 1:
setupSSHKeys.kill(signal.SIGTERM)
return [1, "None"]
elif index == 1:
setupSSHKeys.expect("password:")
setupSSHKeys.sendline(password)
expectation = []
expectation.append("password:")
expectation.append(pexpect.EOF)
innerIndex = setupSSHKeys.expect(expectation)
if innerIndex == 0:
setupSSHKeys.kill(signal.SIGTERM)
return [1, "None"]
elif innerIndex == 1:
setupSSHKeys.kill(signal.SIGTERM)
return [1, "None"]
except pexpect.TIMEOUT, msg:
logging.writeToFile("Timeout [verifyHostKey]")
return [0,"Timeout [verifyHostKey]"]
except pexpect.EOF, msg:
logging.writeToFile("EOF [verifyHostKey]")
return [0,"EOF [verifyHostKey]"]
except BaseException, msg:
logging.writeToFile(str(msg) + " [verifyHostKey]")
return [0,str(msg)+" [verifyHostKey]"]
print verifyHostKey("23.95.216.56") print verifyHostKey("/home/ssl.cyberpanel.net")

View File

@ -5,6 +5,7 @@ import shutil
import logging import logging
import CyberCPLogFileWriter as logging import CyberCPLogFileWriter as logging
import subprocess import subprocess
import shlex
class virtualHostUtilities: class virtualHostUtilities:
@ -21,13 +22,29 @@ class virtualHostUtilities:
confPath = virtualHostUtilities.Server_root + "/conf/vhosts/"+virtualHostName confPath = virtualHostUtilities.Server_root + "/conf/vhosts/"+virtualHostName
completePathToConfigFile = confPath +"/vhost.conf" completePathToConfigFile = confPath +"/vhost.conf"
try: try:
os.makedirs(path) os.makedirs(path)
except OSError,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to create directories for virtual host: "+ path+" [createDirectoryForVirtualHost]]")
return 0
try:
os.makedirs(pathHTML) os.makedirs(pathHTML)
except OSError,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to create directories for virtual host "+ pathHTML+" [createDirectoryForVirtualHost]]")
return 0
try:
os.makedirs(pathLogs) os.makedirs(pathLogs)
except OSError,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able create to directories for virtual host "+ pathLogs+" [createDirectoryForVirtualHost]]")
return 0
try:
os.makedirs(confPath) os.makedirs(confPath)
except OSError,msg: except OSError,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to directories for virtual host [createDirectoryForVirtualHost]]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able create to directories for virtual host "+ confPath+" [createDirectoryForVirtualHost]]")
return 0 return 0
@ -38,25 +55,24 @@ class virtualHostUtilities:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForVirtualHost]]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForVirtualHost]]")
return 0 return 0
try: #try:
uid = pwd.getpwnam("lsadm").pw_uid
gid = grp.getgrnam("lsadm").gr_gid
os.chown(confPath, uid, gid)
os.chown(completePathToConfigFile, uid, gid)
uid = pwd.getpwnam("nobody").pw_uid #command = "sudo chown -R nobody:cyberpanel " + completePathToConfigFile
gid = grp.getgrnam("nobody").gr_gid
os.chown("/home",uid,gid) #cmd = shlex.split(command)
os.chown(path, uid, gid)
os.chown(pathHTML, uid, gid) #res = subprocess.call(cmd)
os.chown(pathLogs, uid, gid)
#command = "sudo chown -R nobody:cyberpanel /home"
#cmd = shlex.split(command)
#res = subprocess.call(cmd)
except BaseException,msg: #except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForVirtualHost]]") # logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForVirtualHost]]")
if virtualHostUtilities.perHostVirtualConf(completePathToConfigFile,administratorEmail,phpVersion) == 1: if virtualHostUtilities.perHostVirtualConf(completePathToConfigFile,administratorEmail,phpVersion) == 1:
@ -237,13 +253,13 @@ class virtualHostUtilities:
os.makedirs(path) os.makedirs(path)
except OSError, msg: except OSError, msg:
logging.CyberCPLogFileWriter.writeToFile( logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [Not able to directories for virtual host [createDirectoryForDomain]]") str(msg) + " [Not able create to directories for virtual host [createDirectoryForDomain]]")
try: try:
os.makedirs(confPath) os.makedirs(confPath)
except OSError, msg: except OSError, msg:
logging.CyberCPLogFileWriter.writeToFile( logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [Not able to directories for virtual host [createDirectoryForDomain]]") str(msg) + " [Not able create to directories for virtual host [createDirectoryForDomain]]")
try: try:
file = open(completePathToConfigFile, "w+") file = open(completePathToConfigFile, "w+")
@ -251,20 +267,20 @@ class virtualHostUtilities:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForDomain]]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForDomain]]")
return 0 return 0
try: #try:
uid = pwd.getpwnam("lsadm").pw_uid # uid = pwd.getpwnam("lsadm").pw_uid
gid = grp.getgrnam("lsadm").gr_gid # gid = grp.getgrnam("lsadm").gr_gid
os.chown(confPath, uid, gid) # os.chown(confPath, uid, gid)
os.chown(completePathToConfigFile, uid, gid) # os.chown(completePathToConfigFile, uid, gid)
uid = pwd.getpwnam("nobody").pw_uid # uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nobody").gr_gid # gid = grp.getgrnam("nobody").gr_gid
os.chown("/home", uid, gid) # os.chown("/home", uid, gid)
os.chown(path, uid, gid) # os.chown(path, uid, gid)
except BaseException, msg: #except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForDomain]]") #logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForDomain]]")
if virtualHostUtilities.perHostDomainConf(path, masterDomain, domain, completePathToConfigFile, if virtualHostUtilities.perHostDomainConf(path, masterDomain, domain, completePathToConfigFile,
administratorEmail, phpVersion) == 1: administratorEmail, phpVersion) == 1:
@ -448,7 +464,6 @@ class virtualHostUtilities:
except BaseException,msg: except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to remove virtual host directory from /home continuing..]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to remove virtual host directory from /home continuing..]")
try: try:
confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + virtualHostName confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + virtualHostName
shutil.rmtree(confPath) shutil.rmtree(confPath)
@ -639,4 +654,28 @@ class virtualHostUtilities:
logging.CyberCPLogFileWriter.writeToFile( logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [UnsuspendVirtualHost]") str(msg) + " [UnsuspendVirtualHost]")
return 0 return 0
return 1 return 1
@staticmethod
def permissionControl(path):
try:
command = 'sudo chown -R cyberpanel:cyberpanel '+path
cmd = shlex.split(command)
res = subprocess.call(cmd)
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
@staticmethod
def leaveControl(path):
try:
command = 'sudo chown -R root:root ' + path
cmd = shlex.split(command)
res = subprocess.call(cmd)
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))

View File

@ -279,25 +279,40 @@ def submitWebsiteCreation(request):
ssl = data['ssl'] ssl = data['ssl']
## tmp change of permissions
if virtualHostUtilities.checkIfVirtualHostExists(domain) == 1: if virtualHostUtilities.checkIfVirtualHostExists(domain) == 1:
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1, data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1,
'error_message': "This domain already exists in Litespeed Configurations, first delete the domain to perform sweap."} 'error_message': "This domain already exists in Litespeed Configurations, first delete the domain to perform sweap."}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
if virtualHostUtilities.createDirectoryForVirtualHost(domain, adminEmail, phpSelection) != 1: if virtualHostUtilities.createDirectoryForVirtualHost(domain, adminEmail, phpSelection) != 1:
numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count() numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1, data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1,
'error_message': "Can not create configurations, see CyberCP main log file."} 'error_message': "Can not create configurations, see CyberPanel main log file. [createDirectoryForVirtualHost]"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
if virtualHostUtilities.createConfigInMainVirtualHostFile(domain) != 1: if virtualHostUtilities.createConfigInMainVirtualHostFile(domain) != 1:
numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count() numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1, data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1,
'error_message': "Can not create configurations, see CyberCP main log file."} 'error_message': "Can not create configurations, see CyberPanel main log file."}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -317,14 +332,17 @@ def submitWebsiteCreation(request):
numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count() numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1, data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1,
'error_message': str( 'error_message': str(
ssl_responce) + ", for more information see CyberCP main log file."} ssl_responce) + ", for more information see CyberPanel main log file."}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
## zone creation and ## zone creation
try: try:
newZone = Domains(admin=admin, name=domain, type="NATIVE") newZone = Domains(admin=admin, name=domain, type="NATIVE")
@ -389,6 +407,9 @@ def submitWebsiteCreation(request):
shutil.copy("/usr/local/CyberCP/index.html", "/home/" + domain + "/public_html/index.html") shutil.copy("/usr/local/CyberCP/index.html", "/home/" + domain + "/public_html/index.html")
data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0} data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -396,6 +417,9 @@ def submitWebsiteCreation(request):
except BaseException,msg: except BaseException,msg:
numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count() numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg),"existsStatus":0} data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg),"existsStatus":0}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -448,9 +472,13 @@ def submitDomainCreation(request):
ssl = data['ssl'] ssl = data['ssl']
path = data['path'] path = data['path']
restart = 1
####### Creation ####### Creation
try: try:
restore = data['restore'] restore = data['restore']
restart = 0
except: except:
if len(path) > 0: if len(path) > 0:
path = path.lstrip("/") path = path.lstrip("/")
@ -462,6 +490,8 @@ def submitDomainCreation(request):
master.adminEmail) != 1: master.adminEmail) != 1:
numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count() numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 0, data_ret = {"existsStatus": 1, 'createWebSiteStatus': 0,
'error_message': "Can not create configurations, see CyberCP main log file."} 'error_message': "Can not create configurations, see CyberCP main log file."}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
@ -470,26 +500,28 @@ def submitDomainCreation(request):
if virtualHostUtilities.createConfigInMainDomainHostFile(domain, masterDomain) != 1: if virtualHostUtilities.createConfigInMainDomainHostFile(domain, masterDomain) != 1:
numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count() numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 0, data_ret = {"existsStatus": 1, 'createWebSiteStatus': 0,
'error_message': "Can not create configurations, see CyberCP main log file."} 'error_message': "Can not create configurations, see CyberCP main log file."}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
if ssl == 1: if restart == 1:
installUtilities.reStartOpenLiteSpeed("restart", "ols")
else:
installUtilities.reStartLiteSpeed() installUtilities.reStartLiteSpeed()
if ssl == 1: if ssl == 1:
ssl_responce = sslUtilities.obtainSSLForADomain(domain, master.adminEmail, path) ssl_responce = sslUtilities.obtainSSLForADomain(domain, master.adminEmail, path)
if ssl_responce == 1: if ssl_responce == 1:
sslUtilities.installSSLForDomain(domain) sslUtilities.installSSLForDomain(domain)
installUtilities.reStartLiteSpeed() if restart == 1:
installUtilities.reStartLiteSpeed()
else: else:
numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count() numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1,
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 0,
'error_message': str( 'error_message': str(
ssl_responce) + ", for more information see CyberCP main log file."} ssl_responce) + ", for more information see CyberCP main log file."}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
@ -501,6 +533,9 @@ def submitDomainCreation(request):
shutil.copy("/usr/local/CyberCP/index.html", path + "/index.html") shutil.copy("/usr/local/CyberCP/index.html", path + "/index.html")
data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0} data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -508,6 +543,8 @@ def submitDomainCreation(request):
except BaseException, msg: except BaseException, msg:
numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count() numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg), "existsStatus": 0} data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg), "existsStatus": 0}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -671,9 +708,11 @@ def submitWebsiteDeletion(request):
numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count() numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(websiteName,numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(websiteName,numberOfWebsites)
delWebsite = Websites.objects.get(domain=websiteName) delWebsite = Websites.objects.get(domain=websiteName)
databases = Databases.objects.filter(website=delWebsite) databases = Databases.objects.filter(website=delWebsite)
@ -694,11 +733,16 @@ def submitWebsiteDeletion(request):
installUtilities.reStartLiteSpeed() installUtilities.reStartLiteSpeed()
data_ret = {'websiteDeleteStatus': 1,'error_message': "None"} data_ret = {'websiteDeleteStatus': 1,'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
except BaseException,msg: except BaseException,msg:
data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)} data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -727,11 +771,16 @@ def submitDomainDeletion(request):
installUtilities.reStartLiteSpeed() installUtilities.reStartLiteSpeed()
data_ret = {'websiteDeleteStatus': 1,'error_message': "None"} data_ret = {'websiteDeleteStatus': 1,'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
except BaseException,msg: except BaseException,msg:
data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)} data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -751,6 +800,9 @@ def submitWebsiteStatus(request):
website = Websites.objects.get(domain=websiteName) website = Websites.objects.get(domain=websiteName)
if state == "Suspend": if state == "Suspend":
virtualHostUtilities.suspendVirtualHost(websiteName) virtualHostUtilities.suspendVirtualHost(websiteName)
installUtilities.reStartLiteSpeed() installUtilities.reStartLiteSpeed()
@ -763,11 +815,16 @@ def submitWebsiteStatus(request):
website.save() website.save()
data_ret = {'websiteStatus': 1,'error_message': "None"} data_ret = {'websiteStatus': 1,'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
except BaseException,msg: except BaseException,msg:
data_ret = {'websiteStatus': 0, 'error_message': str(msg)} data_ret = {'websiteStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -1018,7 +1075,7 @@ def getDataFromLogFile(request):
if start <= 0: if start <= 0:
start = 1 start = 1
startingAndEnding = "'" + str(start) + "," + str(end) + "p'" startingAndEnding = "'" + str(start) + "," + str(end) + "p'"
command = "sed -n " + startingAndEnding + " " + fileName command = "sudo sed -n " + startingAndEnding + " " + fileName
proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
data = proc.stdout.read() data = proc.stdout.read()
else: else:
@ -1027,7 +1084,7 @@ def getDataFromLogFile(request):
if start <= 0: if start <= 0:
start = 1 start = 1
startingAndEnding = "'" + str(start) + "," + str(end) + "p'" startingAndEnding = "'" + str(start) + "," + str(end) + "p'"
command = "sed -n " + startingAndEnding + " " + fileName command = "sudo sed -n " + startingAndEnding + " " + fileName
proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
data = proc.stdout.read() data = proc.stdout.read()
@ -1082,7 +1139,7 @@ def fetchErrorLogs(request):
if start <= 0: if start <= 0:
start = 1 start = 1
startingAndEnding = "'" + str(start) + "," + str(end) + "p'" startingAndEnding = "'" + str(start) + "," + str(end) + "p'"
command = "sed -n " + startingAndEnding + " " + fileName command = "sudo sed -n " + startingAndEnding + " " + fileName
proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
data = proc.stdout.read() data = proc.stdout.read()
else: else:
@ -1091,7 +1148,7 @@ def fetchErrorLogs(request):
if start <= 0: if start <= 0:
start = 1 start = 1
startingAndEnding = "'" + str(start) + "," + str(end) + "p'" startingAndEnding = "'" + str(start) + "," + str(end) + "p'"
command = "sed -n " + startingAndEnding + " " + fileName command = "sudo sed -n " + startingAndEnding + " " + fileName
proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
data = proc.stdout.read() data = proc.stdout.read()
@ -1103,7 +1160,6 @@ def fetchErrorLogs(request):
return HttpResponse(final_json) return HttpResponse(final_json)
def installWordpress(request): def installWordpress(request):
try: try:
val = request.session['userID'] val = request.session['userID']
@ -1116,13 +1172,17 @@ def installWordpress(request):
finalPath = "" finalPath = ""
## temporarily changing permission for sshd files
virtualHostUtilities.permissionControl("/home/"+domainName+"/public_html")
if home == '0': if home == '0':
path = data['path'] path = data['path']
finalPath = "/home/" + domainName + "/public_html/" + path + "/" finalPath = "/home/" + domainName + "/public_html/" + path + "/"
else: else:
finalPath = "/home/" + domainName + "/public_html/" finalPath = "/home/" + domainName + "/public_html/"
if not os.path.exists(finalPath): if not os.path.exists(finalPath):
os.makedirs(finalPath) os.makedirs(finalPath)
@ -1137,8 +1197,9 @@ def installWordpress(request):
## Get wordpress ## Get wordpress
if not os.path.exists("latest.tar.gz"): if not os.path.exists("latest.tar.gz"):
command = 'wget --no-check-certificate http://wordpress.org/latest.tar.gz' command = 'wget --no-check-certificate http://wordpress.org/latest.tar.gz -O latest.tar.gz'
cmd = shlex.split(command) cmd = shlex.split(command)
@ -1150,6 +1211,7 @@ def installWordpress(request):
res = subprocess.call(cmd) res = subprocess.call(cmd)
## Get plugin ## Get plugin
if not os.path.exists("litespeed-cache.1.1.5.1.zip"): if not os.path.exists("litespeed-cache.1.1.5.1.zip"):
@ -1196,7 +1258,7 @@ def installWordpress(request):
if not os.path.exists(homeDir): if not os.path.exists(homeDir):
os.mkdir(homeDir) os.mkdir(homeDir)
command = 'chown -R nobody:nobody '+homeDir command = 'chown -R nobody:cyberpanel '+homeDir
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
@ -1213,7 +1275,7 @@ def installWordpress(request):
if not os.path.exists(homeDir): if not os.path.exists(homeDir):
os.mkdir(homeDir) os.mkdir(homeDir)
command = 'chown -R nobody:nobody ' + homeDir command = 'chown -R nobody:cyberpanel ' + homeDir
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
data_ret = {'installStatus': 0, data_ret = {'installStatus': 0,
@ -1232,7 +1294,7 @@ def installWordpress(request):
if not os.path.exists(homeDir): if not os.path.exists(homeDir):
os.mkdir(homeDir) os.mkdir(homeDir)
command = 'chown -R nobody:nobody ' + homeDir command = 'chown -R nobody:cyberpanel ' + homeDir
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
@ -1260,11 +1322,9 @@ def installWordpress(request):
if items.find("DB_NAME") > -1: if items.find("DB_NAME") > -1:
if items.find("database_name_here") > -1: if items.find("database_name_here") > -1:
writeDataToFile.writelines(defDBName) writeDataToFile.writelines(defDBName)
print ("database_name_here")
elif items.find("DB_USER") > -1: elif items.find("DB_USER") > -1:
if items.find("username_here") > -1: if items.find("username_here") > -1:
writeDataToFile.writelines(defDBUser) writeDataToFile.writelines(defDBUser)
print ("username_here")
elif items.find("DB_PASSWORD") > -1: elif items.find("DB_PASSWORD") > -1:
writeDataToFile.writelines(defDBPassword) writeDataToFile.writelines(defDBPassword)
else: else:
@ -1274,7 +1334,7 @@ def installWordpress(request):
os.rename(wpconfigfile, finalPath + 'wp-config.php') os.rename(wpconfigfile, finalPath + 'wp-config.php')
command = 'chown -R nobody:nobody ' + finalPath command = 'sudo chown -R nobody:cyberpanel ' + "/home/" + domainName + "/public_html/"
cmd = shlex.split(command) cmd = shlex.split(command)
@ -1291,12 +1351,16 @@ def installWordpress(request):
except BaseException, msg: except BaseException, msg:
# remove the downloaded files # remove the downloaded files
shutil.rmtree(finalPath) try:
shutil.rmtree(finalPath)
except:
logging.CyberCPLogFileWriter.writeToFile("shutil.rmtree(finalPath)")
homeDir = "/home/" + domainName + "/public_html" homeDir = "/home/" + domainName + "/public_html"
if not os.path.exists(homeDir): if not os.path.exists(homeDir):
os.mkdir(homeDir) os.mkdir(homeDir)
command = 'chown -R nobody:nobody ' + homeDir command = 'chown -R nobody:cyberpanel ' + homeDir
cmd = shlex.split(command) cmd = shlex.split(command)
res = subprocess.call(cmd) res = subprocess.call(cmd)
data_ret = {'installStatus': 0, 'error_message': str(msg)} data_ret = {'installStatus': 0, 'error_message': str(msg)}
@ -1306,9 +1370,11 @@ def installWordpress(request):
except KeyError, msg: except KeyError, msg:
status = {"installStatus":0,"error":str(msg)} status = {"installStatus":0,"error":str(msg)}
logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[getDataFromLogFile]") logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[installWordpress]")
return HttpResponse("Not Logged in as admin") return HttpResponse("Not Logged in as admin")
def getDataFromConfigFile(request): def getDataFromConfigFile(request):
try: try:
val = request.session['userID'] val = request.session['userID']
@ -1318,6 +1384,8 @@ def getDataFromConfigFile(request):
data = json.loads(request.body) data = json.loads(request.body)
virtualHost = data['virtualHost'] virtualHost = data['virtualHost']
filePath = installUtilities.Server_root_path + "/conf/vhosts/"+virtualHost+"/vhost.conf" filePath = installUtilities.Server_root_path + "/conf/vhosts/"+virtualHost+"/vhost.conf"
configData = open(filePath,"r").read() configData = open(filePath,"r").read()
@ -1330,6 +1398,7 @@ def getDataFromConfigFile(request):
status = {"configstatus":1,"configData":configData} status = {"configstatus":1,"configData":configData}
final_json = json.dumps(status) final_json = json.dumps(status)
@ -1357,6 +1426,8 @@ def saveConfigsToFile(request):
virtualHost = data['virtualHost'] virtualHost = data['virtualHost']
configData = data['configData'] configData = data['configData']
filePath = installUtilities.Server_root_path + "/conf/vhosts/"+virtualHost+"/vhost.conf" filePath = installUtilities.Server_root_path + "/conf/vhosts/"+virtualHost+"/vhost.conf"
vhost = open(filePath,"w") vhost = open(filePath,"w")
@ -1366,6 +1437,9 @@ def saveConfigsToFile(request):
vhost.close() vhost.close()
status = {"configstatus":1,"configData":configData} status = {"configstatus":1,"configData":configData}
final_json = json.dumps(status) final_json = json.dumps(status)
@ -1393,27 +1467,38 @@ def getRewriteRules(request):
data = json.loads(request.body) data = json.loads(request.body)
virtualHost = data['virtualHost'] virtualHost = data['virtualHost']
filePath = "/home/"+virtualHost+"/public_html/.htaccess" filePath = "/home/"+virtualHost+"/public_html/.htaccess"
try: try:
rewriteRules = open(filePath,"r").read() rewriteRules = open(filePath,"r").read()
if len(rewriteRules) == 0: if len(rewriteRules) == 0:
status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"}
status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"}
final_json = json.dumps(status) final_json = json.dumps(status)
return HttpResponse(final_json) return HttpResponse(final_json)
status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} status = {"rewriteStatus": 1, "rewriteRules": rewriteRules}
final_json = json.dumps(status) final_json = json.dumps(status)
return HttpResponse(final_json) return HttpResponse(final_json)
except IOError: except IOError:
status = {"rewriteStatus": 1, "error_message": "none","rewriteRules":""} status = {"rewriteStatus": 1, "error_message": "none","rewriteRules":""}
final_json = json.dumps(status) final_json = json.dumps(status)
return HttpResponse(final_json) return HttpResponse(final_json)
except BaseException, msg: except BaseException, msg:
data_ret = {'rewriteStatus': 0, 'error_message': str(msg)} data_ret = {'rewriteStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
@ -1436,6 +1521,9 @@ def saveRewriteRules(request):
virtualHost = data['virtualHost'] virtualHost = data['virtualHost']
rewriteRules = data['rewriteRules'] rewriteRules = data['rewriteRules']
virtualHostUtilities.addRewriteRules(virtualHost) virtualHostUtilities.addRewriteRules(virtualHost)
filePath = "/home/" + virtualHost + "/public_html/.htaccess" filePath = "/home/" + virtualHost + "/public_html/.htaccess"
@ -1447,6 +1535,9 @@ def saveRewriteRules(request):
vhost.close() vhost.close()
status = {"rewriteStatus":1} status = {"rewriteStatus":1}
final_json = json.dumps(status) final_json = json.dumps(status)
@ -1477,6 +1568,9 @@ def saveSSL(request):
cert = data['cert'] cert = data['cert']
key = data['key'] key = data['key']
pathToStoreSSL = virtualHostUtilities.Server_root + "/conf/vhosts/" + "SSL-" + domain pathToStoreSSL = virtualHostUtilities.Server_root + "/conf/vhosts/" + "SSL-" + domain
website = Websites.objects.get(domain=domain) website = Websites.objects.get(domain=domain)
@ -1504,6 +1598,9 @@ def saveSSL(request):
website.ssl = 1 website.ssl = 1
website.save() website.save()
data_ret = {'sslStatus': 1, 'error_message': "None"} data_ret = {'sslStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -1532,6 +1629,9 @@ def saveSSL(request):
website.ssl = 1 website.ssl = 1
website.save() website.save()
data_ret = {'sslStatus': 1, 'error_message': "None"} data_ret = {'sslStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -1572,6 +1672,8 @@ def CreateWebsiteFromBackup(request):
originalFile = "/home/backup/" + data['backupFile'] originalFile = "/home/backup/" + data['backupFile']
if not os.path.exists(originalFile): if not os.path.exists(originalFile):
dir = data['dir'] dir = data['dir']
path = "/home/backup/transfer-"+str(dir)+"/"+backupFile path = "/home/backup/transfer-"+str(dir)+"/"+backupFile
@ -1607,11 +1709,16 @@ def CreateWebsiteFromBackup(request):
check = 0 check = 0
dbCheck = 0 dbCheck = 0
for items in data: for items in data:
if check == 0: if check == 0:
if virtualHostUtilities.createDirectoryForVirtualHost(domain, adminEmail, phpSelection) != 1: if virtualHostUtilities.createDirectoryForVirtualHost(domain, adminEmail, phpSelection) != 1:
numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count() numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1, data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1,
'error_message': "Can not create configurations, see CyberCP main log file."} 'error_message': "Can not create configurations, see CyberCP main log file."}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
@ -1620,13 +1727,13 @@ def CreateWebsiteFromBackup(request):
if virtualHostUtilities.createConfigInMainVirtualHostFile(domain) != 1: if virtualHostUtilities.createConfigInMainVirtualHostFile(domain) != 1:
numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count() numberOfWebsites = Websites.objects.count()+ChildDomains.objects.count()
virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites) virtualHostUtilities.deleteVirtualHostConfigurations(domain, numberOfWebsites)
data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1, data_ret = {"existsStatus": 1, 'createWebSiteStatus': 1,
'error_message': "Can not create configurations, see CyberCP main log file."} 'error_message': "Can not create configurations, see CyberCP main log file."}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
installUtilities.reStartLiteSpeed()
selectedPackage = Package.objects.get(packageName="Default") selectedPackage = Package.objects.get(packageName="Default")
website = Websites(admin=admin, package=selectedPackage, domain=domain, adminEmail=adminEmail, website = Websites(admin=admin, package=selectedPackage, domain=domain, adminEmail=adminEmail,
@ -1652,6 +1759,9 @@ def CreateWebsiteFromBackup(request):
status.write("Accounts and DBs Created") status.write("Accounts and DBs Created")
status.close() status.close()
data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0} data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)
@ -1682,6 +1792,7 @@ def changePHP(request):
installUtilities.reStartLiteSpeed() installUtilities.reStartLiteSpeed()
data_ret = {'changePHP': 1,'error_message': "None"} data_ret = {'changePHP': 1,'error_message': "None"}
json_data = json.dumps(data_ret) json_data = json.dumps(data_ret)
return HttpResponse(json_data) return HttpResponse(json_data)