def GetCloudList(self, get): try: import web if not hasattr(web.ctx.session, 'package'): downloadUrl = public.get_url( ) + '/install/lib/plugin/deployment/package.json' tmp = json.loads(public.httpGet(downloadUrl)) if not tmp: return public.returnMsg(False, '从云端获取失败!') jsonFile = self.__setupPath + '/list.json' public.writeFile(jsonFile, json.dumps(tmp)) downloadUrl = public.get_url( ) + '/install/lib/plugin/deployment/type.json' tmp = json.loads(public.httpGet(downloadUrl)) if not tmp: return public.returnMsg(False, '从云端获取失败!') jsonFile = self.__setupPath + '/type.json' public.writeFile(jsonFile, json.dumps(tmp)) web.ctx.session.package = True return public.returnMsg(True, '更新成功!') return public.returnMsg(True, '无需更新!') except: return public.returnMsg(False, '从云端获取失败!')
def project(htmlname): if session.get('author', 'nologin') == 'nologin': return redirect('/login') headers['authorization'] = session['author'] validate_result = json.loads( util.validate(session['author'], app.config['passport_key'])) if int(validate_result['code']) == 0: # data['method'] = 'userprojects.getlist' data['method'] = 'project.getlist' # 只在申请列表中通过jinja2渲染 data['params'] = {} r = requests.post(get_url(), headers=headers, json=data) result = json.loads(r.text) result = json.loads(result['result']) if int(result['code']) == 0: return render_template(htmlname + '.html', info=session, user=session['user'], result=result['result']) else: return render_template(htmlname + '.html', info=session, result=result['errmsg']) else: return render_template(htmlname + '.html', errmsg=validate_result['errmsg'])
def install_rar(self, get): unrar_file = '/www/server/rar/unrar' rar_file = '/www/server/rar/rar' bin_unrar = '/usr/local/bin/unrar' bin_rar = '/usr/local/bin/rar' if os.path.exists(unrar_file) and os.path.exists(bin_unrar): try: import rarfile except: os.system("pip install rarfile") return True import platform os_bit = '' if platform.machine() == 'x86_64': os_bit = '-x64' download_url = public.get_url( ) + '/src/rarlinux' + os_bit + '-5.6.1.tar.gz' tmp_file = '/tmp/bt_rar.tar.gz' os.system('wget -O ' + tmp_file + ' ' + download_url) if os.path.exists(unrar_file): os.system("rm -rf /www/server/rar") os.system("tar xvf " + tmp_file + ' -C /www/server/') if os.path.exists(tmp_file): os.remove(tmp_file) if not os.path.exists(unrar_file): return False if os.path.exists(bin_unrar): os.remove(bin_unrar) if os.path.exists(bin_rar): os.remove(bin_rar) os.system('ln -sf ' + unrar_file + ' ' + bin_unrar) os.system('ln -sf ' + rar_file + ' ' + bin_rar) os.system("pip install rarfile") #public.writeFile('data/restart.pl','True') return True
def update_py37(): pyenv='/www/server/panel/pyenv/bin/python' pyenv_exists='/www/server/panel/data/pyenv_exists.pl' if os.path.exists(pyenv) or os.path.exists(pyenv_exists): return False download_url = public.get_url() public.ExecShell("nohup curl {}/install/update_panel_en.sh|bash &>/tmp/panelUpdate.pl &".format(download_url)) public.writeFile(pyenv_exists,'True') return True
def success(): if session.get('author','nologin') == 'nologin': return redirect('/login') headers['authorization'] = session['author'] p_id = request.args.get('id') data['params'] = {'where':{'id':p_id}} data['method'] = 'apply.success' r = requests.post(get_url(),headers=headers, json=data) return r.text
def GetPackageInfo(self,name): data = self.GetDepList(None); if not data: return False; downUrl = public.get_url() + '/install/package'; for info in data: if info['name'] == name: info['download'] = info['download'].replace('{Download}',downUrl); return info; return False;
def emulation(): if session.get('author','nologin') == 'nologin': return redirect('/login') headers['authorization'] = session['author'] version = request.form.get('version') p_id = request.form.get('id') data['params'] = {'version':version,'id':p_id} data['method'] = 'apply.emulation' r = requests.post(get_url(),headers=headers,json=data) return r.text
def UpdatePro(self,get): os.system("wget -O update.sh " + public.get_url() + "/install/update6.sh && bash update.sh"); self.ReWeb(None) return True;
def RepPanel(self, get): vp = '' if public.readFile('/www/server/panel/class/common.py').find( 'checkSafe') != -1: vp = '_pro' public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update" + vp + ".sh && bash update.sh") if hasattr(web.ctx.session, 'getCloudPlugin'): del (web.ctx.session['getCloudPlugin']) return True
def GetPackageInfo(self, name): data = self.GetDepList(None) if not data: return False downUrl = public.get_url() + '/install/package' for info in data: if info['name'] == name: info['download'] = info['download'].replace( '{Download}', downUrl) return info return False
def UpdatePro(self,get): public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update6_en.sh && bash update.sh") self.ReWeb(None) return True
def GetCloudList(self,get): try: import web if not hasattr(web.ctx.session,'package'): downloadUrl = public.get_url() + '/install/lib/plugin/deployment/package.json'; tmp = json.loads(public.httpGet(downloadUrl)); if not tmp: return public.returnMsg(False,'从云端获取失败!'); jsonFile = self.__setupPath + '/list.json'; public.writeFile(jsonFile,json.dumps(tmp)); downloadUrl = public.get_url() + '/install/lib/plugin/deployment/type.json'; tmp = json.loads(public.httpGet(downloadUrl)); if not tmp: return public.returnMsg(False,'从云端获取失败!'); jsonFile = self.__setupPath + '/type.json'; public.writeFile(jsonFile,json.dumps(tmp)); web.ctx.session.package = True return public.returnMsg(True,'更新成功!'); return public.returnMsg(True,'无需更新!'); except: return public.returnMsg(False,'从云端获取失败!');
def sync_cnlist(self, get): if not get: self.get_config(None) self.get_site_config(None) rcnlist = public.httpGet(public.get_url() + '/cnlist.json') if not rcnlist: return public.returnMsg(False, '连接云端失败') cloudList = json.loads(rcnlist) cnlist = self.__get_rule('cn') n = 0 for ipd in cloudList: if ipd in cnlist: continue cnlist.append(ipd) n += 1 self.__write_rule('cn', cnlist) print('同步成功,本次共增加 ' + str(n) + ' 个IP段') if get: return public.returnMsg(True, '同步成功!')
def getCloudPlugin(self, get): if hasattr(web.ctx.session, 'getCloudPlugin') and get != None: return public.returnMsg(True, '已是最新版本!') import json if not hasattr(web.ctx.session, 'downloadUrl'): web.ctx.session.downloadUrl = 'http://download.bt.cn' # 获取列表 try: newUrl = public.get_url() if os.path.exists('plugin/beta/config.conf'): downloadUrl = newUrl + '/install/list.json' else: downloadUrl = newUrl + '/install/list_new.json' data = json.loads(public.httpGet(downloadUrl)) web.ctx.session.downloadUrl = newUrl except: downloadUrl = web.ctx.session.downloadUrl + '/install/list_new.json' data = json.loads(public.httpGet(downloadUrl)) n = i = j = 0 lists = self.GetList(None) for i in range(len(data)): for pinfo in lists: if data[i]['name'] != pinfo['name']: continue data[i]['display'] = pinfo['display'] if data[i]['default']: get.name = data[i]['name'] self.install(get) public.writeFile(self.__list, json.dumps(data)) # 获取分类 try: downloadUrl = web.ctx.session.downloadUrl + '/install/type.json' types = json.loads(public.httpGet(downloadUrl)) public.writeFile(self.__type, json.dumps(types)) except: pass self.getCloudPHPExt(get) self.GetCloudWarning(get) web.ctx.session.getCloudPlugin = True return public.returnMsg(True, 'PLUGIN_UPDATE')
def project(htmlname): if session.get('author','nologin') == 'nologin': return redirect('/login') headers['authorization'] = session['author'] validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) if int(validate_result['code']) == 0: data['method'] = 'userprojects.getlist' data['params'] = {} r = requests.post(get_url(),headers=headers,json=data) result = json.loads(r.text) result = json.loads(result['result']) if int(result['code']) == 0: return render_template(htmlname+'.html',info=session,user=session['user'],result=result['result']) else: return render_template(htmlname+'.html',info=session,result=result['errmsg']) else: return render_template(htmlname+'.html',errmsg=validate_result['errmsg'])
def sync_rule(self): ''' @name 从云端同步规则 @author hwliang<2020-08-05> @return void ''' try: dep_path = '/www/server/panel/class/safe_warning' local_version_file = self.__path + '/version.pl' last_sync_time = local_version_file = self.__path + '/last_sync.pl' if os.path.exists(dep_path): if os.path.exists(last_sync_time): if int(public.readFile(last_sync_time)) > time.time(): return else: if os.path.exists(local_version_file): os.remove(local_version_file) download_url = public.get_url() version_url = download_url + '/install/warning/version.txt' cloud_version = public.httpGet(version_url) if cloud_version: cloud_version = cloud_version.strip() local_version = public.readFile(local_version_file) if local_version: if cloud_version == local_version: return tmp_file = '/tmp/bt_safe_warning.zip' public.ExecShell('wget -O {} {} -T 5'.format(tmp_file,download_url + '/install/warning/safe_warning_en.zip')) if not os.path.exists(tmp_file): return if os.path.getsize(tmp_file) < 2129: os.remove(tmp_file) return if not os.path.exists(dep_path): os.makedirs(dep_path,384) public.ExecShell("unzip -o {} -d {}/ >/dev/null".format(tmp_file,dep_path)) public.writeFile(local_version_file,cloud_version) public.writeFile(last_sync_time,str(int(time.time() + 7200))) if os.path.exists(tmp_file): os.remove(tmp_file) public.ExecShell("chmod -R 600 {}".format(dep_path)) except: pass
def update_to6(): print("====================================================") print("正在升级插件...") print("====================================================") download_address = public.get_url() exlodes = ['gitlab','pm2','mongodb','deployment_jd','logs','docker','beta','btyw'] for pname in os.listdir('plugin/'): if not os.path.isdir('plugin/' + pname): continue if pname in exlodes: continue print("|-正在升级【%s】..." % pname), download_url = download_address + '/install/plugin/' + pname + '/install.sh'; to_file = '/tmp/%s.sh' % pname public.downloadFile(download_url,to_file); os.system('/bin/bash ' + to_file + ' install &> /tmp/plugin_update.log 2>&1'); print(" \033[32m[成功]\033[0m") print("====================================================") print("\033[32m所有插件已成功升级到6.0兼容!\033[0m") print("====================================================")
def update_to6(): print("====================================================") print(public.GetMsg("PLUG_UPDATEING")) print("====================================================") download_address = public.get_url() exlodes = ['gitlab','pm2','mongodb','deployment_jd','logs','docker','beta','btyw'] for pname in os.listdir('plugin/'): if not os.path.isdir('plugin/' + pname): continue if pname in exlodes: continue print("|-upgrading【%s】..." % pname), download_url = download_address + '/install/plugin/' + pname + '/install.sh'; to_file = '/tmp/%s.sh' % pname public.downloadFile(download_url,to_file); os.system('/bin/bash ' + to_file + ' install &> /tmp/plugin_update.log 2>&1'); print(" \033[32m[success]\033[0m") print("====================================================") print("\033[32m"+public.GetMsg("PLUG_UPDATE_TO_6")+"\033[0m") print("====================================================")
def getCloudPlugin(self,get): if hasattr(web.ctx.session,'getCloudPlugin') and get != None: return public.returnMsg(True,'您的插件列表已经是最新版本-1!'); import json if not hasattr(web.ctx.session,'downloadUrl'): web.ctx.session.downloadUrl = 'http://download.bt.cn'; #获取列表 try: newUrl = public.get_url(); if os.path.exists('plugin/beta/config.conf'): downloadUrl = newUrl + '/install/list.json' else: downloadUrl = newUrl + '/install/listTest.json' data = json.loads(public.httpGet(downloadUrl)) web.ctx.session.downloadUrl = newUrl; except: downloadUrl = web.ctx.session.downloadUrl + '/install/listTest.json' data = json.loads(public.httpGet(downloadUrl)) n = i = j = 0; lists = self.GetList(None); for i in range(len(data)): for pinfo in lists: if data[i]['name'] != pinfo['name']: continue; data[i]['display'] = pinfo['display']; if data[i]['default']: get.name = data[i]['name']; self.install(get); public.writeFile(self.__list,json.dumps(data)); #获取分类 try: downloadUrl = web.ctx.session.downloadUrl + '/install/type.json' types = json.loads(public.httpGet(downloadUrl)) public.writeFile(self.__type,json.dumps(types)); except: pass; self.getCloudPHPExt(get); self.GetCloudWarning(get); web.ctx.session.getCloudPlugin = True; return public.returnMsg(True,'PLUGIN_UPDATE');
def project_apply(): if session.get('author',"nologin") == "nologin": return redirect('/login') session['pre_click'] = 'deploy' headers['authorization'] = session['author'] validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) if int(validate_result['code']) == 0: data['method'] = 'git.getlist' data['params'] = {} r = requests.post(get_url(),headers=headers,json=data) result = json.loads(r.text) result = json.loads(result['result']) if int(result['code']) == 0: return render_template('apply.html',info=session,result=result['result']) else: return render_template('apply.html',errmsg=result['errmsg']) else: return render_template('apply.html',errmsg=validate_result['errmsg'])
def Install_uninstall(self, args): # 安装卸载pgsql args = self.processing_parameter(args) # 处理前端传过来的参数 if 'pgsql_unInstall' not in args: args.pgsql_unInstall = 0 if 'get_pgsql_version' not in args: args.get_pgsql_version = 0 if 'get_pgsql_install_info' not in args: args.get_pgsql_install_info = 0 if 'get_pgsql_install_log' not in args: args.get_pgsql_install_log = 0 if 'del_bak' not in args: args.del_bak = 0 if int(args.get_pgsql_install_log) != 0: result = public.ExecShell('''tail /tmp/pgsql_install.log ''')[0] # 返回数据到前端 return {'data': result, "status": True} if int(args.get_pgsql_version) != 0 and int(args.get_pgsql_install_info) != 0: bt_down_url = public.get_url() pgsql_install_info = [ {"pgsql_version": "postgresql 14.2", "down_url": bt_down_url + "/src/postgresql-14.2.tar.gz"}, {"pgsql_version": "postgresql 13.6", "down_url": bt_down_url + "/src/postgresql-13.6.tar.gz"}, {"pgsql_version": "postgresql 12.10", "down_url": bt_down_url + "/src/postgresql-12.10.tar.gz"}, {"pgsql_version": "postgresql 11.15", "down_url": bt_down_url + "/src/postgresql-11.15.tar.gz"}, {"pgsql_version": "postgresql 10.5", "down_url": bt_down_url + "/src/postgresql-10.5.tar.gz"}, {"pgsql_version": "postgresql 9.6", "down_url": bt_down_url + "/src/postgresql-9.6.6.tar.gz"} ] pgsql_version = public.ExecShell('''/www/server/pgsql/bin/psql --version''')[0] if pgsql_version.strip(): is_install = "已经安装" else: is_install = "未安装" return {'data': {"pgsql_install_info": pgsql_install_info, "pgsql_version": pgsql_version, "is_install": is_install}, "status": True} if int(args.pgsql_unInstall) != 0: if int(args.del_bak) == 1: public.ExecShell("rm -rf {}".format(self.db_back_dir)) public.ExecShell('''netstat -luntp|grep postgres|awk '{print $NF}'|awk -F/ '{print "kill -9 "$1}'|sh ''') public.ExecShell("rm -rf /www/server/pgsql && rm -rf /usr/local/pgsql && rm -rf {}".format(self.dbuser_info_path)) return {'data': "pgsql已经卸载成功", "status": True} pgsql_version = args.pgsql_version.split("/")[-1] down_url = args.pgsql_version if os.path.isdir("/www/server/pgsql/bin"): return {'data': "pgsql已经安装", "status": True} public.ExecShell(''' nohup sh /www/server/panel/plugin/pgsql_manager/pgsql_install.sh "{}" "{}" > /tmp/pgsql_install.log 2>&1 & '''.format(pgsql_version, down_url)) # 返回数据到前端 return {'data': "{} 正在安装,请稍等!".format(pgsql_version), "status": True}
def testhistory(): if session.get('author','nologin') == 'nologin': return redirect('/login') headers['authorization'] = session['author'] validate_result = json.loads(util.validate(session['author'], app.config['passport_key'])) project_id = request.args.get('id') project_id = urllib.unquote(project_id).encode('iso-8859-1') project_id = int(project_id) if int(validate_result['code']) == 0: data['method'] ="project_test.getlist" data['params'] = {'where':{'project_id':project_id}} r = requests.post(public.get_url(),headers=headers,json=data) result = json.loads(r.text) result = json.loads(result['result']) if int(result['code']) == 0: return render_template('test_history.html',info=session,result=result['result']) else: return render_template('test_history.html',errmsg=validate_result['errmsg']) else: return render_template('test_history.html',errmsg=validate_result['errmsg'])
def getCloudPlugin(self,get): if hasattr(web.ctx.session,'getCloudPlugin') and get != None: return public.returnMsg(True,'您的插件列表已经是最新版本-1!'); import json if not hasattr(web.ctx.session,'downloadUrl'): web.ctx.session.downloadUrl = 'http://download.bt.cn'; #获取列表 try: newUrl = public.get_url(); downloadUrl = newUrl + '/install/list.json' data = json.loads(public.httpGet(downloadUrl)) web.ctx.session.downloadUrl = newUrl; except: downloadUrl = web.ctx.session.downloadUrl + '/install/list.json' data = json.loads(public.httpGet(downloadUrl)) n = i = j = 0; lists = self.GetList(None); for i in range(len(data)): for pinfo in lists: if data[i]['name'] != pinfo['name']: continue; data[i]['display'] = pinfo['display']; if data[i]['default']: get.name = data[i]['name']; self.install(get); public.writeFile(self.__list,json.dumps(data)); #获取分类 try: downloadUrl = web.ctx.session.downloadUrl + '/install/type.json' types = json.loads(public.httpGet(downloadUrl)) public.writeFile(self.__type,json.dumps(types)); except: pass; self.getCloudPHPExt(get); web.ctx.session.getCloudPlugin = True; return public.returnMsg(True,'PLUGIN_UPDATE');
def ServiceAdmin(self, get=None): #服务管理 if get.name == 'mysqld': public.CheckMyCnf() self.__check_mysql_path() if get.name.find('webserver') != -1: get.name = public.get_webserver() if get.name == 'phpmyadmin': import ajax get.status = 'True' ajax.ajax().setPHPMyAdmin(get) return public.returnMsg(True, 'SYS_EXEC_SUCCESS') if get.name == 'openlitespeed': if get.type == 'stop': public.ExecShell( 'rm -f /tmp/lshttpd/*.sock* && /usr/local/lsws/bin/lswsctrl stop' ) elif get.type == 'start': public.ExecShell( 'rm -f /tmp/lshttpd/*.sock* && /usr/local/lsws/bin/lswsctrl start' ) else: public.ExecShell( 'rm -f /tmp/lshttpd/*.sock* && /usr/local/lsws/bin/lswsctrl restart' ) return public.returnMsg(True, 'SYS_EXEC_SUCCESS') #检查httpd配置文件 if get.name == 'apache' or get.name == 'httpd': get.name = 'httpd' if not os.path.exists(self.setupPath + '/apache/bin/apachectl'): return public.returnMsg(True, 'SYS_NOT_INSTALL_APACHE') vhostPath = self.setupPath + '/panel/vhost/apache' if not os.path.exists(vhostPath): public.ExecShell('mkdir ' + vhostPath) public.ExecShell('/etc/init.d/httpd start') if get.type == 'start': public.ExecShell('/etc/init.d/httpd stop') self.kill_port() result = public.ExecShell('ulimit -n 8192 ; ' + self.setupPath + '/apache/bin/apachectl -t') if result[1].find('Syntax OK') == -1: public.WriteLog("TYPE_SOFT", 'SYS_EXEC_ERR', (str(result), )) return public.returnMsg(False, 'SYS_CONF_APACHE_ERR', (result[1].replace("\n", '<br>'), )) if get.type == 'restart': public.ExecShell('pkill -9 httpd') public.ExecShell('/etc/init.d/httpd start') time.sleep(0.5) #检查nginx配置文件 elif get.name == 'nginx': vhostPath = self.setupPath + '/panel/vhost/rewrite' if not os.path.exists(vhostPath): public.ExecShell('mkdir ' + vhostPath) vhostPath = self.setupPath + '/panel/vhost/nginx' if not os.path.exists(vhostPath): public.ExecShell('mkdir ' + vhostPath) public.ExecShell('/etc/init.d/nginx start') result = public.ExecShell('ulimit -n 8192 ; nginx -t -c ' + self.setupPath + '/nginx/conf/nginx.conf') if result[1].find('perserver') != -1: limit = self.setupPath + '/nginx/conf/nginx.conf' nginxConf = public.readFile(limit) limitConf = "limit_conn_zone $binary_remote_addr zone=perip:10m;\n\t\tlimit_conn_zone $server_name zone=perserver:10m;" nginxConf = nginxConf.replace( "#limit_conn_zone $binary_remote_addr zone=perip:10m;", limitConf) public.writeFile(limit, nginxConf) public.ExecShell('/etc/init.d/nginx start') return public.returnMsg(True, 'SYS_CONF_NGINX_REP') if result[1].find('proxy') != -1: import panelSite panelSite.panelSite().CheckProxy(get) public.ExecShell('/etc/init.d/nginx start') return public.returnMsg(True, 'SYS_CONF_NGINX_REP') #return result if result[1].find('successful') == -1: public.WriteLog("TYPE_SOFT", 'SYS_EXEC_ERR', (str(result), )) return public.returnMsg(False, 'SYS_CONF_NGINX_ERR', (result[1].replace("\n", '<br>'), )) if get.type == 'start': self.kill_port() time.sleep(0.5) if get.name == 'redis': redis_init = '/etc/init.d/redis' if os.path.exists(redis_init): init_body = public.ReadFile(redis_init) if init_body.find('pkill -9 redis') == -1: public.ExecShell("wget -O " + redis_init + " " + public.get_url() + '/init/redis.init') public.ExecShell("chmod +x " + redis_init) #执行 execStr = "/etc/init.d/" + get.name + " " + get.type if execStr == '/etc/init.d/pure-ftpd reload': execStr = self.setupPath + '/pure-ftpd/bin/pure-pw mkdb ' + self.setupPath + '/pure-ftpd/etc/pureftpd.pdb' if execStr == '/etc/init.d/pure-ftpd start': public.ExecShell('pkill -9 pure-ftpd') if execStr == '/etc/init.d/tomcat reload': execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start' if execStr == '/etc/init.d/tomcat restart': execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start' if get.name != 'mysqld': result = public.ExecShell(execStr) else: public.ExecShell(execStr) result = [] result.append('') result.append('') if result[1].find('nginx.pid') != -1: public.ExecShell('pkill -9 nginx && sleep 1') public.ExecShell('/etc/init.d/nginx start') if get.type != 'test': public.WriteLog("TYPE_SOFT", 'SYS_EXEC_SUCCESS', (execStr, )) if len(result[1] ) > 1 and get.name != 'pure-ftpd' and get.name != 'redis': return public.returnMsg( False, '<p>Warning message: <p>' + result[1].replace('\n', '<br>')) return public.returnMsg(True, 'SYS_EXEC_SUCCESS')
def UpdatePanel(self,get): #return public.returnMsg(False,'演示服务器,禁止此操作!'); try: if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK'); import web,json if int(web.ctx.session.config['status']) == 0: public.httpGet(web.ctx.session.home+'/Api/SetupCount?type=Linux'); public.M('config').where("id=?",('1',)).setField('status',1); #取回远程版本信息 if hasattr(web.ctx.session,'updateInfo') == True and hasattr(get,'check') == False: updateInfo = web.ctx.session.updateInfo; else: login_temp = 'data/login.temp'; if os.path.exists(login_temp): logs = public.readFile(login_temp) os.remove(login_temp); else: logs = ''; import psutil,panelPlugin,system; mem = psutil.virtual_memory(); mplugin = panelPlugin.panelPlugin(); mplugin.ROWS = 10000; panelsys = system.system(); data = {} data['sites'] = str(public.M('sites').count()); data['ftps'] = str(public.M('ftps').count()); data['databases'] = str(public.M('databases').count()); data['system'] = panelsys.GetSystemVersion() + '|' + str(mem.total / 1024 / 1024) + 'MB|' + public.getCpuType() + '*' + str(psutil.cpu_count()) + '|' + public.get_webserver() + '|' + web.ctx.session.version; data['system'] += '||'+self.GetInstalleds(mplugin.getPluginList(None)); data['logs'] = logs data['oem'] = '' data['intrusion'] = self.get_ssh_intrusion(); msg = public.getMsg('PANEL_UPDATE_MSG'); sUrl = web.ctx.session.home + '/Api/updateLinux'; betaIs = 'data/beta.pl'; betaStr = public.readFile(betaIs); if betaStr: if betaStr.strip() != 'False': sUrl = web.ctx.session.home + '/Api/updateLinuxBeta'; msg = public.getMsg('PANEL_UPDATE_MSG_TEST'); betaIs = 'plugin/beta/config.conf'; betaStr = public.readFile(betaIs); if betaStr: if betaStr.strip() != 'False': sUrl = web.ctx.session.home + '/Api/updateLinuxBeta'; msg = public.getMsg('PANEL_UPDATE_MSG_TEST'); updateInfo = json.loads(public.httpPost(sUrl,data)); if not updateInfo: return public.returnMsg(False,"CONNECT_ERR"); updateInfo['msg'] = msg; web.ctx.session.updateInfo = updateInfo; #检查是否需要升级 if updateInfo['version'] == web.ctx.session.version: try: return public.returnMsg(False,updateInfo['msg']); except: return public.returnMsg(False,'PANEL_UPDATE_ERR_NEW'); #是否执行升级程序 if(updateInfo['force'] == True or hasattr(get,'toUpdate') == True or os.path.exists('data/autoUpdate.pl') == True): setupPath = web.ctx.session.setupPath; uptype = 'update'; betaIs = 'plugin/beta/config.conf'; betaStr = public.readFile(betaIs); if betaStr: if betaStr.strip() != 'False': uptype = 'updateTest'; betaIs = 'data/beta.pl'; betaStr = public.readFile(betaIs); if betaStr: if betaStr.strip() != 'False': uptype = 'updateTest'; httpUrl = public.get_url(); if httpUrl: updateInfo['downUrl'] = httpUrl + '/install/' + uptype + '/LinuxPanel-' + updateInfo['version'] + '.zip'; public.downloadFile(updateInfo['downUrl'],'panel.zip'); if os.path.getsize('panel.zip') < 1048576: return public.returnMsg(False,"PANEL_UPDATE_ERR_DOWN"); public.ExecShell('unzip -o panel.zip -d ' + setupPath + '/'); import compileall if os.path.exists(setupPath + '/panel/main.py'): public.ExecShell('rm -f ' + setupPath + '/panel/*.pyc'); if os.path.exists(setupPath + '/panel/class/common.py'): public.ExecShell('rm -f ' + setupPath + '/panel/class/*.pyc'); compileall.compile_dir(setupPath + '/panel'); compileall.compile_dir(setupPath + '/panel/class'); public.ExecShell('rm -f panel.zip'); web.ctx.session.version = updateInfo['version'] return public.returnMsg(True,'PANEL_UPDATE',(updateInfo['version'],)); #输出新版本信息 data = { 'status' : True, 'version': updateInfo['version'], 'updateMsg' : updateInfo['updateMsg'] }; public.ExecShell('rm -rf /www/server/phpinfo/*'); return data; except Exception,ex: return public.returnMsg(False,"CONNECT_ERR");
def SetupPackage(self,get): name = get.dname site_name = get.site_name; php_version = get.php_version; #取基础信息 find = public.M('sites').where('name=?',(site_name,)).field('id,path').find(); path = find['path']; #获取包信息 pinfo = self.GetPackageInfo(name); if not pinfo: return public.returnMsg(False,'指定软件包不存在!'); #检查本地包 self.WriteLogs(json.dumps({'name':'检查软件包','total':0,'used':0,'pre':0,'speed':0})); packageZip = self.__setupPath + '/package/' + name + '.zip'; isDownload = False; if os.path.exists(packageZip): md5str = self.GetFileMd5(packageZip); if md5str != pinfo['md5']: isDownload = True; else: isDownload = True; #下载文件 if isDownload: self.WriteLogs(json.dumps({'name':'下载文件','total':0,'used':0,'pre':0,'speed':0})); self.DownloadFile(pinfo['download'], packageZip); if not os.path.exists(packageZip): return public.returnMsg(False,'文件下载失败!'); os.system('unzip -o '+packageZip+' -d ' + path + '/'); #设置权限 self.WriteLogs(json.dumps({'name':'设置权限','total':0,'used':0,'pre':0,'speed':0})); os.system('chmod -R 755 ' + path); os.system('chown -R www.www ' + path); if pinfo['chmod'] != "": access = pinfo['chmod'].split(',') for chm in access: tmp = chm.split('|'); if len(tmp) != 2: continue; os.system('chmod -R ' + tmp[0] + ' ' + path + '/' + tmp[1]); #安装PHP扩展 self.WriteLogs(json.dumps({'name':'安装必要的PHP扩展','total':0,'used':0,'pre':0,'speed':0})); if pinfo['ext'] != '': exts = pinfo['ext'].split(','); import files mfile = files.files(); for ext in exts: if ext == 'pathinfo': import config con = config.config(); get.version = php_version; get.type = 'on'; con.setPathInfo(get); else: get.name = ext get.version = php_version get.type = '1'; mfile.InstallSoft(get); #执行额外shell进行依赖安装 self.WriteLogs(json.dumps({'name':'执行额外SHELL','total':0,'used':0,'pre':0,'speed':0})); if os.path.exists(path+'/install.sh'): os.system('cd '+path+' && bash ' + 'install.sh'); os.system('rm -f ' + path+'/install.sh') #是否执行Composer if os.path.exists(path + '/composer.json'): self.WriteLogs(json.dumps({'name':'执行Composer','total':0,'used':0,'pre':0,'speed':0})); if not os.path.exists(path + '/composer.lock'): execPHP = '/www/server/php/' + php_version +'/bin/php'; if execPHP: if public.get_url().find('125.88'): os.system('cd ' +path+' && '+execPHP+' /usr/bin/composer config repo.packagist composer https://packagist.phpcomposer.com'); import panelSite; phpini = '/www/server/php/' + php_version + '/etc/php.ini' phpiniConf = public.readFile(phpini); phpiniConf = phpiniConf.replace('proc_open,proc_get_status,',''); public.writeFile(phpini,phpiniConf); os.system('nohup cd '+path+' && '+execPHP+' /usr/bin/composer install -vvv > /tmp/composer.log 2>&1 &'); #写伪静态 self.WriteLogs(json.dumps({'name':'设置伪静态','total':0,'used':0,'pre':0,'speed':0})); swfile = path + '/nginx.rewrite'; if os.path.exists(swfile): rewriteConf = public.readFile(swfile); dwfile = self.__panelPath + '/vhost/rewrite/' + site_name + '.conf'; public.writeFile(dwfile,rewriteConf); #设置运行目录 self.WriteLogs(json.dumps({'name':'设置运行目录','total':0,'used':0,'pre':0,'speed':0})); if pinfo['run'] != '/': import panelSite; siteObj = panelSite.panelSite(); mobj = obj(); mobj.id = find['id']; mobj.runPath = pinfo['run']; siteObj.SetSiteRunPath(mobj); #导入数据 self.WriteLogs(json.dumps({'name':'导入数据库','total':0,'used':0,'pre':0,'speed':0})); if os.path.exists(path+'/import.sql'): databaseInfo = public.M('databases').where('pid=?',(find['id'],)).field('username,password').find(); if databaseInfo: os.system('/www/server/mysql/bin/mysql -u' + databaseInfo['username'] + ' -p' + databaseInfo['password'] + ' ' + databaseInfo['username'] + ' < ' + path + '/import.sql'); os.system('rm -f ' + path + '/import.sql'); siteConfigFile = path + '/' + pinfo['config']; if os.path.exists(siteConfigFile): siteConfig = public.readFile(siteConfigFile) siteConfig = siteConfig.replace('BT_DB_USERNAME',databaseInfo['username']) siteConfig = siteConfig.replace('BT_DB_PASSWORD',databaseInfo['password']) siteConfig = siteConfig.replace('BT_DB_NAME',databaseInfo['username']) public.writeFile(siteConfigFile,siteConfig) public.serviceReload(); self.depTotal(name); self.WriteLogs(json.dumps({'name':'准备部署','total':0,'used':0,'pre':0,'speed':0})); return public.returnMsg(True,pinfo);
def download_icon(self, name, iconFile): srcIcon = self.__install_path + '/' + name + '/icon.png' public.ExecShell('wget -O ' + iconFile + ' ' + public.get_url() + '/install/lib/plugin/' + name + '/icon.png &')
def RepPanel(self, get): public.writeFile('data/js_random.pl', '1') public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update6_en.sh && bash update.sh") self.ReWeb(None) return True
def UpdatePro(self, get): public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update_pro.sh && bash update.sh pro") if hasattr(web.ctx.session, 'getCloudPlugin'): del (web.ctx.session['getCloudPlugin']) return True
def UpdatePanel(self,get): try: if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK'); import json if int(session['config']['status']) == 0: public.HttpGet(public.GetConfigValue('home')+'/Api/SetupCount?type=Linux'); public.M('config').where("id=?",('1',)).setField('status',1); #取回远程版本信息 if 'updateInfo' in session and hasattr(get,'check') == False: updateInfo = session['updateInfo']; else: login_temp = 'data/login.temp'; if os.path.exists(login_temp): logs = public.readFile(login_temp) os.remove(login_temp); else: logs = ''; import psutil,panelPlugin,system; mem = psutil.virtual_memory(); mplugin = panelPlugin.panelPlugin(); mplugin.ROWS = 10000; panelsys = system.system(); data = {} data['sites'] = str(public.M('sites').count()); data['ftps'] = str(public.M('ftps').count()); data['databases'] = str(public.M('databases').count()); data['system'] = panelsys.GetSystemVersion() + '|' + str(mem.total / 1024 / 1024) + 'MB|' + public.getCpuType() + '*' + str(psutil.cpu_count()) + '|' + public.get_webserver() + '|' +session['version']; data['system'] += '||'+self.GetInstalleds(mplugin.getPluginList(None)); data['logs'] = logs data['oem'] = '' data['intrusion'] = 0; msg = public.getMsg('PANEL_UPDATE_MSG'); sUrl = public.GetConfigValue('home') + '/api/panel/updateLinux'; updateInfo = json.loads(public.httpPost(sUrl,data)); if not updateInfo: return public.returnMsg(False,"CONNECT_ERR"); updateInfo['msg'] = msg; session['updateInfo'] = updateInfo; #检查是否需要升级 if updateInfo['version'] ==session['version']: try: return public.returnMsg(False,updateInfo['msg']); except: return public.returnMsg(False,'PANEL_UPDATE_ERR_NEW'); #是否执行升级程序 if(updateInfo['force'] == True or hasattr(get,'toUpdate') == True or os.path.exists('data/autoUpdate.pl') == True): setupPath = public.GetConfigValue('setup_path'); uptype = 'update'; httpUrl = public.get_url(); if httpUrl: updateInfo['downUrl'] = httpUrl + '/install/' + uptype + '/LinuxPanel-' + updateInfo['version'] + '.zip'; public.downloadFile(updateInfo['downUrl'],'panel.zip'); if os.path.getsize('panel.zip') < 1048576: return public.returnMsg(False,"PANEL_UPDATE_ERR_DOWN"); public.ExecShell('unzip -o panel.zip -d ' + setupPath + '/'); import compileall if os.path.exists('/www/server/panel/runserver.py'): public.ExecShell('rm -f /www/server/panel/*.pyc'); if os.path.exists('/www/server/panel/class/common.py'): public.ExecShell('rm -f /www/server/panel/class/*.pyc'); if os.path.exists('panel.zip'):os.remove("panel.zip") session['version'] = updateInfo['version'] if 'getCloudPlugin' in session: del(session['getCloudPlugin']); return public.returnMsg(True,'PANEL_UPDATE',(updateInfo['version'],)); #输出新版本信息 data = { 'status' : True, 'version': updateInfo['version'], 'updateMsg' : updateInfo['updateMsg'] }; public.ExecShell('rm -rf /www/server/phpinfo/*'); return data; except Exception as ex: return public.returnMsg(False,"CONNECT_ERR");
def RepPanel(self, get): os.system("wget -O update.sh " + public.get_url() + "/install/update6_en.sh && bash update.sh") self.ReWeb(None) return True
def SetupPackage(self,get): name = get.dname site_name = get.site_name; php_version = get.php_version; #取基础信息 find = public.M('sites').where('name=?',(site_name,)).field('id,path,name').find(); path = find['path']; if path.replace('//','/') == '/': return public.returnMsg(False,'Dangerous website root directory!') #获取包信息 pinfo = self.GetPackageInfo(name); id = pinfo['id'] if not pinfo: return public.returnMsg(False,'The specified package does not exist.!'); #检查本地包 self.WriteLogs(json.dumps({'name':'Verifying package...','total':0,'used':0,'pre':0,'speed':0})); pack_path = self.__panelPath + '/package' if not os.path.exists(pack_path): os.makedirs(pack_path,384) packageZip = pack_path + '/'+ name + '.zip'; isDownload = False; if os.path.exists(packageZip): md5str = self.GetFileMd5(packageZip); if md5str != pinfo['versions'][0]['md5']: isDownload = True; else: isDownload = True; #下载文件 if isDownload: self.WriteLogs(json.dumps({'name':'Downloading file ...','total':0,'used':0,'pre':0,'speed':0})); if pinfo['versions'][0]['download']: self.DownloadFile('http://www.bt.cn/api/Pluginother/get_file?fname=' + pinfo['versions'][0]['download'], packageZip); if not os.path.exists(packageZip): return public.returnMsg(False,'File download failed!' + packageZip); pinfo = self.set_temp_file(packageZip,path) if not pinfo: return public.returnMsg(False,'Cannot find [aaPanel Auto Deployment Configuration File] in the installation package') #设置权限 self.WriteLogs(json.dumps({'name':'Setting permissions','total':0,'used':0,'pre':0,'speed':0})); os.system('chmod -R 755 ' + path); os.system('chown -R www.www ' + path); if pinfo['chmod'] != "": for chm in pinfo['chmod']: os.system('chmod -R ' + str(chm['mode']) + ' ' + (path + '/' + chm['path']).replace('//','/')); #安装PHP扩展 self.WriteLogs(json.dumps({'name':'Install the necessary PHP extensions','total':0,'used':0,'pre':0,'speed':0})); import files mfile = files.files(); for ext in pinfo['php_ext']: if ext == 'pathinfo': import config con = config.config(); get.version = php_version; get.type = 'on'; con.setPathInfo(get); else: get.name = ext get.version = php_version get.type = '1'; mfile.InstallSoft(get); #解禁PHP函数 if 'enable_functions' in pinfo: try: php_f = public.GetConfigValue('setup_path') + '/php/' + php_version + '/etc/php.ini' php_c = public.readFile(php_f) rep = "disable_functions\s*=\s{0,1}(.*)\n" tmp = re.search(rep,phpini).groups(); disable_functions = tmp[0].split(','); for fun in pinfo['enable_functions']: fun = fun.strip() if fun in disable_functions: disable_functions.remove(fun) disable_functions = ','.join(disable_functions) php_c = re.sub(rep, 'disable_functions = ' + disable_functions + "\n", php_c); public.writeFile(php_f,php_c) public.phpReload(php_version) except:pass #执行额外shell进行依赖安装 self.WriteLogs(json.dumps({'name':'Execute extra SHELL','total':0,'used':0,'pre':0,'speed':0})); if os.path.exists(path+'/install.sh'): os.system('cd '+path+' && bash ' + 'install.sh ' + find['name']); os.system('rm -f ' + path+'/install.sh') #是否执行Composer if os.path.exists(path + '/composer.json'): self.WriteLogs(json.dumps({'name':'Execute Composer','total':0,'used':0,'pre':0,'speed':0})); if not os.path.exists(path + '/composer.lock'): execPHP = '/www/server/php/' + php_version +'/bin/php'; if execPHP: if public.get_url().find('125.88'): os.system('cd ' +path+' && '+execPHP+' /usr/bin/composer config repo.packagist composer https://packagist.phpcomposer.com'); import panelSite; phpini = '/www/server/php/' + php_version + '/etc/php.ini' phpiniConf = public.readFile(phpini); phpiniConf = phpiniConf.replace('proc_open,proc_get_status,',''); public.writeFile(phpini,phpiniConf); os.system('nohup cd '+path+' && '+execPHP+' /usr/bin/composer install -vvv > /tmp/composer.log 2>&1 &'); #写伪静态 self.WriteLogs(json.dumps({'name':'Set URL rewrite','total':0,'used':0,'pre':0,'speed':0})); swfile = path + '/nginx.rewrite'; if os.path.exists(swfile): rewriteConf = public.readFile(swfile); dwfile = self.__panelPath + '/vhost/rewrite/' + site_name + '.conf'; public.writeFile(dwfile,rewriteConf); #删除伪静态文件 public.ExecShell("rm -f " + path + '/*.rewrite') #删除多余文件 rm_file = path + '/index.html' if os.path.exists(rm_file): rm_file_body = public.readFile(rm_file) if rm_file_body.find('panel-heading') != -1: os.remove(rm_file) #设置运行目录 self.WriteLogs(json.dumps({'name':'Set the run directory','total':0,'used':0,'pre':0,'speed':0})); if pinfo['run_path'] != '/': import panelSite; siteObj = panelSite.panelSite(); mobj = obj(); mobj.id = find['id']; mobj.runPath = pinfo['run_path']; siteObj.SetSiteRunPath(mobj); #导入数据 self.WriteLogs(json.dumps({'name':'Import database','total':0,'used':0,'pre':0,'speed':0})); if os.path.exists(path+'/import.sql'): databaseInfo = public.M('databases').where('pid=?',(find['id'],)).field('username,password').find(); if databaseInfo: os.system('/www/server/mysql/bin/mysql -u' + databaseInfo['username'] + ' -p' + databaseInfo['password'] + ' ' + databaseInfo['username'] + ' < ' + path + '/import.sql'); os.system('rm -f ' + path + '/import.sql'); siteConfigFile = (path + '/' + pinfo['db_config']).replace('//','/'); if os.path.exists(siteConfigFile): siteConfig = public.readFile(siteConfigFile) siteConfig = siteConfig.replace('BT_DB_USERNAME',databaseInfo['username']) siteConfig = siteConfig.replace('BT_DB_PASSWORD',databaseInfo['password']) siteConfig = siteConfig.replace('BT_DB_NAME',databaseInfo['username']) public.writeFile(siteConfigFile,siteConfig) #清理文件和目录 for f_path in pinfo['remove_file']: filename = (path + '/' + f_path).replace('//','/') if os.path.exists(filename): if not os.path.isdir(filename): if f_path.find('.user.ini') != -1: public.ExecShell("chattr -i " + filename) os.remove(filename) else: public.ExecShell("rm -rf " + filename) public.serviceReload(); if id: self.depTotal(id); self.WriteLogs(json.dumps({'name':'Ready to deploy','total':0,'used':0,'pre':0,'speed':0})); return public.returnMsg(True,pinfo);
def SetupPackage(self, get): name = get.dname site_name = get.site_name php_version = get.php_version #取基础信息 find = public.M('sites').where('name=?', (site_name, )).field('id,path').find() path = find['path'] #获取包信息 pinfo = self.GetPackageInfo(name) if not pinfo: return public.returnMsg(False, '指定软件包不存在!') #检查本地包 self.WriteLogs( json.dumps({ 'name': '检查软件包', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) packageZip = self.__setupPath + '/package/' + name + '.zip' isDownload = False if os.path.exists(packageZip): md5str = self.GetFileMd5(packageZip) if md5str != pinfo['md5']: isDownload = True else: isDownload = True #下载文件 if isDownload: self.WriteLogs( json.dumps({ 'name': '下载文件', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) self.DownloadFile(pinfo['download'], packageZip) if not os.path.exists(packageZip): return public.returnMsg(False, '文件下载失败!') os.system('unzip -o ' + packageZip + ' -d ' + path + '/') #设置权限 self.WriteLogs( json.dumps({ 'name': '设置权限', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) os.system('chmod -R 755 ' + path) os.system('chown -R www.www ' + path) if pinfo['chmod'] != "": access = pinfo['chmod'].split(',') for chm in access: tmp = chm.split('|') if len(tmp) != 2: continue os.system('chmod -R ' + tmp[0] + ' ' + path + '/' + tmp[1]) #安装PHP扩展 self.WriteLogs( json.dumps({ 'name': '安装必要的PHP扩展', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if pinfo['ext'] != '': exts = pinfo['ext'].split(',') import files mfile = files.files() for ext in exts: if ext == 'pathinfo': import config con = config.config() get.version = php_version get.type = 'on' con.setPathInfo(get) else: get.name = ext get.version = php_version get.type = '1' mfile.InstallSoft(get) #执行额外shell进行依赖安装 self.WriteLogs( json.dumps({ 'name': '执行额外SHELL', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if os.path.exists(path + '/install.sh'): os.system('cd ' + path + ' && bash ' + 'install.sh') os.system('rm -f ' + path + '/install.sh') #是否执行Composer if os.path.exists(path + '/composer.json'): self.WriteLogs( json.dumps({ 'name': '执行Composer', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if not os.path.exists(path + '/composer.lock'): execPHP = '/www/server/php/' + php_version + '/bin/php' if execPHP: if public.get_url().find('125.88'): os.system( 'cd ' + path + ' && ' + execPHP + ' /usr/bin/composer config repo.packagist composer https://packagist.phpcomposer.com' ) import panelSite phpini = '/www/server/php/' + php_version + '/etc/php.ini' phpiniConf = public.readFile(phpini) phpiniConf = phpiniConf.replace( 'proc_open,proc_get_status,', '') public.writeFile(phpini, phpiniConf) os.system( 'nohup cd ' + path + ' && ' + execPHP + ' /usr/bin/composer install -vvv > /tmp/composer.log 2>&1 &' ) #写伪静态 self.WriteLogs( json.dumps({ 'name': '设置伪静态', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) swfile = path + '/nginx.rewrite' if os.path.exists(swfile): rewriteConf = public.readFile(swfile) dwfile = self.__panelPath + '/vhost/rewrite/' + site_name + '.conf' public.writeFile(dwfile, rewriteConf) #设置运行目录 self.WriteLogs( json.dumps({ 'name': '设置运行目录', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if pinfo['run'] != '/': import panelSite siteObj = panelSite.panelSite() mobj = obj() mobj.id = find['id'] mobj.runPath = pinfo['run'] siteObj.SetSiteRunPath(mobj) #导入数据 self.WriteLogs( json.dumps({ 'name': '导入数据库', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if os.path.exists(path + '/import.sql'): databaseInfo = public.M('databases').where( 'pid=?', (find['id'], )).field('username,password').find() if databaseInfo: os.system('/www/server/mysql/bin/mysql -u' + databaseInfo['username'] + ' -p' + databaseInfo['password'] + ' ' + databaseInfo['username'] + ' < ' + path + '/import.sql') os.system('rm -f ' + path + '/import.sql') siteConfigFile = path + '/' + pinfo['config'] if os.path.exists(siteConfigFile): siteConfig = public.readFile(siteConfigFile) siteConfig = siteConfig.replace('BT_DB_USERNAME', databaseInfo['username']) siteConfig = siteConfig.replace('BT_DB_PASSWORD', databaseInfo['password']) siteConfig = siteConfig.replace('BT_DB_NAME', databaseInfo['username']) public.writeFile(siteConfigFile, siteConfig) public.serviceReload() self.depTotal(name) self.WriteLogs( json.dumps({ 'name': '准备部署', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) return public.returnMsg(True, pinfo)
def UpdatePanel(self, get): try: if not public.IsRestart(): return public.returnMsg(False, 'EXEC_ERR_TASK') import json if int(session['config']['status']) == 0: public.HttpGet( public.GetConfigValue('home') + '/Api/SetupCount?type=Linux') public.M('config').where("id=?", ('1', )).setField('status', 1) #取回远程版本信息 if 'updateInfo' in session and hasattr(get, 'check') == False: updateInfo = session['updateInfo'] else: logs = '' import psutil, system, sys mem = psutil.virtual_memory() import panelPlugin mplugin = panelPlugin.panelPlugin() mplugin.ROWS = 10000 panelsys = system.system() data = {} data['sites'] = str(public.M('sites').count()) data['ftps'] = str(public.M('ftps').count()) data['databases'] = str(public.M('databases').count()) data['system'] = panelsys.GetSystemVersion() + '|' + str( mem.total / 1024 / 1024) + 'MB|' + str(public.getCpuType()) + '*' + str( psutil.cpu_count()) + '|' + str( public.get_webserver()) + '|' + session['version'] data['system'] += '||' + self.GetInstalleds( mplugin.getPluginList(None)) data['logs'] = logs data['client'] = request.headers.get('User-Agent') data['oem'] = '' data['intrusion'] = 0 data['uid'] = self.get_uid() #msg = public.getMsg('PANEL_UPDATE_MSG'); data['o'] = '' filename = '/www/server/panel/data/o.pl' if os.path.exists(filename): data['o'] = str(public.readFile(filename)) sUrl = public.GetConfigValue('home') + '/api/panel/updateLinux' updateInfo = json.loads(public.httpPost(sUrl, data)) if not updateInfo: return public.returnMsg(False, "CONNECT_ERR") #updateInfo['msg'] = msg; session['updateInfo'] = updateInfo #检查是否需要升级 if updateInfo['is_beta'] == 1: if updateInfo['beta']['version'] == session['version']: return public.returnMsg(False, updateInfo) else: if updateInfo['version'] == session['version']: return public.returnMsg(False, updateInfo) #是否执行升级程序 if (updateInfo['force'] == True or hasattr(get, 'toUpdate') == True or os.path.exists('data/autoUpdate.pl') == True): if updateInfo['is_beta'] == 1: updateInfo['version'] = updateInfo['beta']['version'] setupPath = public.GetConfigValue('setup_path') uptype = 'update' httpUrl = public.get_url() if httpUrl: updateInfo[ 'downUrl'] = httpUrl + '/install/' + uptype + '/LinuxPanel-' + updateInfo[ 'version'] + '.zip' public.downloadFile(updateInfo['downUrl'], 'panel.zip') if os.path.getsize('panel.zip') < 1048576: return public.returnMsg(False, "PANEL_UPDATE_ERR_DOWN") public.ExecShell('unzip -o panel.zip -d ' + setupPath + '/') import compileall if os.path.exists('/www/server/panel/runserver.py'): public.ExecShell('rm -f /www/server/panel/*.pyc') if os.path.exists('/www/server/panel/class/common.py'): public.ExecShell('rm -f /www/server/panel/class/*.pyc') if os.path.exists('panel.zip'): os.remove("panel.zip") session['version'] = updateInfo['version'] if 'getCloudPlugin' in session: del (session['getCloudPlugin']) if updateInfo['is_beta'] == 1: self.to_beta() public.ExecShell("/etc/init.d/bt start") public.writeFile('data/restart.pl', 'True') return public.returnMsg(True, 'PANEL_UPDATE', (updateInfo['version'], )) #输出新版本信息 data = { 'status': True, 'version': updateInfo['version'], 'updateMsg': updateInfo['updateMsg'] } public.ExecShell('rm -rf /www/server/phpinfo/*') return public.returnMsg(True, updateInfo) except Exception as ex: return public.returnMsg(False, "CONNECT_ERR")
def SetupPackage(self, get): name = get.dname site_name = get.site_name php_version = get.php_version #取基础信息 find = public.M('sites').where( 'name=?', (site_name, )).field('id,path,name').find() if not 'path' in find: return public.returnMsg(False, '网站不存在!') path = find['path'] if path.replace('//', '/') == '/': return public.returnMsg(False, '危险的网站根目录!') #获取包信息 pinfo = self.GetPackageInfo(name) id = pinfo['id'] if not pinfo: return public.returnMsg(False, '指定软件包不存在!') #检查本地包 self.WriteLogs( json.dumps({ 'name': '正在校验软件包...', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) pack_path = self.__panelPath + '/package' if not os.path.exists(pack_path): os.makedirs(pack_path, 384) packageZip = pack_path + '/' + name + '.zip' isDownload = False if os.path.exists(packageZip): md5str = self.GetFileMd5(packageZip) if md5str != pinfo['versions'][0]['md5']: isDownload = True else: isDownload = True #下载文件 if isDownload: self.WriteLogs( json.dumps({ 'name': '正在下载文件 ...', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if pinfo['versions'][0]['download']: self.DownloadFile( 'http://www.bt.cn/api/Pluginother/get_file?fname=' + pinfo['versions'][0]['download'], packageZip) if not os.path.exists(packageZip): return public.returnMsg(False, '文件下载失败!' + packageZip) pinfo = self.set_temp_file(packageZip, path) if not pinfo: return public.returnMsg(False, '在安装包中找不到【宝塔自动部署配置文件】') #设置权限 self.WriteLogs( json.dumps({ 'name': '设置权限', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) os.system('chmod -R 755 ' + path) os.system('chown -R www.www ' + path) if pinfo['chmod']: for chm in pinfo['chmod']: os.system('chmod -R ' + str(chm['mode']) + ' ' + (path + '/' + chm['path']).replace('//', '/')) #安装PHP扩展 self.WriteLogs( json.dumps({ 'name': '安装必要的PHP扩展', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) import files mfile = files.files() if type(pinfo['php_ext']) == str: pinfo['php_ext'] = pinfo['php_ext'].strip().split(',') for ext in pinfo['php_ext']: if ext == 'pathinfo': import config con = config.config() get.version = php_version get.type = 'on' con.setPathInfo(get) else: get.name = ext get.version = php_version get.type = '1' mfile.InstallSoft(get) #解禁PHP函数 if 'enable_functions' in pinfo: try: if type(pinfo['enable_functions']) == str: pinfo['enable_functions'] = pinfo[ 'enable_functions'].strip().split(',') php_f = public.GetConfigValue( 'setup_path') + '/php/' + php_version + '/etc/php.ini' php_c = public.readFile(php_f) rep = "disable_functions\s*=\s{0,1}(.*)\n" tmp = re.search(rep, php_c).groups() disable_functions = tmp[0].split(',') for fun in pinfo['enable_functions']: fun = fun.strip() if fun in disable_functions: disable_functions.remove(fun) disable_functions = ','.join(disable_functions) php_c = re.sub( rep, 'disable_functions = ' + disable_functions + "\n", php_c) public.writeFile(php_f, php_c) public.phpReload(php_version) except: pass #执行额外shell进行依赖安装 self.WriteLogs( json.dumps({ 'name': '执行额外SHELL', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if os.path.exists(path + '/install.sh'): os.system('cd ' + path + ' && bash ' + 'install.sh ' + find['name'] + " &> install.log") os.system('rm -f ' + path + '/install.sh') #是否执行Composer if os.path.exists(path + '/composer.json'): self.WriteLogs( json.dumps({ 'name': '执行Composer', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if not os.path.exists(path + '/composer.lock'): execPHP = '/www/server/php/' + php_version + '/bin/php' if execPHP: if public.get_url().find('125.88'): os.system( 'cd ' + path + ' && ' + execPHP + ' /usr/bin/composer config repo.packagist composer https://packagist.phpcomposer.com' ) import panelSite phpini = '/www/server/php/' + php_version + '/etc/php.ini' phpiniConf = public.readFile(phpini) phpiniConf = phpiniConf.replace( 'proc_open,proc_get_status,', '') public.writeFile(phpini, phpiniConf) os.system( 'nohup cd ' + path + ' && ' + execPHP + ' /usr/bin/composer install -vvv > /tmp/composer.log 2>&1 &' ) #写伪静态 self.WriteLogs( json.dumps({ 'name': '设置伪静态', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) swfile = path + '/nginx.rewrite' if os.path.exists(swfile): rewriteConf = public.readFile(swfile) dwfile = self.__panelPath + '/vhost/rewrite/' + site_name + '.conf' public.writeFile(dwfile, rewriteConf) swfile = path + '/.htaccess' if os.path.exists(swfile): swpath = (path + '/' + pinfo['run_path'] + '/.htaccess').replace( '//', '/') if pinfo['run_path'] != '/' and not os.path.exists(swpath): public.writeFile(swpath, public.readFile(swfile)) #删除伪静态文件 public.ExecShell("rm -f " + path + '/*.rewrite') #删除多余文件 rm_file = path + '/index.html' if os.path.exists(rm_file): rm_file_body = public.readFile(rm_file) if rm_file_body.find('panel-heading') != -1: os.remove(rm_file) #设置运行目录 self.WriteLogs( json.dumps({ 'name': '设置运行目录', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if pinfo['run_path'] != '/': import panelSite siteObj = panelSite.panelSite() mobj = obj() mobj.id = find['id'] mobj.runPath = pinfo['run_path'] siteObj.SetSiteRunPath(mobj) #导入数据 self.WriteLogs( json.dumps({ 'name': '导入数据库', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if os.path.exists(path + '/import.sql'): databaseInfo = public.M('databases').where( 'pid=?', (find['id'], )).field('username,password').find() if databaseInfo: os.system('/www/server/mysql/bin/mysql -u' + databaseInfo['username'] + ' -p' + databaseInfo['password'] + ' ' + databaseInfo['username'] + ' < ' + path + '/import.sql') os.system('rm -f ' + path + '/import.sql') siteConfigFile = (path + '/' + pinfo['db_config']).replace( '//', '/') if os.path.exists(siteConfigFile): siteConfig = public.readFile(siteConfigFile) siteConfig = siteConfig.replace('BT_DB_USERNAME', databaseInfo['username']) siteConfig = siteConfig.replace('BT_DB_PASSWORD', databaseInfo['password']) siteConfig = siteConfig.replace('BT_DB_NAME', databaseInfo['username']) public.writeFile(siteConfigFile, siteConfig) #清理文件和目录 self.WriteLogs( json.dumps({ 'name': '清理多余的文件', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if type(pinfo['remove_file']) == str: pinfo['remove_file'] = pinfo['remove_file'].strip().split(',') print(pinfo['remove_file']) for f_path in pinfo['remove_file']: if not f_path: continue filename = (path + '/' + f_path).replace('//', '/') if os.path.exists(filename): if not os.path.isdir(filename): if f_path.find('.user.ini') != -1: public.ExecShell("chattr -i " + filename) os.remove(filename) else: public.ExecShell("rm -rf " + filename) public.serviceReload() if id: self.depTotal(id) self.WriteLogs( json.dumps({ 'name': '准备部署', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) return public.returnMsg(True, pinfo)