Initial Command Line Interface.

This commit is contained in:
usmannasir
2018-06-01 02:08:21 +05:00
parent 659f2014b4
commit 371a26ea26
12 changed files with 2402 additions and 2517 deletions

0
cli/__init__.py Normal file
View File

28
cli/cliLogger.py Normal file
View File

@@ -0,0 +1,28 @@
import subprocess
import time
class cliLogger:
fileName = "/home/cyberpanel/error-logs.txt"
@staticmethod
def writeforCLI(message, level, method):
try:
file = open(cliLogger.fileName, 'a')
file.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "] [" + level + ":" + method + "] " + message + "\n")
file.close()
file.close()
except IOError:
return "Can not write to error file!"
@staticmethod
def readLastNFiles(numberOfLines,fileName):
try:
lastFewLines = subprocess.check_output(["tail", "-n",str(numberOfLines),fileName])
return lastFewLines
except subprocess.CalledProcessError,msg:
return "File was empty"

123
cli/cyberPanel.py Executable file
View File

@@ -0,0 +1,123 @@
#!/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 argparse
from inspect import stack
from cliLogger import cliLogger as logger
import json
from plogical.virtualHostUtilities import virtualHostUtilities
import re
from websiteFunctions.models import Websites, ChildDomains
from plogical.vhost import vhost
class cyberPanel:
def printStatus(self, operationStatus, errorMessage):
data = json.dumps({'success': operationStatus,
'errorMessage': errorMessage
})
print data
def createWebsite(self, package, owner, domainName, email, php, ssl, dkim, openBasedir):
try:
externalApp = "".join(re.findall("[a-zA-Z]+", domainName))[:7]
numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count())
sslpath = "/home/" + domainName + "/public_html"
phpSelection = 'PHP ' + php
result = virtualHostUtilities.createVirtualHost(domainName, email, phpSelection, externalApp, numberOfWebsites, ssl, sslpath, dkim,
openBasedir, owner, package)
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:
numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count()
vhost.deleteVirtualHostConfigurations(domainName, numberOfWebsites)
self.printStatus(1, 'None')
except BaseException, msg:
logger.writeforCLI(str(msg), "Error", stack()[0][3])
print 0
def main():
parser = argparse.ArgumentParser(description='CyberPanel Command Line Interface!')
parser.add_argument('function', help='Specific a operation to perform!')
## 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()
if args.function == "createWebsite":
completeCommandExample = 'cyberpanel createWebsite --package Detault --owner admin --domainName cyberpanel.net --email support@cyberpanel.net --php 5.6'
if not args.package:
print "\n\nPlease enter the package name. For example:\n\n" + completeCommandExample + "\n\n"
if not args.owner:
print "\n\nPlease enter the owner name. For example:\n\n" + completeCommandExample + "\n\n"
if not args.domainName:
print "\n\nPlease enter the domain name. For example:\n\n" + completeCommandExample + "\n\n"
if not args.email:
print "\n\nPlease enter the email. For example:\n\n" + completeCommandExample + "\n\n"
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"
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 = cyberPanel()
cyberpanel.createWebsite(args.package, args.owner, args.domainName, args.email, args.php, ssl, dkim, openBasedir)
elif args.function == "deleteWebsite":
completeCommandExample = 'cyberpanel deleteWebsite --domainName cyberpanel.net'
if not args.domainName:
print "\n\nPlease enter the domain to delete. For example:\n\n" + completeCommandExample + "\n\n"
return
cyberpanel = cyberPanel()
cyberpanel.deleteWebsite(args.domainName)
if __name__ == "__main__":
main()

View File

@@ -593,26 +593,6 @@ def submitZoneDeletion(request):
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
def createDNSRecord(request, zone, name, type, value, priority, ttl):
try:
val = request.session['userID']
if Records.objects.filter(name=name, type=type).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()
except KeyError,msg:
final_dic = {'add_status': 0, 'error_message': "Not Logged In, please refresh the page or login again."}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)

View File

@@ -2669,7 +2669,7 @@ def main():
parser = argparse.ArgumentParser(description='CyberPanel Installer')
parser.add_argument('publicip', help='Please enter public IP for your VPS or dedicated server.')
parser.add_argument('mysql', help='Specify number of MySQL instances to be used.')
parser.add_argument('--mysql', help='Specify number of MySQL instances to be used.')
args = parser.parse_args()
logging.InstallLog.writeToFile("Starting CyberPanel installation..")
@@ -2687,6 +2687,11 @@ def main():
checks = preFlightsChecks("/usr/local/lsws/",args.publicip,"/usr/local",cwd,"/usr/local/CyberCP")
try:
mysql = args.mysql
except:
mysql = 'One'
checks.checkPythonVersion()
checks.setup_account_cyberpanel()
@@ -2706,12 +2711,12 @@ def main():
import installCyberPanel
installCyberPanel.Main(cwd, args.mysql)
installCyberPanel.Main(cwd, mysql)
checks.fix_selinux_issue()
checks.install_psmisc()
checks.install_postfix_davecot()
checks.setup_email_Passwords(installCyberPanel.InstallCyberPanel.mysqlPassword, args.mysql)
checks.setup_postfix_davecot_config(args.mysql)
checks.setup_email_Passwords(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql)
checks.setup_postfix_davecot_config(mysql)
checks.install_unzip()
@@ -2731,7 +2736,7 @@ def main():
checks.installCertBot()
checks.test_Requests()
checks.download_install_CyberPanel(installCyberPanel.InstallCyberPanel.mysqlPassword, args.mysql)
checks.download_install_CyberPanel(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql)
checks.setup_cron()
checks.installTLDExtract()
#checks.installdnsPython()

View File

@@ -14,6 +14,17 @@ class CyberCPLogFileWriter:
except IOError,msg:
return "Can not write to error file."
@staticmethod
def writeforCLI(message, level, method):
try:
file = open(CyberCPLogFileWriter.fileName, 'a')
file.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "] [" + level + ":" + method + "] " + message + "\n")
file.close()
file.close()
except IOError:
return "Can not write to error file!"
@staticmethod
def readLastNFiles(numberOfLines,fileName):
try:

0
plogical/childDomain.py Normal file
View File

View File

@@ -1,7 +1,14 @@
#!/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 CyberCPLogFileWriter as logging
import os
import subprocess
import shutil
import shlex
from dns.models import Domains,Records
class DNS:
@@ -9,373 +16,298 @@ class DNS:
zones_base_dir = "/usr/local/lsws/conf/zones/"
create_zone_dir = "/usr/local/lsws/conf/zones"
## DNS Functions
@staticmethod
def createNameServer(virtualHostName, firstNS, firstNSIP, secondNS, secondNSIP):
def dnsTemplate(domain, admin):
try:
if not os.path.exists(DNS.zones_base_dir):
os.mkdir(DNS.create_zone_dir)
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
zonePath = DNS.zones_base_dir + virtualHostName
zoneFilePath = zonePath + "/zone.conf"
import tldextract
extractDomain = tldextract.extract(domain)
topLevelDomain = extractDomain.domain + '.' + extractDomain.suffix
subDomain = extractDomain.subdomain
if len(subDomain) == 0:
data = open(DNS.nsd_base, "r").readlines()
if Domains.objects.filter(name=topLevelDomain).count() == 0:
zone = Domains(admin=admin, name=topLevelDomain, type="NATIVE")
zone.save()
if DNS.checkIfZoneExists(virtualHostName, data) == 1:
content = "ns1." + topLevelDomain + " hostmaster." + topLevelDomain + " 1 10800 3600 604800 3600"
os.mkdir(zonePath)
zoneFileToWrite = open(zoneFilePath, "w")
soaRecord = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="SOA",
content=content,
ttl=3600,
prio=0,
disabled=0,
auth=1)
soaRecord.save()
if DNS.addEntryInMainZone(virtualHostName, data) == 1:
if DNS.perVirtualHostZoneFile(virtualHostName, zoneFileToWrite) == 1:
if DNS.addNSRecord(firstNS, firstNSIP, secondNS, secondNSIP, zoneFileToWrite) == 1:
DNS.restartNSD()
zoneFileToWrite.close()
return 1
else:
zoneFileToWrite.close()
return 0
else:
zoneFileToWrite.close()
return 0
else:
zoneFileToWrite.close()
return 0
## Main A record.
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="A",
content=ipAddress,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
# CNAME Records.
cNameValue = "www." + topLevelDomain
record = Records(domainOwner=zone,
domain_id=zone.id,
name=cNameValue,
type="CNAME",
content=topLevelDomain,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
cNameValue = "ftp." + topLevelDomain
record = Records(domainOwner=zone,
domain_id=zone.id,
name=cNameValue,
type="CNAME",
content=topLevelDomain,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
## MX Record.
mxValue = "mail." + topLevelDomain
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="MX",
content=mxValue,
ttl=3600,
prio="10",
disabled=0,
auth=1)
record.save()
record = Records(domainOwner=zone,
domain_id=zone.id,
name=mxValue,
type="A",
content=ipAddress,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
## TXT Records for mail
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="TXT",
content="v=spf1 a mx ip4:" + ipAddress + " ~all",
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
record = Records(domainOwner=zone,
domain_id=zone.id,
name="_dmarc." + topLevelDomain,
type="TXT",
content="v=DMARC1; p=none",
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
record = Records(domainOwner=zone,
domain_id=zone.id,
name="_domainkey." + topLevelDomain,
type="TXT",
content="t=y; o=~;",
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
else:
if not os.path.exists(zonePath):
os.mkdir(zonePath)
zoneFileToWrite = open(zoneFilePath, "w")
if Domains.objects.filter(name=topLevelDomain).count() == 0:
zone = Domains(admin=admin, name=topLevelDomain, type="NATIVE")
zone.save()
content = "ns1." + topLevelDomain + " hostmaster." + topLevelDomain + " 1 10800 3600 604800 3600"
if DNS.perVirtualHostZoneFile(virtualHostName, zoneFileToWrite) == 1:
if DNS.addNSRecord(firstNS, firstNSIP, secondNS, secondNSIP, zoneFileToWrite) == 1:
DNS.restartNSD()
zoneFileToWrite.close()
return 1
else:
zoneFileToWrite.close()
return 0
else:
zoneFileToWrite.close()
return 0
soaRecord = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="SOA",
content=content,
ttl=3600,
prio=0,
disabled=0,
auth=1)
soaRecord.save()
else:
## Main A record.
zoneFileToWrite = open(zoneFilePath, "a")
if DNS.addNSRecord(firstNS, firstNSIP, secondNS, secondNSIP, zoneFileToWrite) == 1:
DNS.restartNSD()
zoneFileToWrite.close()
return 1
else:
zoneFileToWrite.close()
return 0
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="A",
content=ipAddress,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
zoneFileToWrite.close()
logging.CyberCPLogFileWriter.writeToFile(
"Zone file for virtualhost already exists. " + "[createNameServer]")
return 1
# CNAME Records.
except IOError, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addEntryInMainZone]")
return 0
cNameValue = "www." + topLevelDomain
@staticmethod
def checkIfZoneExists(virtualHostName,data):
for items in data:
if items.find(virtualHostName) > -1:
return 0
return 1
record = Records(domainOwner=zone,
domain_id=zone.id,
name=cNameValue,
type="CNAME",
content=topLevelDomain,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
cNameValue = "ftp." + topLevelDomain
@staticmethod
def addEntryInMainZone(virtualHostName,data):
record = Records(domainOwner=zone,
domain_id=zone.id,
name=cNameValue,
type="CNAME",
content=topLevelDomain,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
# Defining zone to be added
zone = "zone:" + "\n"
zoneName = " name: " + virtualHostName + "\n"
zoneFile = " zonefile: "+virtualHostName+"/zone.conf" + "\n"
## MX Record.
mxValue = "mail." + topLevelDomain
try:
mainZoneFile = open(DNS.nsd_base,"w")
zoneCheck = 1
noZones = 1
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="MX",
content=mxValue,
ttl=3600,
prio="10",
disabled=0,
auth=1)
record.save()
for items in data:
if items.find("zone:")>-1 and zoneCheck==1:
mainZoneFile.writelines(zone)
mainZoneFile.writelines(zoneName)
mainZoneFile.writelines(zoneFile)
mainZoneFile.writelines("\n")
mainZoneFile.writelines(items)
noZones = 0
zoneCheck = 0
else:
mainZoneFile.writelines(items)
record = Records(domainOwner=zone,
domain_id=zone.id,
name=mxValue,
type="A",
content=ipAddress,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
if noZones ==1:
mainZoneFile.writelines(zone)
mainZoneFile.writelines(zoneName)
mainZoneFile.writelines(zoneFile)
mainZoneFile.writelines("\n")
## Creating sub-domain level record.
mainZoneFile.close()
return 1
except IOError,msg:
mainZoneFile.close()
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addEntryInMainZone]")
return 0
zone = Domains.objects.get(name=topLevelDomain)
@staticmethod
def perVirtualHostZoneFile(virtualHostName, zoneFileToWrite):
actualSubDomain = subDomain + "." + topLevelDomain
# Make zone directory
## Main A record.
origin = "$ORIGIN " + virtualHostName + "." + "\n"
ttl = "$TTL 86400" + "\n"
DNS.createDNSRecord(zone, actualSubDomain, "A", ipAddress, 0, 3600)
try:
zoneFileToWrite.writelines(origin)
zoneFileToWrite.writelines(ttl)
zoneFileToWrite.writelines("\n")
# CNAME Records.
# Create SOA Record
DNS.createSOARecord(virtualHostName, zoneFileToWrite)
return 1
cNameValue = "www." + actualSubDomain
DNS.createDNSRecord(zone, cNameValue, "CNAME", actualSubDomain, 0, 3600)
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [perVirtualHostZoneFile]")
return 0
logging.CyberCPLogFileWriter.writeToFile(
"We had errors while creating DNS records for: " + domain + ". Error message: " + str(msg))
@staticmethod
def createSOARecord(virtualHostName,fileHandle):
# Define SOA Record
soa = "@ IN SOA ns1 admin@"+virtualHostName+" (" + "\n"
serialNumber = " 2012082703" + "\n"
refreshRate = " 28800" + "\n"
retryRate = " 1400" + "\n"
expiry = " 864000" + "\n"
minTTL = " 86400" + "\n"
endSOA = " )" + "\n"
def createDKIMRecords(domain):
try:
fileHandle.writelines("\n")
fileHandle.writelines(soa)
fileHandle.writelines(serialNumber)
fileHandle.writelines(refreshRate)
fileHandle.writelines(retryRate)
fileHandle.writelines(expiry)
fileHandle.writelines(minTTL)
fileHandle.writelines(endSOA)
import tldextract
extractDomain = tldextract.extract(domain)
topLevelDomain = extractDomain.domain + '.' + extractDomain.suffix
fileHandle.writelines("\n")
zone = Domains.objects.get(name=topLevelDomain)
path = "/etc/opendkim/keys/" + topLevelDomain + "/default.txt"
command = "sudo cat " + path
output = subprocess.check_output(shlex.split(command))
return 1
except IOError,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createSOARecord]")
return 0
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))
@staticmethod
def addNSRecord(nsRecordOne,firstNSIP, nsRecordTwo, secondNSIP, fileHandle):
# Defining NS Record
NSARecordOne = nsRecordOne.split(".")[0]
NSARecordTwo = nsRecordTwo.split(".")[0]
NS1 = "\t\t" + "NS" + "\t" + nsRecordOne + "." "\n"
NS2 = "\t\t" + "NS" + "\t" + nsRecordTwo + "."
try:
fileHandle.writelines("\n")
fileHandle.writelines("\n")
fileHandle.writelines(NS1)
fileHandle.writelines(NS2)
DNS.addRecord(NSARecordOne, "A", firstNSIP, fileHandle)
DNS.addRecord(NSARecordTwo, "A", secondNSIP, fileHandle)
fileHandle.writelines("\n")
return 1
except IOError, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addRecord]")
return 0
def createDNSRecord(zone, name, type, value, priority, ttl):
if Records.objects.filter(name=name, type=type).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()
@staticmethod
def addRecord(recordValue, recordType, recordIP, fileHandle):
# Define Record
recordString = recordValue +"\t" + "IN" + "\t" + recordType + "\t" + recordIP
def deleteDNSZone(virtualHostName):
try:
fileHandle.writelines("\n")
fileHandle.writelines(recordString)
fileHandle.writelines("\n")
return 1
except IOError, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addRecord]")
return 0
@staticmethod
def restartNSD():
try:
############## Restart NSD ######################
cmd = []
cmd.append("systemctl")
cmd.append("restart")
cmd.append("nsd")
res = subprocess.call(cmd)
if res == 1:
print("###############################################")
print(" Could restart NSD ")
print("###############################################")
logging.CyberCPLogFileWriter.writeToFile("[Failed to restart NSD]")
return 0
else:
print("###############################################")
print(" NSD Restarted ")
print("###############################################")
return 1
except OSError, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [restartNSD]")
return 0
@staticmethod
def deleteZone(virtualHostname):
try:
if os.path.exists(DNS.zones_base_dir+virtualHostname):
shutil.rmtree(DNS.zones_base_dir+virtualHostname)
data = open(DNS.nsd_base, "r").readlines()
writeDataToFile = open(DNS.nsd_base,"w")
index = 0
for items in data:
if items.find(virtualHostname) >-1:
try:
del data[index-1]
del data[index-1]
del data[index-1]
delZone = Domains.objects.get(name=virtualHostName)
delZone.delete()
except:
break
break
index = index+1
for items in data:
writeDataToFile.writelines(items)
writeDataToFile.close()
except OSError,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [deleteZone]")
@staticmethod
def addARecord(virtualHostName,recordValue,recordIP):
try:
if not os.path.exists(DNS.zones_base_dir):
os.mkdir(DNS.create_zone_dir)
data = open(DNS.nsd_base, "r").readlines()
zonePath = DNS.zones_base_dir + virtualHostName
zoneFilePath = zonePath + "/zone.conf"
if DNS.checkIfZoneExists(virtualHostName,data) == 1:
DNS.addEntryInMainZone(virtualHostName,data)
os.mkdir(zonePath)
zoneFileToWrite = open(zoneFilePath, "w")
DNS.perVirtualHostZoneFile(virtualHostName, zoneFileToWrite)
DNS.addRecord(recordValue,"A",recordIP,zoneFileToWrite)
else:
if not os.path.exists(zonePath):
os.mkdir(zonePath)
zoneFileToWrite = open(zoneFilePath, "w")
if DNS.perVirtualHostZoneFile(virtualHostName, zoneFileToWrite) == 1:
if DNS.addRecord(recordValue,"A",recordIP,zoneFileToWrite) == 1:
DNS.restartNSD()
zoneFileToWrite.close()
return 1
else:
zoneFileToWrite.close()
return 0
else:
zoneFileToWrite.close()
return 0
else:
zoneFileToWrite = open(zoneFilePath, "a")
if DNS.addRecord(recordValue,"A",recordIP,zoneFileToWrite) == 1:
DNS.restartNSD()
zoneFileToWrite.close()
return 1
else:
zoneFileToWrite.close()
return 0
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [addARecord]')
@staticmethod
def deleteRecord(recordValue, recordType, recordIP, virtualHostName):
try:
zonePath = DNS.zones_base_dir + virtualHostName
zoneFilePath = zonePath + "/zone.conf"
data = open(zoneFilePath, "r").readlines()
writeDataToFile = open(zoneFilePath, "w")
for items in data:
if items.find(recordIP) > -1 and items.find(recordValue) > -1 and items.find(recordType)>-1:
continue
else:
writeDataToFile.writelines(items)
writeDataToFile.close()
return 1
except IOError, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addRecord]")
return 0
## There does not exist a zone for this domain.
pass

View File

@@ -143,7 +143,7 @@ class installUtilities:
cmd = shlex.split(command)
res = subprocess.call(cmd)
res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT)
if res == 1:
print("###############################################")

1069
plogical/vhost.py Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -25,7 +25,6 @@ from random import randint
import hashlib
from xml.etree import ElementTree
from plogical.mailUtilities import mailUtilities
from dns.views import createDNSRecord
# Create your views here.
@@ -170,248 +169,6 @@ def deleteWebsite(request):
except KeyError:
return redirect(loadLoginPage)
def dnsTemplate(request, domain, admin):
try:
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
import tldextract
extractDomain = tldextract.extract(domain)
topLevelDomain = extractDomain.domain + '.' + extractDomain.suffix
subDomain = extractDomain.subdomain
if len(subDomain) == 0:
if Domains.objects.filter(name=topLevelDomain).count() == 0:
zone = Domains(admin=admin, name=topLevelDomain, type="NATIVE")
zone.save()
content = "ns1." + topLevelDomain + " hostmaster." + topLevelDomain + " 1 10800 3600 604800 3600"
soaRecord = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="SOA",
content=content,
ttl=3600,
prio=0,
disabled=0,
auth=1)
soaRecord.save()
## Main A record.
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="A",
content=ipAddress,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
# CNAME Records.
cNameValue = "www." + topLevelDomain
record = Records(domainOwner=zone,
domain_id=zone.id,
name=cNameValue,
type="CNAME",
content=topLevelDomain,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
cNameValue = "ftp." + topLevelDomain
record = Records(domainOwner=zone,
domain_id=zone.id,
name=cNameValue,
type="CNAME",
content=topLevelDomain,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
## MX Record.
mxValue = "mail." + topLevelDomain
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="MX",
content=mxValue,
ttl=3600,
prio="10",
disabled=0,
auth=1)
record.save()
record = Records(domainOwner=zone,
domain_id=zone.id,
name=mxValue,
type="A",
content=ipAddress,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
## TXT Records for mail
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="TXT",
content="v=spf1 a mx ip4:" + ipAddress + " ~all",
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
record = Records(domainOwner=zone,
domain_id=zone.id,
name="_dmarc." + topLevelDomain,
type="TXT",
content="v=DMARC1; p=none",
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
record = Records(domainOwner=zone,
domain_id=zone.id,
name="_domainkey." + topLevelDomain,
type="TXT",
content="t=y; o=~;",
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
else:
if Domains.objects.filter(name=topLevelDomain).count() == 0:
zone = Domains(admin=admin, name=topLevelDomain, type="NATIVE")
zone.save()
content = "ns1." + topLevelDomain + " hostmaster." + topLevelDomain + " 1 10800 3600 604800 3600"
soaRecord = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="SOA",
content=content,
ttl=3600,
prio=0,
disabled=0,
auth=1)
soaRecord.save()
## Main A record.
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="A",
content=ipAddress,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
# CNAME Records.
cNameValue = "www." + topLevelDomain
record = Records(domainOwner=zone,
domain_id=zone.id,
name=cNameValue,
type="CNAME",
content=topLevelDomain,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
cNameValue = "ftp." + topLevelDomain
record = Records(domainOwner=zone,
domain_id=zone.id,
name=cNameValue,
type="CNAME",
content=topLevelDomain,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
## MX Record.
mxValue = "mail." + topLevelDomain
record = Records(domainOwner=zone,
domain_id=zone.id,
name=topLevelDomain,
type="MX",
content=mxValue,
ttl=3600,
prio="10",
disabled=0,
auth=1)
record.save()
record = Records(domainOwner=zone,
domain_id=zone.id,
name=mxValue,
type="A",
content=ipAddress,
ttl=3600,
prio=0,
disabled=0,
auth=1)
record.save()
## Creating sub-domain level record.
zone = Domains.objects.get(name=topLevelDomain)
actualSubDomain = subDomain + "." + topLevelDomain
## Main A record.
createDNSRecord(request, zone, actualSubDomain, "A", ipAddress, 0, 3600)
# CNAME Records.
cNameValue = "www." + actualSubDomain
createDNSRecord(request, zone, cNameValue, "CNAME", actualSubDomain, 0, 3600)
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(
"We had errors while creating DNS records for: " + domain + ". Error message: " + str(msg))
def createDKIMRecords(request, domain, admin):
try:
@@ -495,19 +252,6 @@ def submitWebsiteCreation(request):
externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:7]
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)
####### Limitations check
admin = Administrator.objects.get(userName=websiteOwner)
@@ -523,12 +267,6 @@ def submitWebsiteCreation(request):
####### Limitations Check End
##### Zone creation
dnsTemplate(requests, domain, admin)
## zone creation
numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count())
sslpath = "/home/" + domain + "/public_html"
@@ -536,9 +274,12 @@ def submitWebsiteCreation(request):
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
execPath = execPath + " createVirtualHost --virtualHostName " + domain + " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + "' --virtualHostUser " + externalApp + " --numberOfSites " + numberOfWebsites + " --ssl " + str(
data['ssl']) + " --sslPath " + sslpath + " --dkimCheck " + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir'])
execPath = execPath + " createVirtualHost --virtualHostName " + domain + \
" --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \
"' --virtualHostUser " + externalApp + " --numberOfSites " + numberOfWebsites + \
" --ssl " + str(data['ssl']) + " --sslPath " + sslpath + " --dkimCheck " + str(data['dkimCheck'])\
+ " --openBasedir " + str(data['openBasedir']) + ' --websiteOwner ' + websiteOwner \
+ ' --package ' + packageName
output = subprocess.check_output(shlex.split(execPath))
@@ -549,18 +290,6 @@ def submitWebsiteCreation(request):
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
## Create Configurations ends here
## DKIM Check
if data['dkimCheck'] == 1:
createDKIMRecords(request, domain, admin)
selectedPackage = Package.objects.get(packageName=packageName)
website = Websites(admin=admin, package=selectedPackage, domain=domain, adminEmail=adminEmail,phpSelection=phpSelection, ssl=data['ssl'], externalApp=externalApp)
website.save()
data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0}
json_data = json.dumps(data_ret)
@@ -579,71 +308,45 @@ def submitDomainCreation(request):
masterDomain = data['masterDomain']
domain = data['domainName']
phpSelection = data['phpSelection']
## Check if this domain either exists as website or child domain
if Websites.objects.filter(domain=domain).count() > 0:
data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0,
'error_message': "This Domain already exists as a website."}
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 domain already exists as child domain."}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
####### Limitations check
master = Websites.objects.get(domain=masterDomain)
domainsInPackage = master.package.allowedDomains
if domainsInPackage == 0:
pass
elif domainsInPackage > master.childdomains_set.all().count():
pass
else:
data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0,
'error_message': "Exceeded maximum number of domains for this package"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
####### Limitations Check End
ssl = data['ssl']
path = data['path']
restart = 1
## Create Configurations
try:
restore = data['restore']
restart = 0
except:
restore = '1'
if len(path) > 0:
path = path.lstrip("/")
path = "/home/" + masterDomain + "/public_html/" + path
else:
path = "/home/" + masterDomain + "/public_html/" + domain
### Zone creation.
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \
" --phpVersion '" + phpSelection + "' --ssl " + str(data['ssl']) + " --dkimCheck " + \
str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path \
+ ' --restore ' + restore
except:
restore = '0'
if len(path) > 0:
path = path.lstrip("/")
path = "/home/" + masterDomain + "/public_html/" + path
else:
path = "/home/" + masterDomain + "/public_html/" + domain
val = request.session['userID']
admin = Administrator.objects.get(pk=val)
dnsTemplate(requests, domain, admin)
externalApp = master.externalApp
numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count())
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + " --administratorEmail " + master.adminEmail + " --phpVersion '" + phpSelection + "' --virtualHostUser " + externalApp + " --numberOfSites " + numberOfWebsites + " --ssl " + str(
data['ssl']) + " --path " + path + " --dkimCheck " + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir'])
execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \
" --phpVersion '" + phpSelection + "' --ssl " + str(data['ssl']) + " --dkimCheck " + str(data['dkimCheck']) \
+ " --openBasedir " + str(data['openBasedir']) + ' --path ' + path \
+ ' --restore ' + restore + ' --websiteOwner ' + admin.userName
output = subprocess.check_output(shlex.split(execPath))
@@ -654,21 +357,6 @@ def submitDomainCreation(request):
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
## Create Configurations ends here
## DKIM Check
try:
restore = data['restore']
restart = 0
except BaseException, msg:
if data['dkimCheck'] == 1:
admin = Administrator.objects.get(pk=val)
createDKIMRecords(request, domain, admin)
website = ChildDomains(master=master, domain=domain, path=path, phpSelection=phpSelection, ssl=ssl)
website.save()
data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0}
json_data = json.dumps(data_ret)
@@ -850,41 +538,6 @@ def submitWebsiteDeletion(request):
subprocess.check_output(shlex.split(execPath))
delWebsite = Websites.objects.get(domain=websiteName)
databases = Databases.objects.filter(website=delWebsite)
childDomains = delWebsite.childdomains_set.all()
## Deleting child domains
for items in childDomains:
numberOfWebsites = str(Websites.objects.count()+ChildDomains.objects.count())
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + items.domain + " --numberOfSites " + numberOfWebsites
subprocess.check_output(shlex.split(execPath))
for items in databases:
mysqlUtilities.deleteDatabase(items.dbName, items.dbUser)
delWebsite.delete()
try:
delZone = Domains.objects.get(name=websiteName)
delZone.delete()
except:
## There does not exist a zone for this domain.
pass
installUtilities.reStartLiteSpeed()
## Delete mail accounts
command = "sudo rm -rf /home/vmail/" + websiteName
subprocess.call(shlex.split(command))
data_ret = {'websiteDeleteStatus': 1,'error_message': "None"}
json_data = json.dumps(data_ret)
@@ -909,25 +562,12 @@ def submitDomainDeletion(request):
data = json.loads(request.body)
websiteName = data['websiteName']
numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count())
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName + " --numberOfSites " + numberOfWebsites
execPath = execPath + " deleteDomain --virtualHostName " + websiteName
subprocess.check_output(shlex.split(execPath))
delWebsite = ChildDomains.objects.get(domain=websiteName)
delWebsite.delete()
installUtilities.reStartLiteSpeed()
data_ret = {'websiteDeleteStatus': 1,'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
@@ -2718,14 +2358,6 @@ def submitAliasCreation(request):
admin = Administrator.objects.get(pk=request.session['userID'])
##### Zone creation
dnsTemplate(requests, aliasDomain, admin)
### Zone creation
sslpath = "/home/" + masterDomain + "/public_html"
## Create Configurations
@@ -2733,7 +2365,7 @@ def submitAliasCreation(request):
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
execPath = execPath + " createAlias --masterDomain " + masterDomain + " --aliasDomain " + aliasDomain + " --ssl " + str(
ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email
ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName
output = subprocess.check_output(shlex.split(execPath))
@@ -2746,8 +2378,6 @@ def submitAliasCreation(request):
## Create Configurations ends here
data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)