def ClearOther(): clearPath = [ {'path':'/www/server/panel','find':'testDisk_'}, {'path':'/www/wwwlogs','find':'log'}, {'path':'/tmp','find':'panelBoot.pl'}, {'path':'/www/server/panel/install','find':'.rpm'}, {'path':'/www/server/panel/install','find':'.zip'}, {'path':'/www/server/panel/install','find':'.gz'} ] total = count = 0; print(public.GetMsg("CLEAR_RUBBISH3")) for c in clearPath: for d in os.listdir(c['path']): if d.find(c['find']) == -1: continue; filename = c['path'] + '/' + d; if os.path.isdir(filename): continue fsize = os.path.getsize(filename); print('|---['+ToSize(fsize)+'] del ' + filename), total += fsize os.remove(filename) print('\t\033[1;32m[OK]\033[0m') count += 1; public.serviceReload(); os.system('sleep 1 && /etc/init.d/bt reload > /dev/null &'); print(public.GetMsg("CLEAR_RUBBISH4",(str(count),ToSize(total)))) return total,count
def delete_dns_record(self, domain_name, domain_dns_value): root, _, acme_txt = extract_zone(domain_name) print("delete_dns_record start: ", acme_txt, domain_dns_value) record_id = self.query_recored_id(root, acme_txt) if not record_id: msg = public.GetMsg("CANT_FIND_RECORDID"), domain_name print(msg) return print("start to delete model record, id: ", record_id) randomint = random.randint(11111111111111, 99999999999999) now = datetime.datetime.utcnow() otherStyleTime = now.strftime("%Y-%m-%dT%H:%M:%SZ") paramsdata = { "Action": "DeleteDomainRecord", "Format": "json", "Version": "2015-01-09", "SignatureMethod": "HMAC-SHA1", "Timestamp": otherStyleTime, "SignatureVersion": "1.0", "SignatureNonce": str(randomint), "AccessKeyId": self.key, "RecordId": record_id, } Signature = self.sign(self.secret, paramsdata) paramsdata['Signature'] = Signature req = requests.get(url=self.url, params=paramsdata) if req.status_code != 200: sys.exit( json.dumps({ "data": public.GetMsg("DEL_RES_FAIL"), "msg": req.json() })) print("delete_dns_record end: ", acme_txt)
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 setSession(self): session['menus'] = sorted(json.loads( public.ReadFile('config/menu.json')), key=lambda x: x['sort']) session['yaer'] = datetime.now().year session['download_url'] = 'http://download.bt.cn' session["top_tips"] = public.GetMsg("TOP_TIPS") session["bt_help"] = public.GetMsg("BT_HELP") # session["manual"] = public.GetMsg("MANUAL") session["download"] = public.GetMsg("DOWNLOAD") if not 'brand' in session: session['brand'] = public.GetConfigValue('brand') session['product'] = public.GetConfigValue('product') session['rootPath'] = '/www' session['download_url'] = 'http://download.bt.cn' session['setupPath'] = session['rootPath'] + '/server' session['logsPath'] = '/www/wwwlogs' session['yaer'] = datetime.now().year if not 'menu' in session: session['menu'] = public.GetLan('menu') if not 'lan' in session: session['lan'] = public.GetLanguage() if not 'home' in session: session['home'] = 'https://console.aapanel.com' return None
def install(): if public.M('config').where("id=?",('1',)).getField('status') == 1: if os.path.exists('install.pl'): os.remove('install.pl'); session.clear() return redirect('/login') ret_login = os.path.join('/',admin_path) if admin_path == '/' or admin_path == '/bt': ret_login = '******' if request.method == method_get[0]: if not os.path.exists('install.pl'): return redirect(ret_login) data = {} data['status'] = os.path.exists('install.pl'); data['username'] = public.GetRandomString(8).lower() return render_template( 'install.html',data = data) elif request.method == method_post[0]: if not os.path.exists('install.pl'): return redirect(ret_login) get = get_input() if not hasattr(get,'bt_username'): return public.GetMsg("LOGIN_USER_EMPTY") if not get.bt_username: return public.GetMsg("LOGIN_USER_EMPTY") if not hasattr(get,'bt_password1'): return public.GetMsg("LOGIN_USER_EMPTY") if not get.bt_password1: return public.GetMsg("LOGIN_USER_EMPTY") if get.bt_password1 != get.bt_password2: return public.GetMsg("USER_PASSWORD_CHECK") public.M('users').where("id=?",(1,)).save('username,password',(get.bt_username,public.md5(get.bt_password1.strip()))) os.remove('install.pl'); public.M('config').where("id=?",('1',)).setField('status',1); data = {} data['status'] = os.path.exists('install.pl'); data['username'] = get.bt_username; return render_template( 'install.html',data = data)
def get_task_log(self,id,task_type,num=5): log_file = self.__task_path + str(id) + '.log' if not os.path.exists(log_file): data = '' if(task_type == '1'): data = {'name':public.GetMsg("DOWNLOAD_FILE"),'total':0,'used':0,'pre':0,'speed':0} return data data = public.GetNumLines(log_file,num) n = 0 if(task_type == '1'): try: data = json.loads(data) except: if n < 3: time.sleep(2); n+=1 self.get_task_log(id,task_type,num) else: data = {'name':public.GetMsg("DOWNLOAD_FILE"),'total':0,'used':0,'pre':0,'speed':0} if data == [] and n < 3: time.sleep(1); n+=1 self.get_task_log(id,task_type,num) else: if type(data) == list: return '' data = data.replace('\x08','').replace('\n','<br>') return data
def ClearMail(): rpath = '/var/spool' total = count = 0 import shutil con = ['cron', 'anacron', 'mail'] for d in os.listdir(rpath): if d in con: continue dpath = rpath + '/' + d print('|-正在清理' + dpath + ' ...') time.sleep(0.2) num = size = 0 for n in os.listdir(dpath): filename = dpath + '/' + n fsize = os.path.getsize(filename) print('|---[' + ToSize(fsize) + '] del ' + filename), size += fsize if os.path.isdir(filename): shutil.rmtree(filename) else: os.remove(filename) print('\t\033[1;32m[OK]\033[0m') num += 1 print(public.GetMsg("CLEAR_RUBBISH1", (dpath, str(num), ToSize(size)))) total += size count += num print( '=======================================================================' ) print(public.GetMsg('CLEAR_RUBBISH2', (str(count), ToSize(total)))) return total, count
def setup_idc(): try: panelPath = '/www/server/panel' filename = panelPath + '/data/o.pl' if not os.path.exists(filename): return False o = public.readFile(filename).strip() c_url = 'http://www.bt.cn/api/idc/get_idc_info_bycode?o=%s' % o idcInfo = json.loads(public.httpGet(c_url)) if not idcInfo['status']: return False pFile = panelPath + '/static/language/Simplified_Chinese/public.json' pInfo = json.loads(public.readFile(pFile)) pInfo['BRAND'] = idcInfo['msg']['name'] pInfo['PRODUCT'] = public.GetMsg("WITH_BT_CUSTOM_EDITION") pInfo['NANE'] = pInfo['BRAND'] + pInfo['PRODUCT'] public.writeFile(pFile, json.dumps(pInfo)) tFile = panelPath + '/data/title.pl' titleNew = (pInfo['BRAND'] + public.GetMsg("PANEL")).encode('utf-8') if os.path.exists(tFile): title = public.readFile(tFile).strip() if title == public.GetMsg("NAME") or title == '': public.writeFile(tFile, titleNew) else: public.writeFile(tFile, titleNew) return True except: pass
def set_token(self, get): if 'request_token' in get: return public.returnMsg(False, 'CANT_SET_API_WIFTH_API') save_path = '/www/server/panel/config/api.json' data = json.loads(public.ReadFile(save_path)) if get.t_type == '1': token = public.GetRandomString(32) data['token'] = public.md5(token) public.WriteLog('SET_API', 'REGENERATE_API_TOKEN') elif get.t_type == '2': data['open'] = not data['open'] stats = { True: public.GetMsg("TURN_ON"), False: public.GetMsg("CLOSE") } public.WriteLog('SET_API', 'API_INTERFACE', (stats[data['open']], )) token = stats[data['open']] + public.GetMsg("SUCCESS") elif get.t_type == '3': data['limit_addr'] = get.limit_addr.split('\n') public.WriteLog('SET_API', 'CHANGE_IP_LIMIT', (get.limit_addr)) token = public.GetMsg("SAVE_SUCCESS") public.WriteFile(save_path, json.dumps(data)) return public.returnMsg(True, token)
def check_authorization_status(self, authorization_url, desired_status=None, dns_names_to_delete=[]): """ 检查授权的状态,验证dns有没有添加txt解析记录 """ print("Check authorization status") time.sleep(self.ACME_AUTH_STATUS_WAIT_PERIOD) # 等待 desired_status = desired_status or ["pending", "valid"] number_of_checks = 0 while True: headers = {"User-Agent": self.User_Agent} i = 0 while i < 3: try: check_authorization_status_response = requests.get( authorization_url, timeout=self.ACME_REQUEST_TIMEOUT, headers=headers) except Exception: i += 1 else: break else: sys.exit(json.dumps({"data": public.GetMsg("ACME_ERR3")})) authorization_status = check_authorization_status_response.json( )["status"] number_of_checks = number_of_checks + 1 if number_of_checks == self.ACME_AUTH_STATUS_MAX_CHECKS: msg = public.GetMsg( "SSL_CHECK_TIPS", (number_of_checks, self.ACME_AUTH_STATUS_MAX_CHECKS, self.ACME_AUTH_STATUS_WAIT_PERIOD)) print(msg) for i in dns_names_to_delete: # 验证失败后也删除添加的dns self.dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) sys.exit( json.dumps({ "status": False, "data": public.GetMsg("CHECK_TXT_ERR5"), "msg": msg, })) if authorization_status in desired_status: break else: print( "Failed to verify model txt wait {} seconds to re-verify model, returned information:" .format(self.ACME_AUTH_STATUS_WAIT_PERIOD)) print(check_authorization_status_response.json()) public.WriteFile(os.path.join( ssl_home_path, "check_authorization_status_response"), check_authorization_status_response.text, mode="w") # 等待 time.sleep(self.ACME_AUTH_STATUS_WAIT_PERIOD) print("End of checking authorization status") return check_authorization_status_response
def SetRedirectApache(self, sitename): ap_redirectfile = "%s/panel/vhost/apache/redirect/%s/*.conf" % ( self.setupPath, sitename) ap_file = self.setupPath + "/panel/vhost/apache/" + sitename + ".conf" p_conf = public.readFile(self.__redirectfile) if public.get_webserver() == 'apache': shutil.copyfile(ap_file, '/tmp/ap_file_bk.conf') if os.path.exists(ap_file): ap_conf = public.readFile(ap_file) if p_conf == "[]": rep = "\n*%s\n+\s+IncludeOptiona[\s\w\/\.\*]+" % public.GetMsg( "NGINX_REDIRECT_REP") ap_conf = re.sub(rep, '', ap_conf) public.writeFile(ap_file, ap_conf) return if sitename in p_conf: rep = "%s(\n|.)+IncludeOptional.*\/redirect\/.*conf" % public.GetMsg( "NGINX_REDIRECT_REP1") rep1 = "combined" if not re.search(rep, ap_conf): ap_conf = ap_conf.replace( rep1, rep1 + "\n\t%s" % public.GetMsg("NGINX_REDIRECT_REP") + "\n\tIncludeOptional " + ap_redirectfile) public.writeFile(ap_file, ap_conf) else: rep = "\n*%s\n+\s+IncludeOptiona[\s\w\/\.\*]+" % public.GetMsg( "NGINX_REDIRECT_REP") ap_conf = re.sub(rep, '', ap_conf) public.writeFile(ap_file, ap_conf)
def config(pdata = None): comReturn = comm.local() if comReturn: return comReturn if request.method == method_get[0] and not pdata: import system,wxapp,config c_obj = config.config() data = system.system().GetConcifInfo() data['lan'] = public.GetLan('config') try: data['wx'] = wxapp.wxapp().get_user_info(None)['msg'] except: data['wx'] = '当前未绑定微信号' data['api'] = '' data['ipv6'] = ''; sess_out_path = 'data/session_timeout.pl' if not os.path.exists(sess_out_path): public.writeFile(sess_out_path,'86400') workers_p = 'data/workers.pl' if not os.path.exists(workers_p): public.writeFile(workers_p,'1') data['workers'] = int(public.readFile(workers_p)) s_time_tmp = public.readFile(sess_out_path) if not s_time_tmp: s_time_tmp = '0' data['session_timeout'] = int(s_time_tmp) if c_obj.get_ipv6_listen(None): data['ipv6'] = 'checked' if c_obj.get_token(None)['open']: data['api'] = 'checked' data['basic_auth'] = c_obj.get_basic_auth_stat(None) data['basic_auth']['value'] = public.GetMsg("CLOSE") if data['basic_auth']['open']: data['basic_auth']['value'] = public.GetMsg("OPEN") data['debug'] = '' if app.config['DEBUG']: data['debug'] = 'checked' data['is_local'] = '' if public.is_local(): data['is_local'] = 'checked' return render_template( 'config.html',data=data) import config defs = ('set_coll_open','get_qrcode_data','check_two_step','set_two_step_auth','get_key','get_php_session_path','set_php_session_path','get_cert_source','set_local','set_debug','get_panel_error_logs','clean_panel_error_logs','get_basic_auth_stat','set_basic_auth','get_cli_php_version','get_tmp_token','set_cli_php_version','DelOldSession', 'GetSessionCount', 'SetSessionConf', 'GetSessionConf','get_ipv6_listen','set_ipv6_status','GetApacheValue','SetApacheValue','GetNginxValue','SetNginxValue','get_token','set_token','set_admin_path','is_pro','get_php_config','get_config','SavePanelSSL','GetPanelSSL','GetPHPConf','SetPHPConf','GetPanelList','AddPanelInfo','SetPanelInfo','DelPanelInfo','ClickPanelInfo','SetPanelSSL','SetTemplates','Set502','setPassword','setUsername','setPanel','setPathInfo','setPHPMaxSize','getFpmConfig','setFpmConfig','setPHPMaxTime','syncDate','setPHPDisable','SetControl','ClosePanel','AutoUpdatePanel','SetPanelLock') return publicObject(config.config(),defs,None,pdata);
def setup_idc(): try: panelPath = '/www/server/panel' filename = panelPath + '/data/o.pl' if not os.path.exists(filename): return False o = public.readFile(filename).strip() c_url = 'http://www.bt.cn/api/idc/get_idc_info_bycode?o=%s' % o idcInfo = json.loads(public.httpGet(c_url)) if not idcInfo['status']: return False pFile = panelPath + '/config/config.json' pInfo = json.loads(public.readFile(pFile)) pInfo['brand'] = idcInfo['msg']['name'] pInfo['product'] = public.GetMsg("WITH_BT_CUSTOM_EDITION") public.writeFile(pFile, json.dumps(pInfo)) tFile = panelPath + '/data/title.pl' titleNew = (pInfo['brand'] + public.GetMsg("PANEL")).encode('utf-8') if os.path.exists(tFile): title = public.readFile(tFile).strip() if title == '宝塔Linux面板' or title == '': public.writeFile(tFile, titleNew) public.SetConfigValue('title', titleNew) else: public.writeFile(tFile, titleNew) public.SetConfigValue('title', titleNew) return True except: pass
def set_panel_pwd(password,ncli = False): import db sql = db.Sql() result = sql.table('users').where('id=?',(1,)).setField('password',public.md5(password)) username = sql.table('users').where('id=?',(1,)).getField('username') if ncli: print("|-%s: " % public.GetMsg("USER_NAME") + username); print("|-%s: " % public.GetMsg("NEW_PASS") + password); else: print(username)
def GetLibOpt(self,status,libName): optStr = ''; if status == public.GetMsg("NOT_INSTALL"): optStr = '<a class="link" href="javascript:InstallLib(\''+libName+'\');">'+public.GetMsg("INSTALL")+'</a>'; else: libConfig = public.GetMsg("配置") if(libName == 'beta'): libConfig = public.GetMsg("CLOSE_BETA") optStr = '<a class="link" href="javascript:SetLibConfig(\''+libName+'\');">'+libConfig+'</a> | <a class="link" href="javascript:UninstallLib(\''+libName+'\');">'+public.GetMsg("UNINSTALL")+'</a>'; return optStr;
def create_dns_record(self, domain_name, domain_dns_value): print("create_dns_record {} {}".format(domain_name, domain_dns_value)) # if we have been given a wildcard name, strip wildcard domain_name = domain_name.lstrip("*.") subd = "" if domain_name.count(".") != 1: # not top level domain pos = domain_name.rfind(".", 0, domain_name.rfind(".")) subd = domain_name[:pos] domain_name = domain_name[pos + 1:] if subd != "": subd = "." + subd if sys.version_info[0] == 2: url = urlparse.urljoin(self.DNSPOD_API_BASE_URL, "Record.Create") else: url = urllib.parse.urljoin(self.DNSPOD_API_BASE_URL, "Record.Create") body = { "record_type": "TXT", "domain": domain_name, "sub_domain": "_acme-challenge" + subd, "value": domain_dns_value, "record_line_id": "0", "format": "json", "login_token": self.DNSPOD_LOGIN, } create_dnspod_dns_record_response = requests.post( url, data=body, timeout=self.HTTP_TIMEOUT).json() if create_dnspod_dns_record_response["status"]["code"] != "1": if create_dnspod_dns_record_response["status"][ "code"] == "13" or create_dnspod_dns_record_response[ "status"]["code"] == "7": sys.exit( json.dumps({ "data": public.GetMsg("DNSPORD_ERR"), "msg": create_dnspod_dns_record_response })) elif create_dnspod_dns_record_response["status"][ "code"] == "10004" or create_dnspod_dns_record_response[ "status"]["code"] == "10002": sys.exit( json.dumps({ "data": public.GetMsg("DNSPORD_ERR1"), "msg": create_dnspod_dns_record_response })) else: sys.exit( json.dumps({ "data": create_dnspod_dns_record_response["status"]['message'], "msg": create_dnspod_dns_record_response })) print("create_dns_record_end")
def Get_Renew_SSL(self, get): if not os.path.isfile("/www/server/panel/vhost/crontab.json"): return {"status": False, "msg": public.GetMsg("GET_FAIL_NOT_RESULT"), "data": []} cmd_list = json.loads(public.ReadFile("/www/server/panel/vhost/crontab.json")) import panelTask CertList = self.GetCertList(get) data = [] for j in cmd_list: siteName = j['siteName'] cmd = j['cmd'] home_path = os.path.join("/www/server/panel/vhost/cert/", siteName) home_csr = os.path.join(home_path, "fullchain.pem") home_key = os.path.join(home_path, "privkey.pem") task = panelTask.bt_task() for i in task.get_task_list(): if i['name'] == siteName: siteName_task = {'status': i['status']} siteName_task['subject'] = siteName siteName_task['dns'] = [siteName, ] for item in CertList: if siteName == item['subject']: siteName_task['dns'] = item['dns'] siteName_task['notAfter'] = item['notAfter'] siteName_task['issuer'] = item['issuer'] timeArray = time.localtime(i['addtime']) siteName_task['addtime'] = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) if i['endtime']: timeArray = time.localtime(i['endtime']) siteName_task['endtime'] = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) else: siteName_task['endtime'] = i['endtime'] if i['status'] == -1: siteName_task['msg'] = public.GetMsg("RENEW_NOW") if i['status'] == 0: siteName_task['msg'] = public.GetMsg("WAIT_RENEW") if i['status'] == 1: get.keyPath =home_key get.certPath = home_csr self.SaveCert(get); siteName_task['msg'] = public.GetMsg("RENEW_SUCCESS") siteName_task['status'] = True if not os.path.isfile(home_key) and not os.path.isfile(home_csr): siteName_task['msg'] = public.GetMsg("RENEW_FAIL") siteName_task['status'] = False if os.path.isfile(os.path.join(home_path, "check_authorization_status_response")): siteName_task['msg'] = public.GetMsg("RENEW_FAIL1") siteName_task['status'] = False if os.path.isfile(os.path.join(home_path, "apply_for_cert_issuance_response")): siteName_task['msg'] = public.GetMsg("RENEW_FAIL2") siteName_task['status'] = False data.append(siteName_task) break if data: return {"status": True, "msg": public.GetMsg("SSL_GET_SUCCESS"), "data": data} else: return {"status": False, "msg": public.GetMsg("GET_FAIL_NOT_RESULT"), "data": []}
def PackagePanel(): print('========================================================') print('|-' + public.GetMsg("CLEARING_LOG") + '...'), public.M('logs').where('id!=?', (0, )).delete() print('\t\t\033[1;32m[done]\033[0m') print('|-' + public.GetMsg("CLEARING_TASK_HISTORY") + '...'), public.M('tasks').where('id!=?', (0, )).delete() print('\t\t\033[1;32m[done]\033[0m') print('|-' + public.GetMsg("CLEARING_NET_MO") + '...'), public.M('network').dbfile('system').where('id!=?', (0, )).delete() print('\t\033[1;32m[done]\033[0m') print('|-' + public.GetMsg("CLEARING_CPU_MO") + '...'), public.M('cpuio').dbfile('system').where('id!=?', (0, )).delete() print('\t\033[1;32m[done]\033[0m') print('|-' + public.GetMsg("CLEARING_DISK_MO") + '...'), public.M('diskio').dbfile('system').where('id!=?', (0, )).delete() print('\t\033[1;32m[done]\033[0m') print('|-' + public.GetMsg("CLEARING_IP") + '...'), os.system('rm -f /www/server/panel/data/iplist.txt') os.system('rm -f /www/server/panel/data/address.pl') os.system('rm -f /www/server/panel/data/*.login') os.system('rm -f /www/server/panel/data/domain.conf') os.system('rm -f /www/server/panel/data/user*') os.system('rm -f /www/server/panel/data/admin_path.pl') os.system('rm -f /root/.ssh/*') print('\t\033[1;32m[done]\033[0m') print('|-' + public.GetMsg("CLEARING_SYS_HISTORY") + '...'), command = '''cat /dev/null > /var/log/boot.log cat /dev/null > /var/log/btmp cat /dev/null > /var/log/cron cat /dev/null > /var/log/dmesg cat /dev/null > /var/log/firewalld cat /dev/null > /var/log/grubby cat /dev/null > /var/log/lastlog cat /dev/null > /var/log/mail.info cat /dev/null > /var/log/maillog cat /dev/null > /var/log/messages cat /dev/null > /var/log/secure cat /dev/null > /var/log/spooler cat /dev/null > /var/log/syslog cat /dev/null > /var/log/tallylog cat /dev/null > /var/log/wpa_supplicant.log cat /dev/null > /var/log/wtmp cat /dev/null > /var/log/yum.log history -c ''' os.system(command) print('\t\033[1;32m[done]\033[0m') public.writeFile('/www/server/panel/install.pl', "True") port = public.readFile('data/port.pl').strip() public.M('config').where("id=?", ('1', )).setField('status', 0) print('========================================================') print('\033[1;32m|-' + public.GetMsg("PANEL_TIPS") + '\033[0m') print('\033[1;41m|-' + public.GetMsg("PANEL_INIT_ADD") + ': http://{SERVERIP}:' + port + '/install\033[0m')
def backupPath(self, path, count): sql = db.Sql() startTime = time.time() if path[-1:] == '/': path = path[:-1] name = os.path.basename(path) backup_path = sql.table('config').where( "id=?", (1, )).getField('backup_path') + '/path' if not os.path.exists(backup_path): os.makedirs(backup_path) filename = backup_path + "/Path_" + name + "_" + time.strftime( '%Y%m%d_%H%M%S', time.localtime()) + '.tar.gz' os.system("cd " + os.path.dirname(path) + " && tar zcvf '" + filename + "' '" + os.path.basename(path) + "'" + self.__exclude + " > /dev/null") endDate = time.strftime('%Y/%m/%d %X', time.localtime()) if not os.path.exists(filename): log = public.GetMsg("FTP_DIR_BACK_FAIL", (path, )) print(u"★[" + endDate + "] " + log) print( u"----------------------------------------------------------------------------" ) return outTime = time.time() - startTime sql.table('backup').add( 'type,name,pid,filename,addtime,size', ('2', path, '0', filename, endDate, os.path.getsize(filename))) log = public.GetMsg("FTP_DIR_BACK_SUCCESS", (path, str(round(outTime, 2)))) public.WriteLog('TYPE_CRON', log) print(u"★[" + endDate + "] " + log) print(public.GetMsg("KEEP_PART", (count, ))) print(public.GetMsg("FTP_FILE_NAME") + filename) if self.__exclude: print(u"|---Exclusion rules: " + self.__exclude) #清理多余备份 backups = sql.table('backup').where( 'type=? and pid=? and name=?', ('2', 0, path)).field('id,filename').select() num = len(backups) - int(count) if num > 0: for backup in backups: public.ExecShell("rm -f " + backup['filename']) sql.table('backup').where('id=?', (backup['id'], )).delete() num -= 1 print( public.GetMsg("FTP_CLEAN_BACK_FILE") + backup['filename']) if num < 1: break
def Zip(self,get) : if not 'z_type' in get: get.z_type = 'rar' import panelTask task_obj = panelTask.bt_task() task_obj.create_task(public.GetMsg("COMPRESSION_FILE"),3,get.path,json.dumps({"sfile":get.sfile,"dfile":get.dfile,"z_type":get.z_type})) public.WriteLog("TYPE_FILE", 'ZIP_SUCCESS',(get.sfile,get.dfile)); return public.returnMsg(True,'ADD_COMPRESSION_TO_LINEUP')
def UnZip(self,get): import panelTask if not 'password' in get:get.password = '' task_obj = panelTask.bt_task() task_obj.create_task(public.GetMsg("DECOMPRESSION_FILE"),2,get.sfile,json.dumps({"dfile":get.dfile,"password":get.password})) public.WriteLog("TYPE_FILE", 'UNZIP_SUCCESS',(get.sfile,get.dfile)); return public.returnMsg(True,'ADD_DECOMPRESSION_TO_LINEUP')
def publicObject(toObject,defs,action=None,get = None): if 'request_token' in session and 'login' in session: if not check_csrf(): return public.ReturnJson(False,'Csrf-Token error.'),json_header if not get: get = get_input() if action: get.action = action if hasattr(get,'path'): get.path = get.path.replace('//','/').replace('\\','/'); if get.path.find('./') != -1: return public.ReturnJson(False,public.GetMsg("UNSAFE_PATH")),json_header if get.path.find('->') != -1: get.path = get.path.split('->')[0].strip(); if hasattr(get,'sfile'): get.sfile = get.sfile.replace('//','/').replace('\\','/'); if hasattr(get,'dfile'): get.dfile = get.dfile.replace('//','/').replace('\\','/'); if hasattr(toObject,'site_path_check'): if not toObject.site_path_check(get): return public.ReturnJson(False,'Excessive operation!'),json_header for key in defs: if key == get.action: fun = 'toObject.'+key+'(get)' if hasattr(get,'html') or hasattr(get,'s_module'): return eval(fun) else: return public.GetJson(eval(fun)),json_header return public.ReturnJson(False,'ARGS_ERR'),json_header
def SetSshPort(self,get): #return public.returnMsg(False,'演示服务器,禁止此操作!'); port = get.port if int(port) < 22 or int(port) > 65535: return public.returnMsg(False,'FIREWALL_SSH_PORT_ERR'); ports = ['21','25','80','443','8080','888','8888', '7800'] if port in ports: return public.returnMsg(False,''); file = '/etc/ssh/sshd_config' conf = public.readFile(file) rep = "#*Port\s+([0-9]+)\s*\n" conf = re.sub(rep, "Port "+port+"\n", conf) public.writeFile(file,conf) if self.__isFirewalld: self.__Obj.AddAcceptPort(port); public.ExecShell('setenforce 0'); public.ExecShell('sed -i "s#SELINUX=enforcing#SELINUX=disabled#" /etc/selinux/config'); public.ExecShell("systemctl restart sshd.service") elif self.__isUfw: public.ExecShell('ufw allow ' + port + '/tcp'); public.ExecShell("service ssh restart") else: public.ExecShell('iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport '+port+' -j ACCEPT') public.ExecShell("/etc/init.d/sshd restart") self.FirewallReload() public.M('firewall').where("ps=?",(public.GetMsg("SSH_SERVER"),)).setField('port',port) public.WriteLog("TYPE_FIREWALL", "FIREWALL_SSH_PORT",(port,)) return public.returnMsg(True,'EDIT_SUCCESS')
def apply_for_cert_issuance(self): print("申请颁发证书") identifiers = [] for domain_name in self.all_domain_names: identifiers.append({"type": "dns", "value": domain_name}) payload = {"identifiers": identifiers} url = self.ACME_NEW_ORDER_URL apply_for_cert_issuance_response = self.make_signed_acme_request( url=url, payload=payload) if apply_for_cert_issuance_response.status_code != 201: public.WriteFile(os.path.join(ssl_home_path, "apply_for_cert_issuance_response"), apply_for_cert_issuance_response.text, mode="w") raise ValueError( "{ssl_accept_err}: status_code={status_code} response={response}" .format( ssl_accept_err=public.GetMsg("SSL_ACCEPT_ERR"), status_code=apply_for_cert_issuance_response.status_code, response=self.log_response( apply_for_cert_issuance_response), )) apply_for_cert_issuance_response_json = apply_for_cert_issuance_response.json( ) finalize_url = apply_for_cert_issuance_response_json["finalize"] authorizations = apply_for_cert_issuance_response_json[ "authorizations"] print("申请颁发证书成功") return authorizations, finalize_url
def GetToken(self, get): rtmp = "" data = {} data['identification'] = self.en_code_rsa(get.username) data['password'] = self.en_code_rsa(get.password) data['from_panel'] = self.en_code_rsa('1') try: rtmp = public.httpPost(self.__APIURL + '/login', data) result = json.loads(rtmp) if result['success']: bind = 'data/bind.pl' if os.path.exists(bind): os.remove(bind) userinfo = result['res']['user_data'] userinfo['token'] = result['res']['access_token'] public.writeFile(self.__UPATH, json.dumps(userinfo)) session['focre_cloud'] = True return public.returnMsg(True, 'Bind successfully') else: return public.returnMsg( False, 'Invalid username or email or password! please check and try again!' ) except Exception as ex: bind = 'data/bind.pl' if os.path.exists(bind): os.remove(bind) return public.returnMsg( False, '%s<br>%s' % (public.GetMsg("CONNECT_ERR"), str(rtmp)))
def acme_register(self): if self.PRIOR_REGISTERED: payload = {"onlyReturnExisting": True} elif self.contact_email: payload = { "termsOfServiceAgreed": True, "contact": ["mailto:{0}".format(self.contact_email)], } else: payload = {"termsOfServiceAgreed": True} url = self.ACME_NEW_ACCOUNT_URL acme_register_response = self.make_signed_acme_request(url=url, payload=payload) if acme_register_response.status_code not in [201, 200, 409]: public.WriteFile(os.path.join(ssl_home_path, "apply_for_cert_issuance_response"), acme_register_response.text, mode="w") raise ValueError( "{ssl_register}: status_code={status_code} response={response}" .format( ssl_register=public.GetMsg("SSL_REGISTER_ERR"), status_code=acme_register_response.status_code, response=self.log_response(acme_register_response), )) kid = acme_register_response.headers["Location"] setattr(self, "kid", kid) print("acme_注册_成功") return acme_register_response
def SetRedirectNginx(self, get): ng_redirectfile = "%s/panel/vhost/nginx/redirect/%s/*.conf" % ( self.setupPath, get.sitename) ng_file = self.setupPath + "/panel/vhost/nginx/" + get.sitename + ".conf" p_conf = self.__read_config(self.__redirectfile) if public.get_webserver() == 'nginx': shutil.copyfile(ng_file, '/tmp/ng_file_bk.conf') if os.path.exists(ng_file): ng_conf = public.readFile(ng_file) if not p_conf: rep = "#SSL-END(\n|.)*\/redirect\/.*\*.conf;" ng_conf = re.sub(rep, '#SSL-END', ng_conf) public.writeFile(ng_file, ng_conf) return sitenamelist = [] for i in p_conf: sitenamelist.append(i["sitename"]) if get.sitename in sitenamelist: rep = "include.*\/redirect\/.*\*.conf;" if not re.search(rep, ng_conf): ng_conf = ng_conf.replace( "#SSL-END", "#SSL-END\n\t%s\n\t" % public.GetMsg("NGINX_REDIRECT_REP") + "include " + ng_redirectfile + ";") public.writeFile(ng_file, ng_conf) else: rep = "#SSL-END(\n|.)*\/redirect\/.*\*.conf;" ng_conf = re.sub(rep, '#SSL-END', ng_conf) public.writeFile(ng_file, ng_conf)
def get_sk(self): save_path = '/www/server/panel/config/api.json' if not os.path.exists(save_path): return redirect('/login') try: api_config = json.loads(public.ReadFile(save_path)) except: os.remove(save_path) return redirect('/login') if not api_config['open']: return redirect('/login') from BTPanel import get_input get = get_input() client_ip = public.GetClientIp() if not 'client_bind_token' in get: if not 'request_token' in get or not 'request_time' in get: return redirect('/login') num_key = client_ip + '_api' if not public.get_error_num(num_key,20): return public.returnJson(False,'AUTH_FAILED1') if not client_ip in api_config['limit_addr']: public.set_error_num(num_key) return public.returnJson(False,'%s[' % public.GetMsg("AUTH_FAILED1")+client_ip+']') else: num_key = client_ip + '_app' if not public.get_error_num(num_key,20): return public.returnJson(False,'AUTH_FAILED1') a_file = '/dev/shm/' + get.client_bind_token if not os.path.exists(a_file): import panelApi if not panelApi.panelApi().get_app_find(get.client_bind_token): public.set_error_num(num_key) return public.returnJson(False,'UNBOUND_DEVICE') public.writeFile(a_file,'') if not 'key' in api_config: public.set_error_num(num_key) return public.returnJson(False, 'KEY_ERR') if not 'form_data' in get: public.set_error_num(num_key) return public.returnJson(False, 'FORM_DATA_ERR') g.form_data = json.loads(public.aes_decrypt(get.form_data, api_config['key'])) get = get_input() if not 'request_token' in get or not 'request_time' in get: return redirect('/login') g.is_aes = True g.aes_key = api_config['key'] request_token = public.md5(get.request_time + api_config['token']) if get.request_token == request_token: public.set_error_num(num_key,True) return False public.set_error_num(num_key) return public.returnJson(False,'SECRET_KEY_CHECK_FALSE')
def make_signed_acme_request(self, url, payload): print("Sign acme request") headers = {"User-Agent": self.User_Agent} payload = self.stringfy_items(payload) if payload in ["GET_Z_CHALLENGE", "DOWNLOAD_Z_CERTIFICATE"]: i = 0 while i < 3: try: response = requests.get(url, timeout=self.ACME_REQUEST_TIMEOUT, headers=headers) except Exception: i += 1 else: break else: sys.exit(json.dumps({"data": public.GetMsg("ACME_ERR3")})) else: payload64 = self.calculate_safe_base64(json.dumps(payload)) protected = self.get_acme_header(url) protected64 = self.calculate_safe_base64(json.dumps(protected)) signature = self.sign_message(message="{0}.{1}".format( protected64, payload64)) # bytes signature64 = self.calculate_safe_base64(signature) # str data = json.dumps({ "protected": protected64, "payload": payload64, "signature": signature64 }) headers.update({"Content-Type": "application/jose+json"}) i = 0 while i < 3: try: response = requests.post(url, data=data.encode("utf8"), timeout=self.ACME_REQUEST_TIMEOUT, headers=headers) except Exception: i += 1 else: break else: sys.exit(json.dumps({"data": public.GetMsg("ACME_ERR3")})) return response
def create_dns_record(self, domain_name, domain_dns_value): root, _, acme_txt = extract_zone(domain_name) print("create_dns_record start: ", acme_txt, domain_dns_value) randomint = random.randint(11111111111111, 99999999999999) now = datetime.datetime.utcnow() otherStyleTime = now.strftime("%Y-%m-%dT%H:%M:%SZ") paramsdata = { "Action": "AddDomainRecord", "Format": "json", "Version": "2015-01-09", "SignatureMethod": "HMAC-SHA1", "Timestamp": otherStyleTime, "SignatureVersion": "1.0", "SignatureNonce": str(randomint), "AccessKeyId": self.key, "DomainName": root, "RR": acme_txt, "Type": "TXT", "Value": domain_dns_value, } Signature = self.sign(self.secret, paramsdata) paramsdata['Signature'] = Signature req = requests.get(url=self.url, params=paramsdata) if req.status_code != 200: if req.json()['Code'] == 'IncorrectDomainUser' or req.json( )['Code'] == 'InvalidDomainName.NoExist': sys.exit( json.dumps({ "data": public.GetMsg("ALICLOUD_ERR"), "msg": req.json() })) elif req.json( )['Code'] == 'InvalidAccessKeyId.NotFound' or req.json( )['Code'] == 'SignatureDoesNotMatch': sys.exit( json.dumps({ "data": public.GetMsg("API_SK_ERR"), "msg": req.json() })) else: sys.exit( json.dumps({ "data": req.json()['Message'], "msg": req.json() })) print("create_dns_record end")