def __CheckRedirectStart(self,get,action=""): isError = public.checkWebConfig() if (isError != True): return public.returnMsg(False, 'GET_ERR_IN_CONFILE') if action == "create": #检测名称是否重复 if sys.version_info.major < 3: if len(get.redirectname) < 3 or len(get.redirectname) > 15: print("NAME_LEN") return public.returnMsg(False, 'NAME_LEN') else: if len(get.redirectname.encode("utf-8")) < 3 or len(get.redirectname.encode("utf-8")) > 15: print("NAME_LEN") return public.returnMsg(False, 'NAME_LEN') if self.__CheckRedirect(get.sitename,get.redirectname): return public.returnMsg(False, 'REDIRECT_EXIST') #检测是否选择域名 if get.domainorpath == "domain": if not json.loads(get.redirectdomain): return public.returnMsg(False, 'SELECT_RED_DOMAIN') else: if not get.redirectpath: return public.returnMsg(False, 'INPUT_RED_DOMAIN') #repte = "[\?\=\[\]\)\(\*\&\^\%\$\#\@\!\~\`{\}\>\<\,\',\"]+" # 检测路径格式 if "/" not in get.redirectpath: return public.returnMsg(False, "PATH_ERR") #if re.search(repte, get.redirectpath): # return public.returnMsg(False, "代理目录不能有以下特殊符号 ?,=,[,],),(,*,&,^,%,$,#,@,!,~,`,{,},>,<,\,',\"]") #检测域名是否已经存在配置文件 repeatdomain = self.__CheckRepeatDomain(get,action) if repeatdomain: return public.returnMsg(False, 'RED_DOMAIN_EXIST' , (repeatdomain,)) #检测路径是否有存在配置文件 repeatpath = self.__CheckRepeatPath(get) if repeatpath: return public.returnMsg(False, 'RED_DOMAIN_EXIST' , (repeatpath,)) #检测目标URL格式 rep = "http(s)?\:\/\/([a-zA-Z0-9][-a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9][a-zA-Z0-9]{0,62})+.?" if not re.match(rep, get.tourl): return public.returnMsg(False, 'URL_FORMAT_ERR' ,(get.tourl,)) #检测目标URL是否可用 #if self.__CheckRedirectUrl(get): # return public.returnMsg(False, '目标URL无法访问') #检查目标URL的域名和被重定向的域名是否一样 if get.domainorpath == "domain": for d in json.loads(get.redirectdomain): tu = self.GetToDomain(get.tourl) if d == tu: return public.GetMsg("DOMAIN_SAMEAS_URL",(d,)) if get.domainorpath == "path": domains = self.GetAllDomain(get.sitename) rep = "https?://(.*)" tu = re.search(rep,get.tourl).group(1) for d in domains: ad = "%s%s" % (d,get.redirectpath) #站点域名+重定向路径 if tu == ad: return public.GetMsg("URL_SAMEAS_REDPATH",(tu,))
def SaveFileBody(self, get): get.path = get.path.encode('utf-8') if not os.path.exists(get.path): if get.path.find('.htaccess') == -1: return public.returnMsg(False, 'The specified file does not exist!') try: isConf = get.path.find('.conf') if isConf != -1: os.system('\\cp -a ' + get.path + ' /tmp/backup.conf') data = get.data[0] if get.encoding == 'ascii': get.encoding = 'utf-8' public.writeFile(get.path, data.encode(get.encoding)) if isConf != -1: isError = public.checkWebConfig() if isError != True: os.system('\\cp -a /tmp/backup.conf ' + get.path) return public.returnMsg( False, 'Configuration file error:<br><font style="color:red;">' + isError.replace("\n", '<br>') + '</font>') public.serviceReload() return public.returnMsg(True, 'File saved successfully!') except: return public.returnMsg(False, 'File save failed!')
def __CheckRedirectStart(self, get, action=""): isError = public.checkWebConfig() if (isError != True): return public.returnMsg(False, '配置文件出错请先排查配置') if action == "create": #检测名称是否重复 if sys.version_info.major < 3: if len(get.redirectname) < 3 or len(get.redirectname) > 15: return public.returnMsg(False, '名称必须大于3小于15个字符串') else: if len(get.redirectname.encode("utf-8")) < 3 or len( get.redirectname.encode("utf-8")) > 15: return public.returnMsg(False, '名称必须大于3小于15个字符串') if self.__CheckRedirect(get.sitename, get.redirectname): return public.returnMsg(False, '指定重定向名称已存在') #检测是否选择域名 if get.domainorpath == "domain": if not json.loads(get.redirectdomain): return public.returnMsg(False, '请选择重定向域名') else: if not get.redirectpath: return public.returnMsg(False, '请输入重定向路径') #repte = "[\?\=\[\]\)\(\*\&\^\%\$\#\@\!\~\`{\}\>\<\,\',\"]+" # 检测路径格式 if "/" not in get.redirectpath: return public.returnMsg(False, "路径格式不正确,格式为/xxx") #if re.search(repte, get.redirectpath): # return public.returnMsg(False, "代理目录不能有以下特殊符号 ?,=,[,],),(,*,&,^,%,$,#,@,!,~,`,{,},>,<,\,',\"]") #检测域名是否已经存在配置文件 repeatdomain = self.__CheckRepeatDomain(get, action) if repeatdomain: return public.returnMsg(False, '重定向域名重复 %s' % (repeatdomain)) #检测路径是否有存在配置文件 repeatpath = self.__CheckRepeatPath(get) if repeatpath: return public.returnMsg(False, '重定向路径重复 %s' % (repeatpath)) #检测目标URL格式 rep = "http(s)?\:\/\/([a-zA-Z0-9][-a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9][a-zA-Z0-9]{0,62})+.?" if not re.match(rep, get.tourl): return public.returnMsg(False, '目标URL格式不对 %s' + get.tourl) #检测目标URL是否可用 #if self.__CheckRedirectUrl(get): # return public.returnMsg(False, '目标URL无法访问') #检查目标URL的域名和被重定向的域名是否一样 if get.domainorpath == "domain": for d in json.loads(get.redirectdomain): tu = self.GetToDomain(get.tourl) if d == tu: return '域名 "%s" 和目标域名一致请取消选择' % (d) if get.domainorpath == "path": domains = self.GetAllDomain(get.sitename) rep = "https?://(.*)" tu = re.search(rep, get.tourl).group(1) for d in domains: ad = "%s%s" % (d, get.redirectpath) #站点域名+重定向路径 if tu == ad: return '"%s" ,目标URL和被重定向路径一致请不要花样作死' % (tu)
def SaveFileBody(self, get): if sys.version_info[0] == 2: get.path = get.path.encode('utf-8') if not os.path.exists(get.path): if get.path.find('.htaccess') == -1: return public.returnMsg(False, 'FILE_NOT_EXISTS') try: isConf = -1 if os.path.exists('/etc/init.d/nginx') or os.path.exists( '/etc/init.d/httpd'): isConf = get.path.find('nginx') if isConf == -1: isConf = get.path.find('apache') if isConf == -1: isConf = get.path.find('rewrite') if isConf != -1: os.system('\\cp -a ' + get.path + ' /tmp/backup.conf') data = get.data userini = False if get.path.find('.user.ini') != -1: userini = True public.ExecShell('chattr -i ' + get.path) if get.path.find('/www/server/cron') != -1: try: import crontab data = crontab.crontab().CheckScript(data) except: pass if get.encoding == 'ascii': get.encoding = 'utf-8' if sys.version_info[0] == 2: data = data.encode(get.encoding, errors='ignore') fp = open(get.path, 'w+') else: data = data.encode(get.encoding, errors='ignore').decode(get.encoding) fp = open(get.path, 'w+', encoding=get.encoding) fp.write(data) fp.close() if isConf != -1: isError = public.checkWebConfig() if isError != True: os.system('\\cp -a /tmp/backup.conf ' + get.path) return public.returnMsg( False, 'ERROR:<br><font style="color:red;">' + isError.replace("\n", '<br>') + '</font>') public.serviceReload() if userini: public.ExecShell('chattr +i ' + get.path) public.WriteLog('TYPE_FILE', 'FILE_SAVE_SUCCESS', (get.path, )) return public.returnMsg(True, 'FILE_SAVE_SUCCESS') except Exception as ex: return public.returnMsg(False, 'FILE_SAVE_ERR' + str(ex))
def check_site_conf(self,webserver,site_name,name): isError = public.checkWebConfig() auth_file = "{setup_path}/panel/vhost/{webserver}/dir_auth/{site_name}/{name}.conf".format(setup_path=self.setup_path,webserver=webserver,site_name=site_name,name=name) if (isError != True): os.remove(auth_file) # a_conf = self._read_conf() # for i in range(len(a_conf)-1,-1,-1): # if site_name == a_conf[i]["sitename"] and a_conf[i]["proxyname"]: # del a_conf[i] return public.returnMsg(False, 'ERROR: %s<br><a style="color:red;">' % public.GetMsg("CONFIG_ERROR") + isError.replace("\n", '<br>') + '</a>')
def SaveFileBody(self,get): get.path = get.path.encode('utf-8'); if not os.path.exists(get.path): if get.path.find('.htaccess') == -1: return public.returnMsg(False,'FILE_NOT_EXISTS') try: isConf = -1 if os.path.exists('/etc/init.d/nginx') or os.path.exists('/etc/init.d/httpd'): isConf = get.path.find('nginx'); if isConf == -1: isConf = get.path.find('apache'); if isConf == -1: isConf = get.path.find('rewrite'); if isConf != -1: os.system('\\cp -a '+get.path+' /tmp/backup.conf'); data = get.data[0]; userini = False; if get.path.find('.user.ini') != -1: userini = True; public.ExecShell('chattr -i ' + get.path); if get.path.find('/www/server/cron') != -1: try: import crontab data = crontab.crontab().CheckScript(data); except: pass if get.encoding == 'ascii':get.encoding = 'utf-8'; public.writeFile(get.path,data.encode(get.encoding)); if isConf != -1: isError = public.checkWebConfig(); if isError != True: os.system('\\cp -a /tmp/backup.conf '+get.path); return public.returnMsg(False,'ERROR:<br><font style="color:red;">'+isError.replace("\n",'<br>')+'</font>'); public.serviceReload(); if userini: public.ExecShell('chattr +i ' + get.path); public.WriteLog('TYPE_FILE','FILE_SAVE_SUCCESS',(get.path,)); return public.returnMsg(True,'FILE_SAVE_SUCCESS'); except: return public.returnMsg(False,'FILE_SAVE_ERR');
def SetApacheValue(self, get): apachedefaultcontent = public.readFile(self.apachedefaultfile) apachempmcontent = public.readFile(self.apachempmfile) if not "mpm_event_module" in apachempmcontent: return public.returnMsg( False, "mpm_event_module conf not found or /www/server/apache/conf/extra/httpd-mpm.conf is empty" ) conflist = [] getdict = get.__dict__ for i in getdict.keys(): if i != "__module__" and i != "__doc__" and i != "data" and i != "args" and i != "action": getpost = {"name": i, "value": str(getdict[i])} conflist.append(getpost) for c in conflist: if c["name"] == "KeepAlive": if not re.search("on|off", c["value"]): return public.returnMsg(False, "INIT_ARGS_ERR") else: print(c["value"]) if not re.search("\d+", c["value"]): print(c["name"], c["value"]) return public.returnMsg(False, 'INIT_ARGS_ERR') rep = "%s\s+\w+" % c["name"] if re.search(rep, apachedefaultcontent): newconf = "%s %s" % (c["name"], c["value"]) apachedefaultcontent = re.sub(rep, newconf, apachedefaultcontent) elif re.search(rep, apachempmcontent): newconf = "%s\t\t\t%s" % (c["name"], c["value"]) apachempmcontent = re.sub(rep, newconf, apachempmcontent) public.writeFile(self.apachedefaultfile, apachedefaultcontent) public.writeFile(self.apachempmfile, apachempmcontent) isError = public.checkWebConfig() if (isError != True): shutil.copyfile('/tmp/_file_bk.conf', self.apachedefaultfile) shutil.copyfile('/tmp/proxyfile_bk.conf', self.apachempmfile) return public.returnMsg( False, 'ERROR: %s<br><a style="color:red;">' % public.GetMsg("CONFIG_ERROR") + isError.replace("\n", '<br>') + '</a>') public.serviceReload() return public.returnMsg(True, 'SET_SUCCESS')
def SetApacheValue(self, get): apachedefaultcontent = public.readFile(self.apachedefaultfile) apachempmcontent = public.readFile(self.apachempmfile) conflist = [] getdict = get.__dict__ for i in getdict.keys(): if i != "__module__" and i != "__doc__" and i != "data" and i != "args" and i != "action": getpost = {"name": i, "value": str(getdict[i])} conflist.append(getpost) public.writeFile("/tmp/list", str(conflist)) for c in conflist: if c["name"] == "KeepAlive": if not re.search("on|off", c["value"]): return public.returnMsg(False, '参数值错误') else: print(c["value"]) if not re.search("\d+", c["value"]): print(c["name"], c["value"]) return public.returnMsg( False, '参数值错误,请输入数字整数 %s %s' % (c["name"], c["value"])) rep = "%s\s+\w+" % c["name"] if re.search(rep, apachedefaultcontent): newconf = "%s %s" % (c["name"], c["value"]) apachedefaultcontent = re.sub(rep, newconf, apachedefaultcontent) elif re.search(rep, apachempmcontent): newconf = "%s\t\t\t%s" % (c["name"], c["value"]) apachempmcontent = re.sub(rep, newconf, apachempmcontent, count=1) public.writeFile(self.apachedefaultfile, apachedefaultcontent) public.writeFile(self.apachempmfile, apachempmcontent) isError = public.checkWebConfig() if (isError != True): shutil.copyfile('/tmp/_file_bk.conf', self.apachedefaultfile) shutil.copyfile('/tmp/proxyfile_bk.conf', self.apachempmfile) return public.returnMsg( False, 'ERROR: 配置出错<br><a style="color:red;">' + isError.replace("\n", '<br>') + '</a>') public.serviceReload() return public.returnMsg(True, '设置成功')
def SetNginxValue(self,get): ngconfcontent = public.readFile(self.nginxconf) proxycontent = public.readFile(self.proxyfile) if public.get_webserver() == 'nginx': shutil.copyfile(self.nginxconf, '/tmp/ng_file_bk.conf') shutil.copyfile(self.proxyfile, '/tmp/proxyfile_bk.conf') conflist = [] getdict = get.__dict__ for i in getdict.keys(): if i != "__module__" and i != "__doc__" and i != "data" and i != "args" and i != "action": getpost = { "name": i, "value": str(getdict[i]) } conflist.append(getpost) for c in conflist: rep = "%s\s+[^kKmMgG\;\n]+" % c["name"] if c["name"] == "worker_processes" or c["name"] == "gzip": if not re.search("auto|on|off|\d+", c["value"]): return public.returnMsg(False, 'INIT_ARGS_ERR') else: if not re.search("\d+", c["value"]): return public.returnMsg(False, 'INIT_ARGS_ERR') if re.search(rep,ngconfcontent): newconf = "%s %s" % (c["name"],c["value"]) ngconfcontent = re.sub(rep,newconf,ngconfcontent) elif re.search(rep,proxycontent): newconf = "%s %s" % (c["name"], c["value"]) proxycontent = re.sub(rep, newconf , proxycontent) public.writeFile(self.nginxconf,ngconfcontent) public.writeFile(self.proxyfile, proxycontent) isError = public.checkWebConfig() if (isError != True): shutil.copyfile('/tmp/ng_file_bk.conf', self.nginxconf) shutil.copyfile('/tmp/proxyfile_bk.conf', self.proxyfile) return public.returnMsg(False, 'ERROR: <br><a style="color:red;">' + isError.replace("\n", '<br>') + '</a>') public.serviceReload() return public.returnMsg(True, 'SET_SUCCESS')
def SaveFileBody(self,get): get.path = get.path.encode('utf-8'); if not os.path.exists(get.path): if get.path.find('.htaccess') == -1: return public.returnMsg(False,'FILE_NOT_EXISTS') try: isConf = -1 if os.path.exists('/etc/init.d/nginx') or os.path.exists('/etc/init.d/httpd'): isConf = get.path.find('nginx'); if isConf == -1: isConf = get.path.find('apache'); if isConf == -1: isConf = get.path.find('rewrite'); if isConf != -1: os.system('\\cp -a '+get.path+' /tmp/backup.conf'); data = get.data[0]; if get.path.find('/www/server/cron') != -1: try: import crontab data = crontab.crontab().CheckScript(data); except: pass if get.encoding == 'ascii':get.encoding = 'utf-8'; public.writeFile(get.path,data.encode(get.encoding)); if isConf != -1: isError = public.checkWebConfig(); if isError != True: os.system('\\cp -a /tmp/backup.conf '+get.path); return public.returnMsg(False,'ERROR:<br><font style="color:red;">'+isError.replace("\n",'<br>')+'</font>'); public.serviceReload(); public.WriteLog('TYPE_FILE','FILE_SAVE_SUCCESS',(get.path,)); return public.returnMsg(True,'FILE_SAVE_SUCCESS'); except: return public.returnMsg(False,'FILE_SAVE_ERR');
def SetRedirect(self, get): ng_file = self.setupPath + "/panel/vhost/nginx/" + get.sitename + ".conf" ap_file = self.setupPath + "/panel/vhost/apache/" + get.sitename + ".conf" p_conf = self.__read_config(self.__redirectfile) # nginx # 构建重定向配置 if int(get.type) == 1: domainstr = """ if ($host ~ '^%s'){ return %s %s%s; } """ pathstr = """ rewrite ^%s(.*) %s%s %s; """ rconf = "#REWRITE-START" tourl = get.tourl # if tourl[-1] == "/": # tourl = tourl[:-1] if get.domainorpath == "domain": domains = json.loads(get.redirectdomain) holdpath = int(get.holdpath) if holdpath == 1: for sd in domains: rconf += domainstr % (sd, get.redirecttype, tourl, "$request_uri") else: for sd in domains: rconf += domainstr % (sd, get.redirecttype, tourl, "") if get.domainorpath == "path": redirectpath = get.redirectpath if get.redirecttype == "301": redirecttype = "permanent" else: redirecttype = "redirect" if int(get.holdpath) == 1 and redirecttype == "permanent": rconf += pathstr % (redirectpath, tourl, "$1", redirecttype) elif int(get.holdpath) == 0 and redirecttype == "permanent": rconf += pathstr % (redirectpath, tourl, "", redirecttype) elif int(get.holdpath) == 1 and redirecttype == "redirect": rconf += pathstr % (redirectpath, tourl, "$1", redirecttype) elif int(get.holdpath) == 0 and redirecttype == "redirect": rconf += pathstr % (redirectpath, tourl, "", redirecttype) rconf += "#REWRITE-END" nginxrconf = rconf # 设置apache重定向 domainstr = """ <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %s{HTTP_HOST} ^%s [NC] RewriteRule ^(.*) %s%s [L,R=%s] </IfModule> """ pathstr = """ <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^%s(.*) %s%s [L,R=%s] </IfModule> """ rconf = "#REWRITE-START" if get.domainorpath == "domain": domains = json.loads(get.redirectdomain) holdpath = int(get.holdpath) if holdpath == 1: for sd in domains: rconf += domainstr % ("%", sd, tourl, "$1", get.redirecttype) else: for sd in domains: rconf += domainstr % ("%", sd, tourl, "", get.redirecttype) if get.domainorpath == "path": holdpath = int(get.holdpath) if holdpath == 1: rconf += pathstr % (get.redirectpath, tourl, "$1", get.redirecttype) else: rconf += pathstr % (get.redirectpath, tourl, "", get.redirecttype) rconf += "#REWRITE-END" apacherconf = rconf redirectname_md5 = self.__calc_md5(get.redirectname) for w in ["nginx", "apache"]: redirectfile = "%s/panel/vhost/%s/redirect/%s/%s_%s.conf" % ( self.setupPath, w, get.sitename, redirectname_md5, get.sitename) redirectdir = "%s/panel/vhost/%s/redirect/%s" % ( self.setupPath, w, get.sitename) if not os.path.exists(redirectdir): public.ExecShell("mkdir -p %s" % redirectdir) if w == "nginx": public.writeFile(redirectfile, nginxrconf) else: public.writeFile(redirectfile, apacherconf) isError = public.checkWebConfig() if (isError != True): if public.get_webserver() == "nginx": shutil.copyfile('/tmp/ng_file_bk.conf', ng_file) else: shutil.copyfile('/tmp/ap_file_bk.conf', ap_file) for i in range(len(p_conf) - 1, -1, -1): if get.sitename == p_conf[i]["sitename"] and p_conf[i][ "redirectname"]: del (p_conf[i]) return public.returnMsg( False, '%s<br><a style="color:red;">' % public.GetMsg("HAVE_ERR") + isError.replace("\n", '<br>') + '</a>') else: redirectname_md5 = self.__calc_md5(get.redirectname) redirectfile = "%s/panel/vhost/%s/redirect/%s/%s_%s.conf" for w in ["apache", "nginx"]: rf = redirectfile % (self.setupPath, w, get.sitename, redirectname_md5, get.sitename) if os.path.exists(rf): os.remove(rf)