diff --git a/backup/views.py b/backup/views.py
index ba735d95d..0e44e58d0 100644
--- a/backup/views.py
+++ b/backup/views.py
@@ -13,10 +13,8 @@ from loginSystem.views import loadLoginPage
import os
import time
import plogical.backupUtilities as backupUtil
-from shutil import rmtree
import shlex
import subprocess
-import signal
import requests
from baseTemplate.models import version
from plogical.virtualHostUtilities import virtualHostUtilities
@@ -26,7 +24,6 @@ from xml.etree import ElementTree
from xml.dom import minidom
from dns.models import Domains,Records
from mailServer.models import Domains as eDomains
-from mailServer.models import EUsers
from plogical.mailUtilities import mailUtilities
@@ -180,13 +177,12 @@ def submitBackupCreation(request):
if request.method == 'POST':
data = json.loads(request.body)
- backupDomain = data['websiteToBeBacked']
+ backupDomain = data['websiteToBeBacked']
website = Websites.objects.get(domain=backupDomain)
## defining paths
-
## /home/example.com/backup
backupPath = os.path.join("/home",backupDomain,"backup/")
domainUser = website.externalApp
@@ -195,160 +191,12 @@ def submitBackupCreation(request):
## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018
tempStoragePath = os.path.join(backupPath,backupName)
- ## Generating meta
-
- ## XML Generation
-
- metaFileXML = Element('metaFile')
-
- child = SubElement(metaFileXML, 'masterDomain')
- child.text = backupDomain
-
- child = SubElement(metaFileXML, 'phpSelection')
- child.text = website.phpSelection
-
- child = SubElement(metaFileXML, 'externalApp')
- child.text = website.externalApp
-
-
- childDomains = website.childdomains_set.all()
-
- databases = website.databases_set.all()
-
- ## Child domains XML
-
- childDomainsXML = Element('ChildDomains')
-
- for items in childDomains:
-
- childDomainXML = Element('domain')
-
- child = SubElement(childDomainXML, 'domain')
- child.text = items.domain
- child = SubElement(childDomainXML, 'phpSelection')
- child.text = items.phpSelection
- child = SubElement(childDomainXML, 'path')
- child.text = items.path
-
- childDomainsXML.append(childDomainXML)
-
-
- metaFileXML.append(childDomainsXML)
-
- ## Databases XML
-
- databasesXML = Element('Databases')
-
- for items in databases:
- dbuser = DBUsers.objects.get(user=items.dbUser)
-
- databaseXML = Element('database')
-
- child = SubElement(databaseXML, 'dbName')
- child.text = items.dbName
- child = SubElement(databaseXML, 'dbUser')
- child.text = items.dbUser
- child = SubElement(databaseXML, 'password')
- child.text = dbuser.password
-
- databasesXML.append(databaseXML)
-
- metaFileXML.append(databasesXML)
-
-
- ## Get Aliases
-
- aliasesXML = Element('Aliases')
-
- aliases = backupUtil.backupUtilities.getAliases(backupDomain)
-
- for items in aliases:
-
- child = SubElement(aliasesXML, 'alias')
- child.text = items
-
- metaFileXML.append(aliasesXML)
-
-
- ## Finish Alias
-
- ## DNS Records XML
-
- try:
- dnsRecordsXML = Element("dnsrecords")
- domain = Domains.objects.get(name=backupDomain)
- dnsRecords = Records.objects.filter(domain_id=domain.id)
-
- for items in dnsRecords:
- dnsRecordXML = Element('dnsrecord')
-
- child = SubElement(dnsRecordXML, 'type')
- child.text = items.type
- child = SubElement(dnsRecordXML, 'name')
- child.text = items.name
- child = SubElement(dnsRecordXML, 'content')
- child.text = items.content
- child = SubElement(dnsRecordXML, 'priority')
- child.text = str(items.prio)
-
- dnsRecordsXML.append(dnsRecordXML)
-
- metaFileXML.append(dnsRecordsXML)
-
- except BaseException,msg:
- logging.CyberCPLogFileWriter.writeToFile(str(msg))
-
- ## Email accounts XML
-
- try:
- emailRecordsXML = Element('emails')
- eDomain = eDomains.objects.get(domain=backupDomain)
- emailAccounts = eDomain.eusers_set.all()
-
- for items in emailAccounts:
- emailRecordXML = Element('emailAccount')
-
- child = SubElement(emailRecordXML, 'email')
- child.text = items.email
- child = SubElement(emailRecordXML, 'password')
- child.text = items.password
-
- emailRecordsXML.append(emailRecordXML)
-
- metaFileXML.append(emailRecordsXML)
-
- except BaseException,msg:
- logging.CyberCPLogFileWriter.writeToFile(str(msg))
-
- ## Email meta generated!
-
-
- def prettify(elem):
- """Return a pretty-printed XML string for the Element.
- """
- rough_string = ElementTree.tostring(elem, 'utf-8')
- reparsed = minidom.parseString(rough_string)
- return reparsed.toprettyxml(indent=" ")
-
- ## /home/cyberpanel/1047.xml
- metaPath = os.path.join("/home", "cyberpanel", str(randint(1000, 9999)) + ".xml")
-
- xmlpretty = prettify(metaFileXML).encode('ascii', 'ignore')
- metaFile = open(metaPath,'w')
- metaFile.write(xmlpretty)
- metaFile.close()
-
- ## meta generated
-
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py"
- execPath = execPath + " submitBackupCreation --tempStoragePath " + tempStoragePath + " --backupName " + backupName + " --backupPath " + backupPath + " --metaPath " + metaPath
+ execPath = execPath + " submitBackupCreation --tempStoragePath " + tempStoragePath + " --backupName " \
+ + backupName + " --backupPath " + backupPath + ' --backupDomain ' + backupDomain
subprocess.Popen(shlex.split(execPath))
- newBackup = Backups(website=website, fileName=backupName, date=time.strftime("%I-%M-%S-%a-%b-%Y"),
- size=0, status=0)
- newBackup.save()
-
time.sleep(2)
final_json = json.dumps({'metaStatus': 1, 'error_message': "None", 'tempStorage': tempStoragePath})
@@ -557,6 +405,8 @@ def restoreStatus(request):
if os.path.exists(path):
path = os.path.join("/home","backup",backupFile)
+ elif os.path.exists(data['backupFile']):
+ path = data['backupFile'].strip(".tar.gz")
else:
dir = data['dir']
path = "/home/backup/transfer-" + str(dir) + "/" + backupFile
diff --git a/cli/cliParser.py b/cli/cliParser.py
new file mode 100644
index 000000000..93f081114
--- /dev/null
+++ b/cli/cliParser.py
@@ -0,0 +1,58 @@
+import argparse
+
+class cliParser:
+
+ def prepareArguments(self):
+ ## Website creation arguemtns
+
+ parser = argparse.ArgumentParser(description='CyberPanel Command Line Interface!')
+ parser.add_argument('function', help='Specific a operation to perform!')
+
+ parser.add_argument('--package', help='Select a package for website.')
+ parser.add_argument('--owner', help='Select a website owner.')
+ parser.add_argument('--masterDomain',
+ help='Master domain argument, which is required for creating child domains!')
+ parser.add_argument('--childDomain',
+ help='Child domain argument, which is required for creating child domains!')
+ parser.add_argument('--domainName', help='Domain name!')
+ parser.add_argument('--email', help='Administrator email.')
+ parser.add_argument('--php', help='PHP Selection.')
+ parser.add_argument('--ssl', help='Weather to obtain SSL.')
+ parser.add_argument('--dkim', help='DKIM Signing')
+ parser.add_argument('--openBasedir', help='To enable or disable open_basedir protection for domain.')
+ parser.add_argument('--fileName', help='Complete path to a file that needs to be restored.')
+
+ ## Package arguments.
+
+ parser.add_argument('--packageName', help='Package name.')
+ parser.add_argument('--diskSpace', help='Package disk space in MBs')
+ parser.add_argument('--bandwidth', help='Package bandwidth in MBs.')
+ parser.add_argument('--emailAccounts', help='Number of allowed email accounts for Package.')
+ parser.add_argument('--dataBases', help='Number of allowed databases for Package.')
+ parser.add_argument('--ftpAccounts', help='Number of allowed ftp accounts for Package.')
+ parser.add_argument('--allowedDomains', help='Number of allowed child domains for Package.')
+
+
+ ## DNS Arguments
+
+ parser.add_argument('--name', help='DNS Record Name.')
+ parser.add_argument('--recordType', help='DNS Record type.')
+ parser.add_argument('--value', help='DNS Record value.')
+ parser.add_argument('--priority', help='Priority for DNS Record.')
+ parser.add_argument('--ttl', help='TTL for DNS Record')
+ parser.add_argument('--recordID', help='DNS Record ID to be deleted.')
+
+ ## Database Arguments
+
+ parser.add_argument('--dbName', help='Database name.')
+ parser.add_argument('--dbUsername', help='Datbase username.')
+ parser.add_argument('--dbPassword', help='Database password.')
+ parser.add_argument('--databaseWebsite', help='Database website.')
+
+ ## Email arguments
+ parser.add_argument('--userName', help='Email Username.')
+ parser.add_argument('--password', help='Email password.')
+
+
+
+ return parser.parse_args()
\ No newline at end of file
diff --git a/cli/cyberPanel.py b/cli/cyberPanel.py
index 2863d00e8..65da7b76b 100755
--- a/cli/cyberPanel.py
+++ b/cli/cyberPanel.py
@@ -11,16 +11,30 @@ import json
from plogical.virtualHostUtilities import virtualHostUtilities
import re
from websiteFunctions.models import Websites, ChildDomains
+from plogical.dnsUtilities import DNS
+import time
+import plogical.backupUtilities as backupUtilities
+import requests
+from loginSystem.models import Administrator
+from packages.models import Package
+from plogical.mysqlUtilities import mysqlUtilities
+from cliParser import cliParser
from plogical.vhost import vhost
+from plogical.mailUtilities import mailUtilities
+from plogical.ftpUtilities import FTPUtilities
+
+# All that we see or seem is but a dream within a dream.
class cyberPanel:
+
def printStatus(self, operationStatus, errorMessage):
data = json.dumps({'success': operationStatus,
'errorMessage': errorMessage
})
-
print data
+ ## Website Functions
+
def createWebsite(self, package, owner, domainName, email, php, ssl, dkim, openBasedir):
try:
externalApp = "".join(re.findall("[a-zA-Z]+", domainName))[:7]
@@ -40,6 +54,23 @@ class cyberPanel:
logger.writeforCLI(str(msg), "Error", stack()[0][3])
self.printStatus(0, str(msg))
+ def createDomain(self, masterDomain, domainName, owner, php, ssl, dkim, openBasedir):
+ try:
+
+ path = '/home/' + masterDomain + '/public_html/' + domainName
+ phpSelection = 'PHP ' + php
+
+ result = virtualHostUtilities.createDomain(masterDomain, domainName, phpSelection, path, ssl, dkim, openBasedir, '0', owner)
+
+ if result[0] == 1:
+ self.printStatus(1,'None')
+ else:
+ self.printStatus(0, result[1])
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
def deleteWebsite(self, domainName):
try:
@@ -51,26 +82,719 @@ class cyberPanel:
logger.writeforCLI(str(msg), "Error", stack()[0][3])
print 0
+ def deleteChild(self, childDomain):
+ try:
+ result = virtualHostUtilities.deleteDomain(childDomain)
+
+ if result[0] == 1:
+ self.printStatus(1,'None')
+ else:
+ self.printStatus(0, result[1])
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def listWebsitesJson(self):
+ try:
+
+ websites = Websites.objects.all()
+ ipFile = "/etc/cyberpanel/machineIP"
+ f = open(ipFile)
+ ipData = f.read()
+ ipAddress = ipData.split('\n', 1)[0]
+
+ json_data = "["
+ checker = 0
+
+ for items in websites:
+ if items.state == 0:
+ state = "Suspended"
+ else:
+ state = "Active"
+ dic = {'domain': items.domain, 'adminEmail': items.adminEmail,'ipAddress':ipAddress,'admin': items.admin.userName,'package': items.package.packageName,'state':state}
+
+ if checker == 0:
+ json_data = json_data + json.dumps(dic)
+ checker = 1
+ else:
+ json_data = json_data +',' + json.dumps(dic)
+
+ json_data = json_data + ']'
+ final_json = json.dumps(json_data)
+ print final_json
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def listWebsitesPretty(self):
+ try:
+ from prettytable import PrettyTable
+
+ websites = Websites.objects.all()
+ ipFile = "/etc/cyberpanel/machineIP"
+ f = open(ipFile)
+ ipData = f.read()
+ ipAddress = ipData.split('\n', 1)[0]
+
+ table = PrettyTable(['ID','Domain', 'IP Address', 'Package', 'Owner', 'State', 'Email'])
+
+ for items in websites:
+ if items.state == 0:
+ state = "Suspended"
+ else:
+ state = "Active"
+ table.add_row([items.id, items.domain, ipAddress, items.package.packageName, items.admin.userName, state, items.adminEmail])
+ print table
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def changePHP(self, virtualHostName, phpVersion):
+ try:
+
+ phpVersion = 'PHP ' + phpVersion
+
+ confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + virtualHostName
+ completePathToConfigFile = confPath + "/vhost.conf"
+
+ result = vhost.changePHP(completePathToConfigFile, phpVersion)
+
+ if result[0] == 1:
+ self.printStatus(1,'None')
+ else:
+ self.printStatus(0, result[1])
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def changePackage(self, virtualHostName, packageName):
+ try:
+ if Websites.objects.filter(domain=virtualHostName).count() == 0:
+ self.printStatus(0, 'This website does not exists.')
+ if Package.objects.filter(packageName=packageName).count() == 0:
+ self.printStatus(0, 'This package does not exists.')
+
+ website = Websites.objects.get(domain=virtualHostName)
+ package = Package.objects.get(packageName=packageName)
+
+ website.package = package
+ website.save()
+
+ self.printStatus(1, 'None')
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+
+ ## DNS Functions
+
+ def listDNSJson(self, virtualHostName):
+ try:
+
+ records = DNS.getDNSRecords(virtualHostName)
+
+ json_data = "["
+ checker = 0
+
+ for items in records:
+ dic = {'id': items.id,
+ 'type': items.type,
+ 'name': items.name,
+ 'content': items.content,
+ 'priority': items.prio,
+ 'ttl': items.ttl
+ }
+
+ if checker == 0:
+ json_data = json_data + json.dumps(dic)
+ checker = 1
+ else:
+ json_data = json_data + ',' + json.dumps(dic)
+
+ json_data = json_data + ']'
+ final_json = json.dumps(json_data)
+ print final_json
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def listDNSPretty(self, virtualHostName):
+ try:
+ from prettytable import PrettyTable
+
+ records = DNS.getDNSRecords(virtualHostName)
+
+ table = PrettyTable(['ID', 'TYPE', 'Name', 'Value', 'Priority', 'TTL'])
+ for items in records:
+ if len(items.content) >= 30:
+ content = items.content[0:30] + " ..."
+ else:
+ content = items.content
+ table.add_row([items.id, items.type, items.name, content, items.prio, items.ttl])
+ print table
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def listDNSZonesJson(self):
+ try:
+
+ records = DNS.getDNSZones()
+
+ json_data = "["
+ checker = 0
+
+ for items in records:
+ dic = {'id': items.id,
+ 'name': items.name,
+ }
+
+ if checker == 0:
+ json_data = json_data + json.dumps(dic)
+ checker = 1
+ else:
+ json_data = json_data + ',' + json.dumps(dic)
+
+ json_data = json_data + ']'
+ final_json = json.dumps(json_data)
+ print final_json
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def listDNSZonesPretty(self):
+ try:
+ from prettytable import PrettyTable
+
+ records = records = DNS.getDNSZones()
+
+ table = PrettyTable(['ID', 'Name'])
+
+ for items in records:
+ table.add_row([items.id, items.name])
+ print table
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def createDNSZone(self, virtualHostName, owner):
+ try:
+ admin = Administrator.objects.get(userName=owner)
+ DNS.dnsTemplate(virtualHostName, admin)
+ self.printStatus(1, 'None')
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def createDNSRecord(self, virtualHostName, name, recordType, value, priority, ttl):
+ try:
+ zone = DNS.getZoneObject(virtualHostName)
+ DNS.createDNSRecord(zone, name, recordType, value, int(priority), int(ttl))
+ self.printStatus(1, 'None')
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def deleteDNSZone(self, virtualHostName):
+ try:
+ DNS.deleteDNSZone(virtualHostName)
+ self.printStatus(1, 'None')
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def deleteDNSRecord(self, recordID):
+ try:
+ DNS.deleteDNSRecord(recordID)
+ self.printStatus(1, 'None')
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ ## Backup Functions
+
+ def createBackup(self, virtualHostName):
+ try:
+ website = Websites.objects.get(domain=virtualHostName)
+
+ ## defining paths
+
+ ## /home/example.com/backup
+ backupPath = os.path.join("/home", virtualHostName, "backup/")
+ domainUser = website.externalApp
+ backupName = 'backup-' + domainUser + "-" + time.strftime("%I-%M-%S-%a-%b-%Y")
+
+ ## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018
+ tempStoragePath = os.path.join(backupPath, backupName)
+
+ backupUtilities.submitBackupCreation(tempStoragePath, backupName, backupPath, virtualHostName)
+
+ finalData = json.dumps({'websiteToBeBacked': virtualHostName})
+
+ while (1):
+ r = requests.post("http://localhost:5003/backup/backupStatus", data=finalData)
+ time.sleep(2)
+ data = json.loads(r.text)
+
+ if data['backupStatus'] == 0:
+ print 'Failed to generate backup, Error message : ' + data['error_message'] + '\n'
+ break
+ elif data['abort'] == 1:
+ print 'Backup successfully generated.\n'
+ print 'File Location: ' + tempStoragePath + ".tar.gz\n"
+ break
+ else:
+ print 'Waiting for backup to complete. Current status: ' + data['status']
+
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def restoreBackup(self, fileName):
+ try:
+ if os.path.exists('/home/backup/' + fileName):
+ dir = "CyberPanelRestore"
+ else:
+ dir = 'CLI'
+
+ backupUtilities.submitRestore(fileName, dir)
+
+ while (1):
+ time.sleep(1)
+ finalData = json.dumps({'backupFile': fileName, "dir": dir})
+ r = requests.post("http://localhost:5003/backup/restoreStatus", data=finalData,
+ verify=False)
+ data = json.loads(r.text)
+
+ if data['abort'] == 1 and data['running'] == "Error":
+ print 'Failed to restore backup, Error message : ' + data['status'] + '\n'
+ break
+ elif data['abort'] == 1 and data['running'] == "Completed":
+ print '\n\n'
+ print 'Backup restore completed.\n'
+ break
+ else:
+ print 'Waiting for restore to complete. Current status: ' + data['status']
+
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ ## Packages
+
+ def createPackage(self, owner, packageName, diskSpace, bandwidth, emailAccounts, dataBases, ftpAccounts, allowedDomains):
+ try:
+
+ admin = Administrator.objects.get(userName=owner)
+
+ newPack = Package(admin=admin, packageName=packageName, diskSpace=diskSpace, bandwidth=bandwidth,
+ emailAccounts=emailAccounts, dataBases=dataBases, ftpAccounts=ftpAccounts,
+ allowedDomains=allowedDomains)
+
+ newPack.save()
+
+ self.printStatus(1, 'None')
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def deletePackage(self, packageName):
+ try:
+
+ delPack = Package.objects.get(packageName=packageName)
+ delPack.delete()
+ self.printStatus(1, 'None')
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def listPackagesJson(self):
+ try:
+
+ records = Package.objects.all()
+
+ json_data = "["
+ checker = 0
+
+ for items in records:
+ dic = {'id': items.id,
+ 'packageName': items.packageName,
+ 'domains': items.allowedDomains,
+ 'diskSpace': items.diskSpace,
+ 'bandwidth': items.bandwidth,
+ 'ftpAccounts ': items.ftpAccounts,
+ 'dataBases': items.dataBases,
+ 'emailAccounts':items.emailAccounts
+ }
+
+ if checker == 0:
+ json_data = json_data + json.dumps(dic)
+ checker = 1
+ else:
+ json_data = json_data + ',' + json.dumps(dic)
+
+ json_data = json_data + ']'
+ final_json = json.dumps(json_data)
+ print final_json
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def listPackagesPretty(self):
+ try:
+ from prettytable import PrettyTable
+
+ records = Package.objects.all()
+
+ table = PrettyTable(['Name', 'Domains', 'Disk Space', 'Bandwidth', 'FTP Accounts', 'Databases', 'Email Accounts'])
+
+ for items in records:
+ table.add_row([items.packageName, items.allowedDomains, items.diskSpace, items.bandwidth, items.ftpAccounts, items.dataBases, items.emailAccounts])
+ print table
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+
+ ## Database functions
+
+ def createDatabase(self, dbName, dbUsername, dbPassword, databaseWebsite):
+ try:
+
+ result = mysqlUtilities.submitDBCreation(dbName, dbUsername, dbPassword, databaseWebsite)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def deleteDatabase(self, dbName):
+ try:
+
+ result = mysqlUtilities.submitDBDeletion(dbName)
+
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def listDatabasesJson(self, virtualHostName):
+ try:
+
+ records = mysqlUtilities.getDatabases(virtualHostName)
+
+ json_data = "["
+ checker = 0
+
+ for items in records:
+ dic = {'id': items.id,
+ 'dbName': items.dbName,
+ 'dbUser': items.dbUser,
+ }
+
+ if checker == 0:
+ json_data = json_data + json.dumps(dic)
+ checker = 1
+ else:
+ json_data = json_data + ',' + json.dumps(dic)
+
+ json_data = json_data + ']'
+ final_json = json.dumps(json_data)
+ print final_json
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def listDatabasesPretty(self, virtualHostName):
+ try:
+ from prettytable import PrettyTable
+
+ records = mysqlUtilities.getDatabases(virtualHostName)
+
+ table = PrettyTable(['ID', 'Database Name', 'Database User'])
+
+ for items in records:
+ table.add_row([items.id, items.dbName, items.dbUser])
+ print table
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ ## Email functions
+
+ def createEmail(self, domain, userName, password):
+ try:
+
+ result = mailUtilities.createEmailAccount(domain, userName, password)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def deleteEmail(self, email):
+ try:
+
+ result = mailUtilities.deleteEmailAccount(email)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def changeEmailPassword(self, email, password):
+ try:
+
+ result = mailUtilities.changeEmailPassword(email, password)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def listEmailsJson(self, virtualHostName):
+ try:
+
+ records = mailUtilities.getEmailAccounts(virtualHostName)
+
+ json_data = "["
+ checker = 0
+
+ for items in records:
+ dic = {
+ 'email': items.email,
+ }
+
+ if checker == 0:
+ json_data = json_data + json.dumps(dic)
+ checker = 1
+ else:
+ json_data = json_data + ',' + json.dumps(dic)
+
+ json_data = json_data + ']'
+ final_json = json.dumps(json_data)
+ print final_json
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def listEmailsPretty(self, virtualHostName):
+ try:
+ from prettytable import PrettyTable
+
+ records = mailUtilities.getEmailAccounts(virtualHostName)
+
+ table = PrettyTable(['Email'])
+
+ for items in records:
+ table.add_row([items.email])
+ print table
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ ## FTP Functions
+
+ ## FTP Functions
+
+
+ # FTP Functions
+
+ def createFTPAccount(self, domain, userName, password, owner):
+ try:
+
+ result = FTPUtilities.submitFTPCreation(domain, userName, password, 'None', owner)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def deleteFTPAccount(self, userName):
+ try:
+
+ result = FTPUtilities.submitFTPDeletion(userName)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def changeFTPPassword(self, userName, password):
+ try:
+
+ result = FTPUtilities.changeFTPPassword(userName, password)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def listFTPJson(self, virtualHostName):
+ try:
+
+ records = FTPUtilities.getFTPRecords(virtualHostName)
+
+ json_data = "["
+ checker = 0
+
+ for items in records:
+ dic = {'id': items.id,
+ 'username': items.user,
+ 'path': items.dir
+ }
+
+ if checker == 0:
+ json_data = json_data + json.dumps(dic)
+ checker = 1
+ else:
+ json_data = json_data + ',' + json.dumps(dic)
+
+ json_data = json_data + ']'
+ final_json = json.dumps(json_data)
+ print final_json
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ def listFTPPretty(self, virtualHostName):
+ try:
+ from prettytable import PrettyTable
+
+ records = FTPUtilities.getFTPRecords(virtualHostName)
+
+ table = PrettyTable(['ID', 'User', 'Path'])
+
+ for items in records:
+ table.add_row([items.id, items.user, items.dir])
+ print table
+
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ print 0
+
+ ## FTP Functions
+
+
+ ## SSL Functions
+
+ def issueSSL(self, virtualHost):
+ try:
+
+ path = ''
+ adminEmail = ''
+
+ try:
+ website = ChildDomains.objects.get(domain=virtualHost)
+ adminEmail = website.master.adminEmail
+ path = website.path
+ except:
+ website = Websites.objects.get(domain=virtualHost)
+ adminEmail = website.adminEmail
+ path = "/home/" + virtualHost + "/public_html"
+
+ result = virtualHostUtilities.issueSSL(virtualHost, path, adminEmail)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def issueSSLForHostName(self, virtualHost):
+ try:
+
+ path = ''
+ adminEmail = ''
+
+ try:
+ website = ChildDomains.objects.get(domain=virtualHost)
+ adminEmail = website.master.adminEmail
+ path = website.path
+ except:
+ website = Websites.objects.get(domain=virtualHost)
+ adminEmail = website.adminEmail
+ path = "/home/" + virtualHost + "/public_html"
+
+ result = virtualHostUtilities.issueSSLForHostName(virtualHost, path)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
+
+ def issueSSLForMailServer(self, virtualHost):
+ try:
+
+ path = ''
+ adminEmail = ''
+
+ try:
+ website = ChildDomains.objects.get(domain=virtualHost)
+ adminEmail = website.master.adminEmail
+ path = website.path
+ except:
+ website = Websites.objects.get(domain=virtualHost)
+ adminEmail = website.adminEmail
+ path = "/home/" + virtualHost + "/public_html"
+
+ result = virtualHostUtilities.issueSSLForMailServer(virtualHost, path)
+ if result[0] == 1:
+ self.printStatus(1, 'None')
+ else:
+ self.printStatus(1, result[1])
+ except BaseException, msg:
+ logger.writeforCLI(str(msg), "Error", stack()[0][3])
+ self.printStatus(0, str(msg))
def main():
- parser = argparse.ArgumentParser(description='CyberPanel Command Line Interface!')
- parser.add_argument('function', help='Specific a operation to perform!')
+ parser = cliParser()
+ args = parser.prepareArguments()
+ cyberpanel = cyberPanel()
-
- ## Website creation arguemtns
- parser.add_argument('--package', help='Select a package for website.')
- parser.add_argument('--owner', help='Select a website owner.')
- parser.add_argument('--domainName', help='Domain name!')
- parser.add_argument('--email', help='Administrator email.')
- parser.add_argument('--php', help='Administrator email.')
- parser.add_argument('--ssl', help='Weather to obtain SSL.')
- parser.add_argument('--dkim', help='DKIM Signing')
- parser.add_argument('--openBasedir', help='To enable or disable open_basedir protection for domain.')
-
-
- args = parser.parse_args()
+ ## Website functions
if args.function == "createWebsite":
@@ -78,18 +802,23 @@ def main():
if not args.package:
print "\n\nPlease enter the package name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
if not args.owner:
print "\n\nPlease enter the owner name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
if not args.domainName:
print "\n\nPlease enter the domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
if not args.email:
print "\n\nPlease enter the email. For example:\n\n" + completeCommandExample + "\n\n"
+ return
if not args.php:
print "\n\nPlease enter the PHP version such as 5.6 for PHP version 5.6. For example:\n\n" + completeCommandExample + "\n\n"
+ return
if args.ssl:
ssl = args.ssl
@@ -106,7 +835,6 @@ def main():
else:
openBasedir = 0
- cyberpanel = cyberPanel()
cyberpanel.createWebsite(args.package, args.owner, args.domainName, args.email, args.php, ssl, dkim, openBasedir)
elif args.function == "deleteWebsite":
@@ -116,8 +844,434 @@ def main():
print "\n\nPlease enter the domain to delete. For example:\n\n" + completeCommandExample + "\n\n"
return
- cyberpanel = cyberPanel()
cyberpanel.deleteWebsite(args.domainName)
+ elif args.function == "createChild":
+
+ completeCommandExample = 'cyberpanel createChild --masterDomain cyberpanel.net --childDomain child.cyberpanel.net' \
+ ' --owner admin --php 5.6'
+
+ if not args.masterDomain:
+ print "\n\nPlease enter Master domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.childDomain:
+ print "\n\nPlease enter the Child Domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.owner:
+ print "\n\nPlease enter owner for this domain DNS records. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.php:
+ print "\n\nPlease enter required PHP version. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if args.ssl:
+ ssl = args.ssl
+ else:
+ ssl = 0
+
+ if args.dkim:
+ dkim = args.dkim
+ else:
+ dkim = 0
+
+ if args.openBasedir:
+ openBasedir = args.openBasedir
+ else:
+ openBasedir = 0
+
+ cyberpanel.createDomain(args.masterDomain, args.childDomain, args.owner, args.php, ssl, dkim, openBasedir)
+ elif args.function == "deleteChild":
+
+ completeCommandExample = 'cyberpanel deleteChild --childDomain cyberpanel.net'
+
+ if not args.childDomain:
+ print "\n\nPlease enter the child domain to delete. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.deleteChild(args.childDomain)
+ elif args.function == "listWebsitesJson":
+ cyberpanel.listWebsitesJson()
+ elif args.function == "listWebsitesPretty":
+ cyberpanel.listWebsitesPretty()
+
+ elif args.function == "changePHP":
+
+ completeCommandExample = 'cyberpanel changePHP --domainName cyberpanel.net --php 5.6'
+
+ if not args.domainName:
+ print "\n\nPlease enter Domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.php:
+ print "\n\nPlease enter required PHP version. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+
+ cyberpanel.changePHP(args.domainName, args.php)
+ elif args.function == "changePackage":
+
+ completeCommandExample = 'cyberpanel changePackage --domainName cyberpanel.net --packageName CLI'
+
+ if not args.domainName:
+ print "\n\nPlease enter the Domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.packageName:
+ print "\n\nPlease enter the package name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.changePackage(args.domainName, args.packageName)
+
+ ## DNS Functions
+
+ elif args.function == "listDNSJson":
+
+ completeCommandExample = 'cyberpanel listDNSJson --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter the domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.listDNSJson(args.domainName)
+ elif args.function == "listDNSPretty":
+
+ completeCommandExample = 'cyberpanel listDNSPretty --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter the domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.listDNSPretty(args.domainName)
+ elif args.function == "listDNSZonesJson":
+ cyberpanel.listDNSZonesJson()
+ elif args.function == "listDNSZonesPretty":
+ cyberpanel.listDNSZonesPretty()
+ elif args.function == "createDNSZone":
+ completeCommandExample = 'cyberpanel createDNSZone --owner admin --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter the domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.owner:
+ print "\n\nPlease enter the owner name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.createDNSZone(args.domainName, args.owner)
+ elif args.function == "deleteDNSZone":
+ completeCommandExample = 'cyberpanel deleteDNSZone --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter the domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.deleteDNSZone(args.domainName)
+ elif args.function == "createDNSRecord":
+ completeCommandExample = 'cyberpanel createDNSRecord --domainName cyberpanel.net --name cyberpanel.net' \
+ ' --recordType A --value 192.168.100.1 --priority 0 --ttl 3600'
+
+ if not args.domainName:
+ print "\n\nPlease enter the domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.name:
+ print "\n\nPlease enter the record name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.recordType:
+ print "\n\nPlease enter the record type. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.value:
+ print "\n\nPlease enter the record value. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.priority:
+ print "\n\nPlease enter the priority. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.ttl:
+ print "\n\nPlease enter the ttl. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.createDNSRecord(args.domainName, args.name, args.recordType, args.value, args.priority, args.ttl)
+ elif args.function == "deleteDNSRecord":
+ completeCommandExample = 'cyberpanel deleteDNSRecord --recordID 200'
+
+ if not args.recordID:
+ print "\n\nPlease enter the record ID to be deleted, you can find record ID by listing the current DNS records. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.deleteDNSRecord(args.recordID)
+
+ ## Backup Functions.
+
+ elif args.function == "createBackup":
+
+ completeCommandExample = 'cyberpanel createBackup --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter the domain. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.createBackup(args.domainName)
+ elif args.function == "restoreBackup":
+
+ completeCommandExample = 'cyberpanel restoreBackup --fileName /home/talkshosting.com/backup/backup-talksho-01-30-53-Fri-Jun-2018.tar.gz'
+
+ if not args.fileName:
+ print "\n\nPlease enter the file name or complete path to file. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.restoreBackup(args.fileName)
+
+ ## Package functions.
+
+ elif args.function == "createPackage":
+
+ completeCommandExample = 'cyberpanel createPackage --owner admin --packageName CLI --diskSpace 1000 --bandwidth 10000 --emailAccounts 100' \
+ ' --dataBases 100 --ftpAccounts 100 --allowedDomains 100'
+
+ if not args.owner:
+ print "\n\nPlease enter the owner name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+ if not args.packageName:
+ print "\n\nPlease enter the package name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+ if not args.diskSpace:
+ print "\n\nPlease enter value for Disk Space. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.bandwidth:
+ print "\n\nPlease enter value for Bandwidth. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.emailAccounts:
+ print "\n\nPlease enter value for Email accounts. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.dataBases:
+ print "\n\nPlease enter value for Databases. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.ftpAccounts:
+ print "\n\nPlease enter value for Ftp accounts. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.allowedDomains:
+ print "\n\nPlease enter value for Allowed Child Domains. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+
+
+ cyberpanel.createPackage(args.owner, args.packageName, args.diskSpace, args.bandwidth, args.emailAccounts,
+ args.dataBases, args.ftpAccounts, args.allowedDomains)
+ elif args.function == "deletePackage":
+ completeCommandExample = 'cyberpanel deletePackage --packageName CLI'
+ if not args.packageName:
+ print "\n\nPlease enter the package name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.deletePackage(args.packageName)
+ elif args.function == "listPackagesJson":
+ cyberpanel.listPackagesJson()
+ elif args.function == "listPackagesPretty":
+ cyberpanel.listPackagesPretty()
+
+ ## Database functions.
+
+ elif args.function == "createDatabase":
+
+ completeCommandExample = 'cyberpanel createDatabase --databaseWebsite cyberpanel.net --dbName cyberpanel ' \
+ '--dbUsername cyberpanel --dbPassword cyberpanel'
+
+ if not args.databaseWebsite:
+ print "\n\nPlease enter database website. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+ if not args.dbName:
+ print "\n\nPlease enter the database name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+ if not args.dbUsername:
+ print "\n\nPlease enter the database username. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.dbPassword:
+ print "\n\nPlease enter the password for database. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.createDatabase(args.dbName, args.dbUsername, args.dbPassword, args.databaseWebsite)
+ elif args.function == "deleteDatabase":
+ completeCommandExample = 'cyberpanel deleteDatabase --dbName cyberpanel'
+ if not args.dbName:
+ print "\n\nPlease enter the database name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.deleteDatabase(args.dbName)
+ elif args.function == "listDatabasesJson":
+
+ completeCommandExample = 'cyberpanel listDatabasesJson --databaseWebsite cyberpanel.net'
+
+ if not args.databaseWebsite:
+ print "\n\nPlease enter database website. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+ cyberpanel.listDatabasesJson(args.databaseWebsite)
+ elif args.function == "listDatabasesPretty":
+ completeCommandExample = 'cyberpanel listDatabasesPretty --databaseWebsite cyberpanel.net'
+
+ if not args.databaseWebsite:
+ print "\n\nPlease enter database website. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.listDatabasesPretty(args.databaseWebsite)
+
+ ## Email Functions
+
+ elif args.function == "createEmail":
+
+ completeCommandExample = 'cyberpanel createEmail --domainName cyberpanel.net --userName cyberpanel ' \
+ '--password cyberpanel'
+
+ if not args.domainName:
+ print "\n\nPlease enter Domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+ if not args.userName:
+ print "\n\nPlease enter the user name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.password:
+ print "\n\nPlease enter the password for database. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.createEmail(args.domainName, args.userName, args.password)
+ elif args.function == "deleteEmail":
+ completeCommandExample = 'cyberpanel deleteEmail --email cyberpanel@cyberpanel.net'
+
+ if not args.email:
+ print "\n\nPlease enter the email. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.deleteEmail(args.email)
+ elif args.function == "changeEmailPassword":
+
+ completeCommandExample = 'cyberpanel changeEmailPassword --email cyberpanel@cyberpanel.net --password cyberpanel'
+
+ if not args.email:
+ print "\n\nPlease enter email. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.password:
+ print "\n\nPlease enter the password. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.changeEmailPassword(args.email, args.password)
+ elif args.function == "listEmailsJson":
+ completeCommandExample = 'cyberpanel listEmailsJson --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.listEmailsJson(args.domainName)
+ elif args.function == "listEmailsPretty":
+ completeCommandExample = 'cyberpanel listEmailsPretty --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.listEmailsPretty(args.domainName)
+
+ ## FTP Functions
+
+ elif args.function == "createFTPAccount":
+
+ completeCommandExample = 'cyberpanel createFTPAccount --domainName cyberpanel.net --userName cyberpanel ' \
+ '--password cyberpanel --owner admin'
+
+ if not args.domainName:
+ print "\n\nPlease enter Domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+ if not args.userName:
+ print "\n\nPlease enter the user name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.password:
+ print "\n\nPlease enter the password for database. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.owner:
+ print "\n\nPlease enter the owner name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.createFTPAccount(args.domainName, args.userName, args.password, args.owner)
+ elif args.function == "deleteFTPAccount":
+ completeCommandExample = 'cyberpanel deleteFTPAccount --userName cyberpanel'
+
+ if not args.userName:
+ print "\n\nPlease enter the user name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.deleteFTPAccount(args.userName)
+ elif args.function == "changeFTPPassword":
+
+ completeCommandExample = 'cyberpanel changeFTPPassword --userName cyberpanel --password cyberpanel'
+
+ if not args.userName:
+ print "\n\nPlease enter the user name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ if not args.password:
+ print "\n\nPlease enter the password for database. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.changeFTPPassword(args.userName, args.password)
+ elif args.function == "listFTPJson":
+ completeCommandExample = 'cyberpanel listFTPJson --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.listFTPJson(args.domainName)
+ elif args.function == "listFTPPretty":
+ completeCommandExample = 'cyberpanel listFTPPretty --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.listFTPPretty(args.domainName)
+
+ ## SSL Functions
+ elif args.function == "issueSSL":
+ completeCommandExample = 'cyberpanel issueSSL --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter Domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.issueSSL(args.domainName)
+ elif args.function == "hostNameSSL":
+ completeCommandExample = 'cyberpanel hostNameSSL --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter Domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.issueSSLForHostName(args.domainName)
+ elif args.function == "mailServerSSL":
+
+ completeCommandExample = 'cyberpanel mailServerSSL --domainName cyberpanel.net'
+
+ if not args.domainName:
+ print "\n\nPlease enter Domain name. For example:\n\n" + completeCommandExample + "\n\n"
+ return
+
+ cyberpanel.issueSSLForMailServer(args.domainName)
+
+
if __name__ == "__main__":
main()
\ No newline at end of file
diff --git a/databases/views.py b/databases/views.py
index 0fbf0a192..239d26427 100644
--- a/databases/views.py
+++ b/databases/views.py
@@ -86,47 +86,17 @@ def submitDBCreation(request):
dbName = webUsername+"_"+dbName
dbUsername = webUsername+"_"+dbUsername
- if len(dbName) > 16 or len(dbUsername) > 16:
- data_ret = {'createDBStatus': 0,
- 'error_message': "Length of Database name or Database user should be 16 at max."}
+ result = mysqlUtilities.submitDBCreation(dbName, dbUsername, dbPassword, databaseWebsite)
+
+ if result[0] == 1:
+ data_ret = {'createDBStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
-
- website = Websites.objects.get(domain=databaseWebsite)
-
- if website.package.dataBases == 0:
- pass
- elif website.package.dataBases > website.databases_set.all().count():
- pass
else:
- data_ret = {'createDBStatus': 0, 'error_message': "Maximum database limit reached for this website."}
+ data_ret = {'createDBStatus': 0, 'error_message': result[1]}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
- if Databases.objects.filter(dbName=dbName).exists() or Databases.objects.filter(dbUser=dbUsername).exists() :
- data_ret = {'createDBStatus': 0,
- 'error_message': "This database or user is already taken."}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
- result = mysqlUtilities.createDatabase(dbName, dbUsername, dbPassword)
-
- if result == 1:
- pass
- else:
- data_ret = {'createDBStatus': 0,
- 'error_message': result}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
- db = Databases(website=website,dbName=dbName,dbUser=dbUsername)
- db.save()
-
- data_ret = {'createDBStatus': 1, 'error_message': "None"}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
-
except BaseException,msg:
data_ret = {'createDBStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
@@ -234,16 +204,14 @@ def submitDatabaseDeletion(request):
dbName = data['dbName']
- databaseToBeDeleted = Databases.objects.get(dbName=dbName)
- result = mysqlUtilities.deleteDatabase(dbName,databaseToBeDeleted.dbUser)
+ result = mysqlUtilities.submitDBDeletion(dbName)
- if result == 1:
+ if result[0] == 1:
data_ret = {'deleteStatus': 1, 'error_message': "None"}
- databaseToBeDeleted.delete()
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
else:
- data_ret = {'deleteStatus': 0, 'error_message': result}
+ data_ret = {'deleteStatus': 0, 'error_message': result[1]}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
diff --git a/dns/views.py b/dns/views.py
index 7d0d66a4a..571f6f4d2 100644
--- a/dns/views.py
+++ b/dns/views.py
@@ -385,7 +385,7 @@ def addDNSRecord(request):
value = recordName + "." + zoneDomain
- createDNSRecord(request, zone, value, recordType, recordContentA, 0, ttl )
+ DNS.createDNSRecord(zone, value, recordType, recordContentA, 0, ttl )
elif recordType == "MX":
@@ -400,7 +400,7 @@ def addDNSRecord(request):
recordContentMX = data['recordContentMX']
priority = data['priority']
- createDNSRecord(request, zone, value, recordType, recordContentMX, priority, ttl)
+ DNS.createDNSRecord(zone, value, recordType, recordContentMX, priority, ttl)
elif recordType == "AAAA":
@@ -415,7 +415,7 @@ def addDNSRecord(request):
recordContentAAAA = data['recordContentAAAA'] ## IP or ponting value
- createDNSRecord(request, zone, value, recordType, recordContentAAAA, 0, ttl)
+ DNS.createDNSRecord(zone, value, recordType, recordContentAAAA, 0, ttl)
elif recordType == "CNAME":
@@ -430,7 +430,7 @@ def addDNSRecord(request):
recordContentCNAME = data['recordContentCNAME'] ## IP or ponting value
- createDNSRecord(request, zone, value, recordType, recordContentCNAME, 0, ttl)
+ DNS.createDNSRecord(zone, value, recordType, recordContentCNAME, 0, ttl)
elif recordType == "SPF":
@@ -444,7 +444,7 @@ def addDNSRecord(request):
recordContentSPF = data['recordContentSPF'] ## IP or ponting value
- createDNSRecord(request, zone, value, recordType, recordContentSPF, 0, ttl)
+ DNS.createDNSRecord(zone, value, recordType, recordContentSPF, 0, ttl)
elif recordType == "TXT":
@@ -458,13 +458,13 @@ def addDNSRecord(request):
recordContentTXT = data['recordContentTXT'] ## IP or ponting value
- createDNSRecord(request, zone, value, recordType, recordContentTXT, 0, ttl)
+ DNS.createDNSRecord(zone, value, recordType, recordContentTXT, 0, ttl)
elif recordType == "SOA":
recordContentSOA = data['recordContentSOA']
- createDNSRecord(request, zone, value, recordType, recordContentSOA, 0, ttl)
+ DNS.createDNSRecord(zone, value, recordType, recordContentSOA, 0, ttl)
elif recordType == "NS":
@@ -478,7 +478,7 @@ def addDNSRecord(request):
else:
recordContentNS = recordContentNS + "." + zoneDomain
- createDNSRecord(request, zone, value, recordType, recordContentNS, 0, ttl)
+ DNS.createDNSRecord(zone, recordName, recordType, recordContentNS, 0, ttl)
elif recordType == "SRV":
@@ -493,7 +493,7 @@ def addDNSRecord(request):
recordContentSRV = data['recordContentSRV']
priority = data['priority']
- createDNSRecord(request, zone, value, recordType, recordContentSRV, priority, ttl)
+ DNS.createDNSRecord(zone, value, recordType, recordContentSRV, priority, ttl)
final_dic = {'add_status': 1, 'error_message': "None"}
diff --git a/filemanager/templates/filemanager/index.html b/filemanager/templates/filemanager/index.html
index 0c2c1799d..f1758c9a9 100644
--- a/filemanager/templates/filemanager/index.html
+++ b/filemanager/templates/filemanager/index.html
@@ -18,7 +18,7 @@
-
+
diff --git a/ftp/views.py b/ftp/views.py
index 645505af1..76ae485d9 100644
--- a/ftp/views.py
+++ b/ftp/views.py
@@ -1,9 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
-from datetime import datetime
import hashlib
import json
-
from django.shortcuts import render,redirect
from django.http import HttpResponse
from models import Users
@@ -11,12 +9,10 @@ from loginSystem.models import Administrator
import plogical.CyberCPLogFileWriter as logging
from loginSystem.views import loadLoginPage
from websiteFunctions.models import Websites
-from websiteFunctions.models import ChildDomains
-import pwd
-import grp
import subprocess
from plogical.virtualHostUtilities import virtualHostUtilities
import shlex
+from plogical.ftpUtilities import FTPUtilities
# Create your views here.
def loadFTPHome(request):
@@ -75,97 +71,37 @@ def submitFTPCreation(request):
if request.method == 'POST':
-
data = json.loads(request.body)
userName = data['ftpUserName']
password = data['ftpPassword']
path = data['path']
- ## need to get gid and uid
-
- try:
- website = ChildDomains.objects.get(domain=data['ftpDomain'])
- externalApp = website.master.externalApp
- except:
- website = Websites.objects.get(domain=data['ftpDomain'])
- externalApp = website.externalApp
-
- uid = pwd.getpwnam(externalApp).pw_uid
- gid = grp.getgrnam(externalApp).gr_gid
-
- ## gid , uid ends
-
- path = path.lstrip("/")
-
- if len(path)>0:
-
- path = "/home/" + data['ftpDomain']+"/public_html/"+path
-
- ## Security Check
-
- if path.find("..") > -1:
- data_ret = {'creatFTPStatus': 0,
- 'error_message': "Specified path must be inside virtual host home!"}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
- execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/ftpUtilities.py"
-
- execPath = execPath + " ftpFunctions --path " + path + " --externalApp " + externalApp
-
- output = subprocess.check_output(shlex.split(execPath))
-
- if output.find("1,None") > -1:
- pass
- else:
- data_ret = {'creatFTPStatus': 0, 'error_message': "Not able to create the directory specified, for more information see CyberPanel main log file."}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
+ admin = Administrator.objects.get(id=val)
+ if len(path) > 0:
+ pass
else:
- path = "/home/" + data['ftpDomain']
+ path = 'None'
+
+ execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/ftpUtilities.py"
+
+ execPath = execPath + " submitFTPCreation --domainName " + data['ftpDomain'] + " --userName " + userName \
+ + " --password " + password + " --path " + path + " --owner " + admin.userName
- hash = hashlib.md5()
- hash.update(password)
+ output = subprocess.check_output(shlex.split(execPath))
- admin = Administrator.objects.get(pk=request.session['userID'])
-
- userName = admin.userName + "_" + userName
-
- if website.package.ftpAccounts == 0:
- user = Users(domain=website, user=userName, password=hash.hexdigest(), uid=uid, gid=gid, dir=path,
- quotasize=website.package.diskSpace,
- status="1",
- ulbandwidth=500000,
- dlbandwidth=500000,
- date=datetime.now())
-
- user.save()
-
-
-
- data_ret = {'creatFTPStatus': 1, 'error_message': "None"}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
- elif website.users_set.all().count() < website.package.ftpAccounts:
- user = Users(domain=website,user=userName, password=hash.hexdigest(), uid=uid, gid=gid, dir=path, quotasize=website.package.diskSpace,
- status="1",
- ulbandwidth=500000,
- dlbandwidth=500000,
- date=datetime.now())
-
- user.save()
-
- data_ret = {'creatFTPStatus': 1,'error_message': "None"}
+ if output.find("1,None") > -1:
+ data_ret = {'creatFTPStatus': 1, 'error_message': 'None'}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
else:
- data_ret = {'creatFTPStatus': 0, 'error_message': "Exceeded maximum amount of FTP accounts allowed for the package."}
+ data_ret = {'creatFTPStatus': 0, 'error_message': output}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
+
+
except BaseException,msg:
data_ret = {'creatFTPStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
@@ -268,8 +204,7 @@ def submitFTPDelete(request):
data = json.loads(request.body)
ftpUserName = data['ftpUsername']
- ftp = Users.objects.get(user=ftpUserName)
- ftp.delete()
+ FTPUtilities.submitFTPDeletion(ftpUserName)
final_json = json.dumps({'deleteStatus': 1, 'error_message': "None"})
return HttpResponse(final_json)
@@ -383,15 +318,7 @@ def changePassword(request):
userName = data['ftpUserName']
password = data['ftpPassword']
-
- hash = hashlib.md5()
- hash.update(password)
-
- admin = Administrator.objects.get(pk=request.session['userID'])
-
- ftp = Users.objects.get(user=userName)
- ftp.password = hash.hexdigest()
- ftp.save()
+ FTPUtilities.changeFTPPassword(userName, password)
data_ret = {'changePasswordStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret)
diff --git a/install/install.py b/install/install.py
index a5fe654be..6563c1b56 100644
--- a/install/install.py
+++ b/install/install.py
@@ -2663,6 +2663,32 @@ milter_default_action = accept
logging.InstallLog.writeToFile(str(msg) + " [installdnsPython]")
return 0
+ def setupCLI(self):
+ try:
+ count = 0
+ while (1):
+ command = "ln -s /usr/local/CyberCP/cli/cyberPanel.py /usr/bin/cyberpanel"
+ res = subprocess.call(shlex.split(command))
+
+ if res == 1:
+ count = count + 1
+ preFlightsChecks.stdOut(
+ "Trying to setup CLI, trying again, try number: " + str(count))
+ if count == 3:
+ logging.InstallLog.writeToFile(
+ "Failed to setup CLI! [setupCLI]")
+ else:
+ logging.InstallLog.writeToFile("CLI setup successfull!")
+ preFlightsChecks.stdOut("CLI setup successfull!")
+ break
+
+ command = "chmod +x /usr/local/CyberCP/cli/cyberPanel.py"
+ res = subprocess.call(shlex.split(command))
+
+ except OSError, msg:
+ logging.InstallLog.writeToFile(str(msg) + " [setupCLI]")
+ return 0
+
def main():
@@ -2737,6 +2763,7 @@ def main():
checks.installCertBot()
checks.test_Requests()
checks.download_install_CyberPanel(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql)
+ checks.setupCLI()
checks.setup_cron()
checks.installTLDExtract()
#checks.installdnsPython()
diff --git a/mailServer/views.py b/mailServer/views.py
index 80b567e3f..dd40a4086 100644
--- a/mailServer/views.py
+++ b/mailServer/views.py
@@ -17,7 +17,6 @@ from plogical.mailUtilities import mailUtilities
import thread
from dns.models import Domains as dnsDomains
from dns.models import Records as dnsRecords
-import os
def loadEmailHome(request):
try:
@@ -61,62 +60,19 @@ def submitEmailCreation(request):
userName = data['username']
password = data['password']
- ## Check if already exists
-
- finalEmailUsername = userName + "@" + domainName
-
- if EUsers.objects.filter(email=finalEmailUsername).exists():
- data_ret = {'createEmailStatus': 0, 'error_message': "This account already exists!"}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
- ## Check for email limits.
-
- website = Websites.objects.get(domain=domainName)
-
- try:
-
- newEmailDomain = Domains(domainOwner=website, domain=domainName)
- newEmailDomain.save()
-
- if website.package.emailAccounts == 0 or (
- newEmailDomain.eusers_set.all().count() < website.package.emailAccounts):
- pass
- else:
- data_ret = {'createEmailStatus': 0,
- 'error_message': "Exceeded maximum amount of email accounts allowed for the package."}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
- except:
-
- emailDomain = Domains.objects.get(domain=domainName)
-
- if website.package.emailAccounts == 0 or (
- emailDomain.eusers_set.all().count() < website.package.emailAccounts):
- pass
- else:
- data_ret = {'createEmailStatus': 0,
- 'error_message': "Exceeded maximum amount of email accounts allowed for the package."}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
## Create email entry
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py"
- execPath = execPath + " createEmailAccount --domain " + domainName
+ execPath = execPath + " createEmailAccount --domain " + domainName + " --userName " \
+ + userName + " --password " + password
output = subprocess.check_output(shlex.split(execPath))
if output.find("1,None") > -1:
- emailDomain = Domains.objects.get(domain=domainName)
-
- emailAcct = EUsers(emailOwner=emailDomain, email=finalEmailUsername, password=password)
- emailAcct.save()
-
data_ret = {'createEmailStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
@@ -222,9 +178,7 @@ def submitEmailDeletion(request):
data = json.loads(request.body)
email = data['email']
- email = EUsers(email=email)
-
- email.delete()
+ mailUtilities.deleteEmailAccount(email)
data_ret = {'deleteEmailStatus': 1, 'error_message': "None"}
json_data = json.dumps(data_ret)
diff --git a/manageSSL/views.py b/manageSSL/views.py
index 902268566..8d1d400f0 100644
--- a/manageSSL/views.py
+++ b/manageSSL/views.py
@@ -91,8 +91,6 @@ def issueSSL(request):
execPath = execPath + " issueSSL --virtualHostName " + virtualHost + " --administratorEmail " + adminEmail + " --path " + path
-
-
output = subprocess.check_output(shlex.split(execPath))
if output.find("1,None") > -1:
diff --git a/plogical/backupUtilities.py b/plogical/backupUtilities.py
index be33dfabb..6ae701a1f 100644
--- a/plogical/backupUtilities.py
+++ b/plogical/backupUtilities.py
@@ -1,9 +1,13 @@
+import os,sys
+sys.path.append('/usr/local/CyberCP')
+import django
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
+django.setup()
import pexpect
import CyberCPLogFileWriter as logging
import subprocess
import shlex
from shutil import make_archive,rmtree
-import os
import mysqlUtilities
import tarfile
from multiprocessing import Process
@@ -13,12 +17,20 @@ import signal
from installUtilities import installUtilities
import argparse
from shutil import move,copy
-import sys
from xml.etree import ElementTree
-import time
-from virtualHostUtilities import virtualHostUtilities, createAlias
+from virtualHostUtilities import virtualHostUtilities
from sslUtilities import sslUtilities
-
+from websiteFunctions.models import Websites, ChildDomains, Backups
+from databases.models import Databases
+from loginSystem.models import Administrator
+from dnsUtilities import DNS
+from xml.etree.ElementTree import Element, SubElement
+from xml.etree import ElementTree
+from xml.dom import minidom
+from backup.models import DBUsers
+from mailServer.models import Domains as eDomains
+from random import randint
+import time
## I am not the monster that you think I am..
@@ -28,6 +40,169 @@ class backupUtilities:
completeKeyPath = "/home/cyberpanel/.ssh"
destinationsPath = "/home/cyberpanel/destinations"
+ @staticmethod
+ def prepareBackupMeta(backupDomain, backupName, tempStoragePath, backupPath):
+ try:
+ ## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018 -- tempStoragePath
+ ## /home/example.com/backup - backupPath
+
+ if not os.path.exists(backupPath):
+ os.mkdir(backupPath)
+
+ if not os.path.exists(tempStoragePath):
+ os.mkdir(tempStoragePath)
+
+ website = Websites.objects.get(domain=backupDomain)
+
+ ######### Generating meta
+
+ ## XML Generation
+
+ metaFileXML = Element('metaFile')
+
+ child = SubElement(metaFileXML, 'masterDomain')
+ child.text = backupDomain
+
+ child = SubElement(metaFileXML, 'phpSelection')
+ child.text = website.phpSelection
+
+ child = SubElement(metaFileXML, 'externalApp')
+ child.text = website.externalApp
+
+ childDomains = website.childdomains_set.all()
+
+ databases = website.databases_set.all()
+
+ ## Child domains XML
+
+ childDomainsXML = Element('ChildDomains')
+
+ for items in childDomains:
+ childDomainXML = Element('domain')
+
+ child = SubElement(childDomainXML, 'domain')
+ child.text = items.domain
+ child = SubElement(childDomainXML, 'phpSelection')
+ child.text = items.phpSelection
+ child = SubElement(childDomainXML, 'path')
+ child.text = items.path
+
+ childDomainsXML.append(childDomainXML)
+
+ metaFileXML.append(childDomainsXML)
+
+ ## Databases XML
+
+ databasesXML = Element('Databases')
+
+ for items in databases:
+ dbuser = DBUsers.objects.get(user=items.dbUser)
+
+ databaseXML = Element('database')
+
+ child = SubElement(databaseXML, 'dbName')
+ child.text = items.dbName
+ child = SubElement(databaseXML, 'dbUser')
+ child.text = items.dbUser
+ child = SubElement(databaseXML, 'password')
+ child.text = dbuser.password
+
+ databasesXML.append(databaseXML)
+
+ metaFileXML.append(databasesXML)
+
+ ## Get Aliases
+
+ aliasesXML = Element('Aliases')
+
+ aliases = backupUtilities.getAliases(backupDomain)
+
+ for items in aliases:
+ child = SubElement(aliasesXML, 'alias')
+ child.text = items
+
+ metaFileXML.append(aliasesXML)
+
+ ## Finish Alias
+
+ ## DNS Records XML
+
+ try:
+ dnsRecordsXML = Element("dnsrecords")
+ dnsRecords = DNS.getDNSRecords(backupDomain)
+
+ for items in dnsRecords:
+ dnsRecordXML = Element('dnsrecord')
+
+ child = SubElement(dnsRecordXML, 'type')
+ child.text = items.type
+ child = SubElement(dnsRecordXML, 'name')
+ child.text = items.name
+ child = SubElement(dnsRecordXML, 'content')
+ child.text = items.content
+ child = SubElement(dnsRecordXML, 'priority')
+ child.text = str(items.prio)
+
+ dnsRecordsXML.append(dnsRecordXML)
+
+ metaFileXML.append(dnsRecordsXML)
+
+ except BaseException, msg:
+ logging.CyberCPLogFileWriter.writeToFile(str(msg))
+
+ ## Email accounts XML
+
+ try:
+ emailRecordsXML = Element('emails')
+ eDomain = eDomains.objects.get(domain=backupDomain)
+ emailAccounts = eDomain.eusers_set.all()
+
+ for items in emailAccounts:
+ emailRecordXML = Element('emailAccount')
+
+ child = SubElement(emailRecordXML, 'email')
+ child.text = items.email
+ child = SubElement(emailRecordXML, 'password')
+ child.text = items.password
+
+ emailRecordsXML.append(emailRecordXML)
+
+ metaFileXML.append(emailRecordsXML)
+
+ except BaseException, msg:
+ logging.CyberCPLogFileWriter.writeToFile(str(msg))
+
+ ## Email meta generated!
+
+
+ def prettify(elem):
+ """Return a pretty-printed XML string for the Element.
+ """
+ rough_string = ElementTree.tostring(elem, 'utf-8')
+ reparsed = minidom.parseString(rough_string)
+ return reparsed.toprettyxml(indent=" ")
+
+ ## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018/meta.xml -- metaPath
+ metaPath = os.path.join(tempStoragePath, "meta.xml")
+
+ xmlpretty = prettify(metaFileXML).encode('ascii', 'ignore')
+ metaFile = open(metaPath, 'w')
+ metaFile.write(xmlpretty)
+ metaFile.close()
+
+ ## meta generated
+
+
+ newBackup = Backups(website=website, fileName=backupName, date=time.strftime("%I-%M-%S-%a-%b-%Y"),
+ size=0, status=0)
+ newBackup.save()
+
+ return 1,'None'
+
+
+ except BaseException, msg:
+ return 0,str(msg)
+
@staticmethod
def startBackup(tempStoragePath,backupName,backupPath):
@@ -157,7 +332,6 @@ class backupUtilities:
status.close()
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startBackup]")
-
@staticmethod
def initiateBackup(tempStoragePath,backupName,backupPath):
try:
@@ -169,6 +343,95 @@ class backupUtilities:
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [initiateBackup]")
+ @staticmethod
+ def createWebsiteFromBackup(backupFileOrig, dir):
+ try:
+ backupFile = backupFileOrig.strip(".tar.gz")
+ originalFile = "/home/backup/" + backupFileOrig
+
+ if os.path.exists(backupFileOrig):
+ path = backupFile
+ elif not os.path.exists(originalFile):
+ dir = dir
+ path = "/home/backup/transfer-" + str(dir) + "/" + backupFile
+ else:
+ path = "/home/backup/" + backupFile
+
+ admin = Administrator.objects.get(pk=1)
+
+ ## open meta file to read data
+
+ ## Parsing XML Meta file!
+
+ backupMetaData = ElementTree.parse(os.path.join(path, 'meta.xml'))
+
+ domain = backupMetaData.find('masterDomain').text
+ phpSelection = backupMetaData.find('phpSelection').text
+ externalApp = backupMetaData.find('externalApp').text
+
+ ## Pre-creation checks
+
+ if Websites.objects.filter(domain=domain).count() > 0:
+ raise BaseException('This website already exists.')
+
+
+ if ChildDomains.objects.filter(domain=domain).count() > 0:
+ raise BaseException("This website already exists as child domain.")
+
+
+ ####### Pre-creation checks ends
+
+ numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count()
+
+ ## Create Configurations
+
+ result = virtualHostUtilities.createVirtualHost(domain, admin.email, phpSelection, externalApp,
+ numberOfWebsites, 0, 'CyberPanel', 1, 0,
+ admin.userName, 'Default')
+
+ if result[0] == 0:
+ raise BaseException(result[1])
+
+ ## Create Configurations ends here
+
+ ## Create databases
+
+ databases = backupMetaData.findall('Databases/database')
+ website = Websites.objects.get(domain=domain)
+
+ for database in databases:
+ dbName = database.find('dbName').text
+ dbUser = database.find('dbUser').text
+
+ if mysqlUtilities.mysqlUtilities.createDatabase(dbName, dbUser, "cyberpanel") == 0:
+ raise BaseException("Failed to create Databases!")
+
+ newDB = Databases(website=website, dbName=dbName, dbUser=dbUser)
+ newDB.save()
+
+ ## Create dns zone
+
+ dnsrecords = backupMetaData.findall('dnsrecords/dnsrecord')
+
+ DNS.createDNSZone(domain, admin)
+
+ zone = DNS.getZoneObject(domain)
+
+ for dnsrecord in dnsrecords:
+
+ recordType = dnsrecord.find('type').text
+ value = dnsrecord.find('name').text
+ content = dnsrecord.find('content').text
+ prio = int(dnsrecord.find('priority').text)
+
+ DNS.createDNSRecord(zone, value, recordType, content, prio, 3600)
+
+
+ return 1,'None'
+
+ except BaseException, msg:
+ return 0, str(msg)
+
@staticmethod
def startRestore(backupName, dir):
try:
@@ -177,6 +440,9 @@ class backupUtilities:
backupFileName = backupName.strip(".tar.gz")
completPath = os.path.join("/home","backup",backupFileName) ## without extension
originalFile = os.path.join("/home","backup",backupName) ## with extension
+ elif dir == 'CLI':
+ completPath = backupName.strip(".tar.gz") ## without extension
+ originalFile = backupName ## with extension
else:
backupFileName = backupName.strip(".tar.gz")
completPath = "/home/backup/transfer-"+str(dir)+"/"+backupFileName ## without extension
@@ -218,45 +484,34 @@ class backupUtilities:
backupMetaData = ElementTree.parse(os.path.join(completPath, "meta.xml"))
masterDomain = backupMetaData.find('masterDomain').text
- try:
- finalData = json.dumps({'backupFile': backupName,"dir":dir})
- r = requests.post("http://localhost:5003/websites/CreateWebsiteFromBackup", data=finalData,verify=False)
- data = json.loads(r.text)
+ result = backupUtilities.createWebsiteFromBackup(backupName, dir)
- if data['createWebSiteStatus'] == 1:
+ if result[0] == 1:
+ ## Let us try to restore SSL.
- ## Let us try to restore SSL.
+ if os.path.exists(completPath + "/privkey.pem"):
- if os.path.exists(completPath + "/privkey.pem"):
+ pathToStoreSSL = sslUtilities.Server_root + "/conf/vhosts/" + "SSL-" + masterDomain
- pathToStoreSSL = sslUtilities.Server_root + "/conf/vhosts/" + "SSL-" + masterDomain
+ if not os.path.exists(pathToStoreSSL):
+ os.mkdir(pathToStoreSSL)
- if not os.path.exists(pathToStoreSSL):
- os.mkdir(pathToStoreSSL)
+ sslUtilities.installSSLForDomain(masterDomain)
- sslUtilities.installSSLForDomain(masterDomain)
+ pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem"
+ pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem"
+ copy(completPath + "/privkey.pem", pathToStoreSSLPrivKey)
+ copy(completPath + "/fullchain.pem", pathToStoreSSLFullChain)
- pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem"
- pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem"
-
- copy(completPath + "/privkey.pem", pathToStoreSSLPrivKey)
- copy(completPath + "/fullchain.pem", pathToStoreSSLFullChain)
-
- command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + pathToStoreSSL
- cmd = shlex.split(command)
-
- pass
- else:
- status = open(os.path.join(completPath,'status'), "w")
- status.write("Error Message: " + data['error_message'] +". Not able to create Account, Databases and DNS Records, aborting. [5009]")
- status.close()
- return 0
- except BaseException,msg:
- status = open(os.path.join(completPath,'status'), "w")
- status.write("Error Message: " + str(msg) +". Not able to create Account, Databases and DNS Records, aborting. [5009]")
+ command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + pathToStoreSSL
+ cmd = shlex.split(command)
+ subprocess.call(cmd)
+ else:
+ status = open(os.path.join(completPath, 'status'), "w")
+ status.write("Error Message: " + result[1] +
+ ". Not able to create Account, Databases and DNS Records, aborting. [5009]")
status.close()
- logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startRestore]")
return 0
########### Creating child/sub/addon/parked domains
@@ -342,7 +597,7 @@ class backupUtilities:
aliases = backupMetaData.findall('Aliases/alias')
for items in aliases:
- createAlias(masterDomain, items.text, 0, "", "")
+ virtualHostUtilities.createAlias(masterDomain, items.text, 0, "", "")
## Restoring email accounts
@@ -713,35 +968,28 @@ class backupUtilities:
print 0
-def submitBackupCreation(tempStoragePath,backupName,backupPath,metaPath):
+def submitBackupCreation(tempStoragePath, backupName, backupPath, backupDomain):
try:
## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018 -- tempStoragePath
## backup-example-06-50-03-Thu-Feb-2018 -- backup name
## /home/example.com/backup - backupPath
## /home/cyberpanel/1047.xml - metaPath
- if not os.path.exists(backupPath):
- os.mkdir(backupPath)
- if not os.path.exists(tempStoragePath):
- os.mkdir(tempStoragePath)
-
- ## Move meta file inside the temporary storage created to store backup data.
-
- move(metaPath,os.path.join(tempStoragePath,"meta.xml"))
+ backupUtilities.prepareBackupMeta(backupDomain, backupName, tempStoragePath, backupPath)
p = Process(target=backupUtilities.startBackup, args=(tempStoragePath, backupName, backupPath,))
p.start()
- pid = open(os.path.join(backupPath,'pid'), "w")
+ pid = open(os.path.join(backupPath, 'pid'), "w")
pid.write(str(p.pid))
pid.close()
print "1,None"
- except BaseException,msg:
+ except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [submitBackupCreation]")
- print "0,"+str(msg)
+ print "0," + str(msg)
def cancelBackupCreation(backupCancellationDomain,fileName):
try:
@@ -797,6 +1045,7 @@ def main():
parser.add_argument('--tempStoragePath', help='')
parser.add_argument('--backupName', help='!')
parser.add_argument('--backupPath', help='')
+ parser.add_argument('--backupDomain', help='')
parser.add_argument('--metaPath', help='')
## backup cancellation arguments
@@ -815,7 +1064,7 @@ def main():
args = parser.parse_args()
if args.function == "submitBackupCreation":
- submitBackupCreation(args.tempStoragePath,args.backupName,args.backupPath,args.metaPath)
+ submitBackupCreation(args.tempStoragePath,args.backupName,args.backupPath, args.backupDomain)
elif args.function == "cancelBackupCreation":
cancelBackupCreation(args.backupCancellationDomain,args.fileName)
elif args.function == "submitRestore":
diff --git a/plogical/dnsUtilities.py b/plogical/dnsUtilities.py
index 9324ad0ee..e7d8d8752 100644
--- a/plogical/dnsUtilities.py
+++ b/plogical/dnsUtilities.py
@@ -289,8 +289,31 @@ class DNS:
logging.CyberCPLogFileWriter.writeToFile(
"We had errors while creating DNS records for: " + domain + ". Error message: " + str(msg))
+ @staticmethod
+ def getZoneObject(virtualHostName):
+ try:
+ return Domains.objects.get(name=virtualHostName)
+ except:
+ return 0
+
@staticmethod
def createDNSRecord(zone, name, type, value, priority, ttl):
+
+ if type == 'NS':
+ if Records.objects.filter(name=name, type=type, content=value).count() == 0:
+ record = Records(domainOwner=zone,
+ domain_id=zone.id,
+ name=name,
+ type=type,
+ content=value,
+ ttl=ttl,
+ prio=priority,
+ disabled=0,
+ auth=1)
+ record.save()
+ return
+
+
if Records.objects.filter(name=name, type=type).count() == 0:
record = Records(domainOwner=zone,
domain_id=zone.id,
@@ -310,4 +333,39 @@ class DNS:
delZone.delete()
except:
## There does not exist a zone for this domain.
- pass
\ No newline at end of file
+ pass
+
+ @staticmethod
+ def createDNSZone(virtualHostName, admin):
+ try:
+ zone = Domains(admin=admin, name=virtualHostName, type="NATIVE")
+ zone.save()
+ except:
+ ## There does not exist a zone for this domain.
+ pass
+
+ @staticmethod
+ def getDNSRecords(virtualHostName):
+ try:
+ zone = Domains.objects.get(name=virtualHostName)
+ zone.save()
+ return zone.records_set.all()
+ except:
+ ## There does not exist a zone for this domain.
+ pass
+
+ @staticmethod
+ def getDNSZones():
+ try:
+ return Domains.objects.all()
+ except:
+ pass
+
+ @staticmethod
+ def deleteDNSRecord(recordID):
+ try:
+ delRecord = Records.objects.get(id=recordID)
+ delRecord.delete()
+ except:
+ ## There does not exist a zone for this domain.
+ pass
diff --git a/plogical/ftpUtilities.py b/plogical/ftpUtilities.py
index 405224388..136db5bbb 100644
--- a/plogical/ftpUtilities.py
+++ b/plogical/ftpUtilities.py
@@ -1,9 +1,22 @@
+#!/usr/bin/env python2.7
+import os,sys
+sys.path.append('/usr/local/CyberCP')
+import django
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
+django.setup()
import mysqlUtilities as sql
import subprocess
import CyberCPLogFileWriter as logging
import os
import shlex
import argparse
+from websiteFunctions.models import Websites, ChildDomains
+from loginSystem.models import Administrator
+import pwd
+import grp
+import hashlib
+from ftp.models import Users
+from datetime import datetime
class FTPUtilities:
@@ -40,8 +53,6 @@ class FTPUtilities:
return 1
-
-
@staticmethod
def createFTPDataBaseinMariaDB(username,password):
try:
@@ -178,7 +189,6 @@ class FTPUtilities:
return 1
-
@staticmethod
def changePermissions(directory):
@@ -228,26 +238,140 @@ class FTPUtilities:
cmd = shlex.split(command)
subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT)
- print "1,None"
+ return 1,'None'
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(
- str(msg) + " [getErrorLogs]")
+ str(msg) + " [ftpFunctions]")
+ return 0, str(msg)
+
+ @staticmethod
+ def submitFTPCreation(domainName, userName, password, path, owner):
+ try:
+
+ ## need to get gid and uid
+
+ try:
+ website = ChildDomains.objects.get(domain=domainName)
+ externalApp = website.master.externalApp
+ except:
+ website = Websites.objects.get(domain=domainName)
+ externalApp = website.externalApp
+
+ uid = pwd.getpwnam(externalApp).pw_uid
+ gid = grp.getgrnam(externalApp).gr_gid
+
+ ## gid , uid ends
+
+ path = path.lstrip("/")
+
+ if path != 'None':
+
+ path = "/home/" + domainName + "/public_html/" + path
+
+ ## Security Check
+
+ if path.find("..") > -1:
+ raise BaseException("Specified path must be inside virtual host home!")
+
+
+ result = FTPUtilities.ftpFunctions(path, externalApp)
+
+ if result[0] == 1:
+ pass
+ else:
+ raise BaseException(result[1])
+
+ else:
+ path = "/home/" + domainName
+
+ hash = hashlib.md5()
+ hash.update(password)
+
+ admin = Administrator.objects.get(userName=owner)
+
+ userName = admin.userName + "_" + userName
+
+ if website.package.ftpAccounts == 0:
+ user = Users(domain=website, user=userName, password=hash.hexdigest(), uid=uid, gid=gid,
+ dir=path,
+ quotasize=website.package.diskSpace,
+ status="1",
+ ulbandwidth=500000,
+ dlbandwidth=500000,
+ date=datetime.now())
+
+ user.save()
+
+ elif website.users_set.all().count() < website.package.ftpAccounts:
+ user = Users(domain=website, user=userName, password=hash.hexdigest(), uid=uid, gid=gid,
+ dir=path, quotasize=website.package.diskSpace,
+ status="1",
+ ulbandwidth=500000,
+ dlbandwidth=500000,
+ date=datetime.now())
+
+ user.save()
+
+ else:
+ raise BaseException("Exceeded maximum amount of FTP accounts allowed for the package.")
+
+ print "1,None"
+ return 1,'None'
+
+ except BaseException, msg:
+ logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [submitFTPCreation]")
print "0,"+str(msg)
+ return 0, str(msg)
+
+ @staticmethod
+ def submitFTPDeletion(ftpUsername):
+ try:
+ ftp = Users.objects.get(user=ftpUsername)
+ ftp.delete()
+ return 1,'None'
+ except BaseException, msg:
+ return 0, str(msg)
+
+ @staticmethod
+ def changeFTPPassword(userName, password):
+ try:
+ hash = hashlib.md5()
+ hash.update(password)
+
+ ftp = Users.objects.get(user=userName)
+ ftp.password = hash.hexdigest()
+ ftp.save()
+
+ return 1, None
+ except BaseException, msg:
+ return 0,str(msg)
+
+ @staticmethod
+ def getFTPRecords(virtualHostName):
+ try:
+ website = Websites.objects.get(domain=virtualHostName)
+ return website.users_set.all()
+ except:
+ ## There does not exist a zone for this domain.
+ pass
def main():
parser = argparse.ArgumentParser(description='CyberPanel Installer')
parser.add_argument('function', help='Specific a function to call!')
+ parser.add_argument('--domainName', help='Domain to create FTP for!')
+ parser.add_argument('--userName', help='Username for FTP Account')
+ parser.add_argument('--password', help='Password for FTP Account')
+ parser.add_argument('--owner', help='FTP Account owner.')
parser.add_argument('--path', help='Path to ftp directory!')
- parser.add_argument('--externalApp', help='Owner for the path of FTP Directory!')
args = parser.parse_args()
- if args.function == "ftpFunctions":
- FTPUtilities.ftpFunctions(args.path,args.externalApp)
+ if args.function == "submitFTPCreation":
+ FTPUtilities.submitFTPCreation(args.domainName,args.userName, args.password, args.path, args.owner)
diff --git a/plogical/installUtilities.py b/plogical/installUtilities.py
index b95c9f3a8..7b697e50d 100644
--- a/plogical/installUtilities.py
+++ b/plogical/installUtilities.py
@@ -145,16 +145,6 @@ class installUtilities:
res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT)
- 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]")
diff --git a/plogical/mailUtilities.py b/plogical/mailUtilities.py
index 616ce02e6..bc9c54752 100644
--- a/plogical/mailUtilities.py
+++ b/plogical/mailUtilities.py
@@ -1,9 +1,16 @@
+import os,sys
+sys.path.append('/usr/local/CyberCP')
+import django
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
+django.setup()
import os.path
import shutil
import CyberCPLogFileWriter as logging
import subprocess
import argparse
import shlex
+from mailServer.models import Domains,EUsers
+from websiteFunctions.models import Websites
class mailUtilities:
@@ -12,9 +19,45 @@ class mailUtilities:
cyberPanelHome = "/home/cyberpanel"
@staticmethod
- def createEmailAccount(domain):
+ def createEmailAccount(domain, userName, password):
try:
+ ## Check if already exists
+
+ finalEmailUsername = userName + "@" + domain
+
+ if EUsers.objects.filter(email=finalEmailUsername).exists():
+ raise BaseException("This account already exists!")
+
+ ## Check for email limits.
+
+ website = Websites.objects.get(domain=domain)
+
+ try:
+
+ newEmailDomain = Domains(domainOwner=website, domain=domain)
+ newEmailDomain.save()
+
+ if website.package.emailAccounts == 0 or (
+ newEmailDomain.eusers_set.all().count() < website.package.emailAccounts):
+ pass
+ else:
+ raise BaseException("Exceeded maximum amount of email accounts allowed for the package.")
+
+ except:
+
+ emailDomain = Domains.objects.get(domain=domain)
+
+ if website.package.emailAccounts == 0 or (
+ emailDomain.eusers_set.all().count() < website.package.emailAccounts):
+ pass
+ else:
+ raise BaseException("Exceeded maximum amount of email accounts allowed for the package.")
+
+
+ ## After effects
+
+
path = "/usr/local/CyberCP/install/rainloop/cyberpanel.net.ini"
if not os.path.exists("/usr/local/lscp/cyberpanel/rainloop/data/_data_/_default_/domains/"):
@@ -25,7 +68,7 @@ class mailUtilities:
if not os.path.exists(finalPath):
shutil.copy(path, finalPath)
- command = 'chown -R nobody:nobody /usr/local/lscp/rainloop'
+ command = 'chown -R nobody:nobody /usr/local/lscp/cyberpanel/rainloop'
cmd = shlex.split(command)
@@ -37,13 +80,53 @@ class mailUtilities:
res = subprocess.call(cmd)
+ ## After effects ends
+
+ emailDomain = Domains.objects.get(domain=domain)
+
+ emailAcct = EUsers(emailOwner=emailDomain, email=finalEmailUsername, password=password)
+ emailAcct.save()
+
print "1,None"
+ return 1,"None"
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [createEmailAccount]")
print "0," + str(msg)
+ return 0, str(msg)
+ @staticmethod
+ def deleteEmailAccount(email):
+ try:
+
+ email = EUsers(email=email)
+ email.delete()
+
+ return 1, 'None'
+
+ except BaseException, msg:
+ logging.CyberCPLogFileWriter.writeToFile(
+ str(msg) + " [deleteEmailAccount]")
+ return 0, str(msg)
+
+ @staticmethod
+ def getEmailAccounts(virtualHostName):
+ try:
+ emailDomain = Domains.objects.get(domain=virtualHostName)
+ return emailDomain.eusers_set.all()
+ except:
+ return 0
+
+ @staticmethod
+ def changeEmailPassword(email, newPassword):
+ try:
+ changePass = EUsers.objects.get(email=email)
+ changePass.password = newPassword
+ changePass.save()
+ return 0,'None'
+ except BaseException, msg:
+ return 0, str(msg)
@staticmethod
def setupDKIM(virtualHostName):
@@ -57,8 +140,10 @@ class mailUtilities:
## Generate keys
+ FNULL = open(os.devnull, 'w')
+
command = "opendkim-genkey -D /etc/opendkim/keys/" + virtualHostName + " -d " + virtualHostName + " -s default"
- subprocess.call(shlex.split(command))
+ subprocess.call(shlex.split(command),stdout=FNULL, stderr=subprocess.STDOUT)
## Fix permissions
@@ -273,12 +358,15 @@ def main():
parser = argparse.ArgumentParser(description='CyberPanel Installer')
parser.add_argument('function', help='Specific a function to call!')
parser.add_argument('--domain', help='Domain name!')
+ parser.add_argument('--userName', help='Email Username!')
+ parser.add_argument('--password', help='Email password!')
+
args = parser.parse_args()
if args.function == "createEmailAccount":
- mailUtilities.createEmailAccount(args.domain)
+ mailUtilities.createEmailAccount(args.domain, args.userName, args.password)
elif args.function == "generateKeys":
mailUtilities.generateKeys(args.domain)
elif args.function == "configureOpenDKIM":
diff --git a/plogical/mysqlUtilities.py b/plogical/mysqlUtilities.py
index 031a41a23..7a3021f1a 100644
--- a/plogical/mysqlUtilities.py
+++ b/plogical/mysqlUtilities.py
@@ -1,42 +1,17 @@
-import pexpect
+import os,sys
+sys.path.append('/usr/local/CyberCP')
+import django
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
+django.setup()
import CyberCPLogFileWriter as logging
import subprocess
import shlex
+from websiteFunctions.models import Websites
+from databases.models import Databases
class mysqlUtilities:
- @staticmethod
- def SendQuery(user, password, dbname, query):
- try:
- expectation = "Enter password:"
- securemysql = pexpect.spawn("mysql -u "+user+" -p")
- securemysql.expect(expectation)
- securemysql.sendline(password)
-
- expectation = ["Access denied for user", "Welcome to the MariaDB monitor"]
- index = securemysql.expect(expectation)
- if index == 0:
- return "Wrong Password"
- else:
-
- securemysql.sendline("USE "+dbname+";")
- expectation = "Database changed"
- securemysql.expect(expectation)
-
- expectation = "Query OK"
- securemysql.sendline(query);
- securemysql.expect(expectation)
-
- securemysql.sendline("exit");
-
- securemysql.wait()
- return 1
- except pexpect.EOF, msg:
- logging.CyberCPLogFileWriter.writeToFile(str(msg) + " Exception EOF [SendQuery]")
- except BaseException, msg:
- logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[SendQuery]")
-
@staticmethod
def createDatabase(dbname,dbuser,dbpassword):
@@ -184,3 +159,64 @@ class mysqlUtilities:
return 1
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[restoreDatabaseBackup]")
+
+
+ @staticmethod
+ def submitDBCreation(dbName, dbUsername, dbPassword, databaseWebsite):
+ try:
+
+ if len(dbName) > 16 or len(dbUsername) > 16:
+ raise BaseException("Length of Database name or Database user should be 16 at max.")
+
+ website = Websites.objects.get(domain=databaseWebsite)
+
+ if website.package.dataBases == 0:
+ pass
+ elif website.package.dataBases > website.databases_set.all().count():
+ pass
+ else:
+ raise BaseException("Maximum database limit reached for this website.")
+
+ if Databases.objects.filter(dbName=dbName).exists() or Databases.objects.filter(dbUser=dbUsername).exists():
+ raise BaseException("This database or user is already taken.")
+
+ result = mysqlUtilities.createDatabase(dbName, dbUsername, dbPassword)
+
+ if result == 1:
+ pass
+ else:
+ raise BaseException(result)
+
+ db = Databases(website=website, dbName=dbName, dbUser=dbUsername)
+ db.save()
+
+ return 1,'None'
+
+ except BaseException, msg:
+ logging.CyberCPLogFileWriter.writeToFile(str(msg))
+ return 0,str(msg)
+
+ @staticmethod
+ def submitDBDeletion(dbName):
+ try:
+
+ databaseToBeDeleted = Databases.objects.get(dbName=dbName)
+ result = mysqlUtilities.deleteDatabase(dbName, databaseToBeDeleted.dbUser)
+
+ if result == 1:
+ databaseToBeDeleted.delete()
+ return 1,'None'
+ else:
+ return 0,result
+
+ except BaseException, msg:
+ logging.CyberCPLogFileWriter.writeToFile(str(msg))
+ return 0, str(msg)
+
+ @staticmethod
+ def getDatabases(virtualHostName):
+ try:
+ website = Websites.objects.get(domain=virtualHostName)
+ return website.databases_set.all()
+ except:
+ 0
diff --git a/plogical/vhost.py b/plogical/vhost.py
index 49c650d2b..aac54fce5 100644
--- a/plogical/vhost.py
+++ b/plogical/vhost.py
@@ -559,9 +559,6 @@ class vhost:
writeDataToFile = open(vhFile, "w")
- sockRandomPath = str(randint(1000, 9999))
-
- address = " address UDS://tmp/lshttpd/" + sockRandomPath + ".sock\n"
path = " path /usr/local/lsws/lsphp" + str(finalphp) + "/bin/lsphp\n"
for items in data:
@@ -575,28 +572,14 @@ class vhost:
installUtilities.installUtilities.reStartLiteSpeed()
print "1,None"
+ return 1,'None'
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [IO Error with per host config file [changePHP]]")
+ print 0,str(msg)
return [0, str(msg) + " [IO Error with per host config file [changePHP]]"]
- @staticmethod
- def getDiskUsage(path, totalAllowed):
- try:
-
- totalUsageInMB = subprocess.check_output(["sudo", "du", "-hs", path, "--block-size=1M"]).split()[0]
-
- percentage = float(100) / float(totalAllowed)
-
- percentage = float(percentage) * float(totalUsageInMB)
-
- data = [int(totalUsageInMB), int(percentage)]
- return data
- except BaseException, msg:
- logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [getDiskUsage]")
- return [int(0), int(0)]
-
@staticmethod
def addRewriteRules(virtualHostName, fileName=None):
@@ -655,41 +638,6 @@ class vhost:
return 0
return 1
- @staticmethod
- def suspendVirtualHost(virtualHostName):
- try:
-
- confPath = vhost.Server_root + "/conf/vhosts/" + virtualHostName
-
- command = "sudo mv " + confPath + " " + confPath + "-suspended"
- subprocess.call(shlex.split(command))
-
- except BaseException, msg:
- logging.CyberCPLogFileWriter.writeToFile(
- str(msg) + " [suspendVirtualHost]")
- return 0
- return 1
-
- @staticmethod
- def UnsuspendVirtualHost(virtualHostName):
- try:
-
- confPath = vhost.Server_root + "/conf/vhosts/" + virtualHostName
-
- command = "sudo mv " + confPath + "-suspended" + " " + confPath
- subprocess.call(shlex.split(command))
-
- command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath
- cmd = shlex.split(command)
- subprocess.call(cmd)
-
-
- except BaseException, msg:
- logging.CyberCPLogFileWriter.writeToFile(
- str(msg) + " [UnsuspendVirtualHost]")
- return 0
- return 1
-
@staticmethod
def findDomainBW(domainName, totalAllowed):
try:
diff --git a/plogical/virtualHostUtilities.py b/plogical/virtualHostUtilities.py
index fabbf4078..d19ce8b37 100644
--- a/plogical/virtualHostUtilities.py
+++ b/plogical/virtualHostUtilities.py
@@ -88,7 +88,7 @@ class virtualHostUtilities:
if ssl == 0:
installUtilities.installUtilities.reStartLiteSpeed()
- vhost.finalizeVhostCreation(virtualHostName, virtualHostUser)
+ vhost.finalizeVhostCreation(virtualHostName, virtualHostUser)
## Create Configurations ends here
@@ -134,12 +134,13 @@ class virtualHostUtilities:
subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT)
print "1,None"
- return
+ return 1, None
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [issueSSL]")
print "0," + str(msg)
+ return 0, str(msg)
@staticmethod
def getAccessLogs(fileName, page):
@@ -579,7 +580,7 @@ class virtualHostUtilities:
if retValues[0] == 0:
print "0," + str(retValues[1])
- return
+ return 0,retValues[1]
shutil.copy(pathToStoreSSLPrivKey, destPrivKey)
shutil.copy(pathToStoreSSLFullChain, destCert)
@@ -594,12 +595,14 @@ class virtualHostUtilities:
subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT)
print "1,None"
+ return 1,'None'
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [issueSSLForHostName]")
print "0," + str(msg)
+ return 0, str(msg)
@staticmethod
def issueSSLForMailServer(virtualHost, path):
@@ -623,7 +626,7 @@ class virtualHostUtilities:
if retValues[0] == 0:
print "0," + str(retValues[1])
- return
+ return 0,retValues[1]
## MailServer specific functions
@@ -701,11 +704,13 @@ class virtualHostUtilities:
p.start()
print "1,None"
+ return 1,'None'
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [issueSSLForHostName]")
print "0," + str(msg)
+ return 0,str(msg)
@staticmethod
def createAlias(masterDomain, aliasDomain, ssl, sslPath, administratorEmail, owner=None):
@@ -868,7 +873,7 @@ class virtualHostUtilities:
else:
writeToFile.writelines(items)
- phpIniOverride = "phpIniOverride {\n"
+ phpIniOverride = "\nphpIniOverride {\n"
php_admin_value = 'php_admin_value open_basedir "/tmp:$VH_ROOT"\n'
endPHPIniOverride = "}\n"
@@ -1009,7 +1014,7 @@ class virtualHostUtilities:
except BaseException, msg:
numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count()
- vhost.deleteVirtualHostConfigurations(virtualHostName, numberOfWebsites)
+ vhost.deleteCoreConf(virtualHostName, numberOfWebsites)
logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [createDomain]")
print "0," + str(msg)
@@ -1026,11 +1031,29 @@ class virtualHostUtilities:
installUtilities.installUtilities.reStartLiteSpeed()
print "1,None"
+ return 1,'None'
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(
str(msg) + " [deleteDomain]")
print "0," + str(msg)
+ return 0,str(msg)
+
+ @staticmethod
+ def getDiskUsage(path, totalAllowed):
+ try:
+
+ totalUsageInMB = subprocess.check_output(["sudo", "du", "-hs", path, "--block-size=1M"]).split()[0]
+
+ percentage = float(100) / float(totalAllowed)
+
+ percentage = float(percentage) * float(totalUsageInMB)
+
+ data = [int(totalUsageInMB), int(percentage)]
+ return data
+ except BaseException, msg:
+ logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [getDiskUsage]")
+ return [int(0), int(0)]
def main():
diff --git a/websiteFunctions/urls.py b/websiteFunctions/urls.py
index 1b0a21eaf..ef00bddb1 100644
--- a/websiteFunctions/urls.py
+++ b/websiteFunctions/urls.py
@@ -44,9 +44,6 @@ urlpatterns = [
url(r'^saveSSL', views.saveSSL, name='saveSSL'),
-
- url(r'^CreateWebsiteFromBackup', views.CreateWebsiteFromBackup, name='CreateWebsiteFromBackup'),
-
## sub/add/park domains
url(r'^submitDomainCreation', views.submitDomainCreation, name='submitDomainCreation'),
diff --git a/websiteFunctions/views.py b/websiteFunctions/views.py
index 202f3cc14..3761e0512 100644
--- a/websiteFunctions/views.py
+++ b/websiteFunctions/views.py
@@ -169,35 +169,6 @@ def deleteWebsite(request):
except KeyError:
return redirect(loadLoginPage)
-def createDKIMRecords(request, domain, admin):
- try:
-
- import tldextract
-
- extractDomain = tldextract.extract(domain)
- topLevelDomain = extractDomain.domain + '.' + extractDomain.suffix
-
- zone = Domains.objects.get(name=topLevelDomain)
-
- path = "/etc/opendkim/keys/" + topLevelDomain + "/default.txt"
- command = "sudo cat " + path
- output = subprocess.check_output(shlex.split(command))
-
- record = Records(domainOwner=zone,
- domain_id=zone.id,
- name="default._domainkey." + topLevelDomain,
- type="TXT",
- content="v=DKIM1; k=rsa; p=" + output[53:269],
- ttl=3600,
- prio=0,
- disabled=0,
- auth=1)
- record.save()
-
- except BaseException, msg:
- logging.CyberCPLogFileWriter.writeToFile(
- "We had errors while creating DNS records for: " + domain + ". Error message: " + str(msg))
-
def siteState(request):
try:
val = request.session['userID']
@@ -240,6 +211,7 @@ def siteState(request):
def submitWebsiteCreation(request):
try:
+
if request.method == 'POST':
data = json.loads(request.body)
@@ -315,12 +287,6 @@ def submitDomainCreation(request):
restore = data['restore']
restore = '1'
- if len(path) > 0:
- path = path.lstrip("/")
- path = "/home/" + masterDomain + "/public_html/" + path
- else:
- path = "/home/" + masterDomain + "/public_html/" + domain
-
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \
@@ -501,9 +467,7 @@ def getFurtherAccounts(request):
json_data = json_data +',' + json.dumps(dic)
json_data = json_data + ']'
-
final_dic = {'listWebSiteStatus': 1, 'error_message': "None", "data": json_data}
-
final_json = json.dumps(final_dic)
@@ -534,7 +498,8 @@ def submitWebsiteDeletion(request):
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
- execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName "+ websiteName+" --numberOfSites "+numberOfWebsites
+ execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName + \
+ " --numberOfSites " + numberOfWebsites
subprocess.check_output(shlex.split(execPath))
@@ -573,8 +538,6 @@ def submitDomainDeletion(request):
return HttpResponse(json_data)
except BaseException,msg:
-
-
data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
@@ -596,20 +559,27 @@ def submitWebsiteStatus(request):
if state == "Suspend":
- virtualHostUtilities.suspendVirtualHost(websiteName)
+ confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName
+ command = "sudo mv " + confPath + " " + confPath + "-suspended"
+ subprocess.call(shlex.split(command))
installUtilities.reStartLiteSpeed()
website.state = 0
else:
- virtualHostUtilities.UnsuspendVirtualHost(websiteName)
+ confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName
+
+ command = "sudo mv " + confPath + "-suspended" + " " + confPath
+ subprocess.call(shlex.split(command))
+
+ command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath
+ cmd = shlex.split(command)
+ subprocess.call(cmd)
+
installUtilities.reStartLiteSpeed()
website.state = 1
-
website.save()
-
-
data_ret = {'websiteStatus': 1,'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
@@ -1172,6 +1142,8 @@ def installJoomla(request):
password = data['password']
prefix = data['prefix']
+ mailUtilities.checkHome()
+
finalPath = ""
if home == '0':
@@ -1343,8 +1315,6 @@ def saveConfigsToFile(request):
execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath
-
-
output = subprocess.check_output(shlex.split(execPath))
if output.find("1,None") > -1:
@@ -1593,8 +1563,6 @@ def changePHP(request):
execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile
-
-
output = subprocess.check_output(shlex.split(execPath))
if output.find("1,None") > -1:
@@ -1620,212 +1588,6 @@ def changePHP(request):
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
-def CreateWebsiteFromBackup(request):
- try:
- if request.method == 'POST':
-
- data = json.loads(request.body)
- backupFile = data['backupFile'].strip(".tar.gz")
- originalFile = "/home/backup/" + data['backupFile']
-
-
- if not os.path.exists(originalFile):
- dir = data['dir']
- path = "/home/backup/transfer-"+str(dir)+"/"+backupFile
- else:
- path = "/home/backup/" + backupFile
-
- admin = Administrator.objects.get(pk=1)
- adminEmail = admin.email
-
- ## open meta file to read data
-
- ## Parsing XML Meta file!
-
- backupMetaData = ElementTree.parse(os.path.join(path,'meta.xml'))
-
- domain = backupMetaData.find('masterDomain').text
- phpSelection = backupMetaData.find('phpSelection').text
- externalApp = backupMetaData.find('externalApp').text
-
-
- ## Pre-creation checks
-
- if Websites.objects.filter(domain=domain).count() > 0:
- data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0,
- 'error_message': "This website already exists."}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
-
- if ChildDomains.objects.filter(domain=domain).count() > 0:
- data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0,
- 'error_message': "This website already exists as child domain."}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
-
- ####### Pre-creation checks ends
-
- numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count())
-
- ## Create Configurations
-
- execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
-
- execPath = execPath + " createVirtualHost --virtualHostName " + domain + " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + "' --virtualHostUser " + externalApp + " --numberOfSites " + numberOfWebsites + " --ssl " + str(
- 0) + " --sslPath " + "CyberPanel"
-
- output = subprocess.check_output(shlex.split(execPath))
-
- if output.find("1,None") > -1:
- selectedPackage = Package.objects.get(packageName="Default")
- website = Websites(admin=admin, package=selectedPackage, domain=domain, adminEmail=adminEmail,
- phpSelection=phpSelection, ssl=0, externalApp=externalApp)
- website.save()
- else:
- data_ret = {'createWebSiteStatus': 0, 'error_message': output, "existsStatus": 0}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
- ## Create Configurations ends here
-
- ## Create databases
-
- databases = backupMetaData.findall('Databases/database')
- website = Websites.objects.get(domain=domain)
-
- for database in databases:
- dbName = database.find('dbName').text
- dbUser = database.find('dbUser').text
-
- if mysqlUtilities.createDatabase(dbName, dbUser, "cyberpanel") == 0:
- data_ret = {'createWebSiteStatus': 0, 'error_message': "Failed to create Databases!", "existsStatus": 0}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
- newDB = Databases(website=website, dbName=dbName, dbUser=dbUser)
- newDB.save()
-
-
- ## Create dns zone
-
- dnsrecords = backupMetaData.findall('dnsrecords/dnsrecord')
-
- zone = Domains(admin=admin, name=domain, type="NATIVE")
- zone.save()
-
- for dnsrecord in dnsrecords:
-
- recordType = dnsrecord.find('type').text
- value = dnsrecord.find('name').text
- content = dnsrecord.find('content').text
- prio = int(dnsrecord.find('priority').text)
-
- if recordType == "SOA":
- record = Records(domainOwner=zone,
- domain_id=zone.id,
- name=value,
- type="SOA",
- content=content,
- ttl=3600,
- prio=0,
- disabled=0,
- auth=1)
- record.save()
- elif recordType == "NS":
- record = Records( domainOwner=zone,
- domain_id=zone.id,
- name=value,
- type="NS",
- content=content,
- ttl=3600,
- prio=0,
- disabled=0,
- auth=1 )
- record.save()
-
- elif recordType == "A":
- record = Records( domainOwner=zone,
- domain_id=zone.id,
- name=value,
- type="A",
- content=content,
- ttl=3600,
- prio=0,
- disabled=0,
- auth=1 )
- record.save()
- elif recordType == "MX":
- record = Records(domainOwner=zone,
- domain_id=zone.id,
- name=value,
- type="MX",
- content=content,
- ttl=3600,
- prio=prio,
- disabled=0,
- auth=1)
- record.save()
- elif recordType == "AAAA":
- record = Records( domainOwner=zone,
- domain_id=zone.id,
- name=value,
- type="AAAA",
- content=content,
- ttl=3600,
- prio=0,
- disabled=0,
- auth=1 )
- record.save()
-
- elif recordType == "CNAME":
- record = Records( domainOwner=zone,
- domain_id=zone.id,
- name=value,
- type="CNAME",
- content=content,
- ttl=3600,
- prio=0,
- disabled=0,
- auth=1 )
- record.save()
-
-
- elif recordType == "SPF":
- record = Records( domainOwner=zone,
- domain_id=zone.id,
- name=value,
- type="SPF",
- content=content,
- ttl=3600,
- prio=0,
- disabled=0,
- auth=1 )
- record.save()
-
-
- elif recordType == "TXT":
- record = Records( domainOwner=zone,
- domain_id=zone.id,
- name=value,
- type="TXT",
- content=content,
- ttl=3600,
- prio=0,
- disabled=0,
- auth=1 )
- record.save()
-
-
- data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
-
- except BaseException, msg:
- data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg), "existsStatus": 0}
- json_data = json.dumps(data_ret)
- return HttpResponse(json_data)
def listCron(request):
try: