def _http_post(self, url, data, headers={}, timeout=30): data = json.dumps(data).encode('utf8') if sys.version_info[0] == 2: try: import urllib, urllib2, ssl try: ssl._create_default_https_context = ssl._create_unverified_context except: pass req = urllib2.Request(url, data, headers=headers) response = urllib2.urlopen(req, timeout=timeout) return response except Exception as ex: print(public.get_error_info()) return str(ex) else: try: import urllib.request, ssl try: ssl._create_default_https_context = ssl._create_unverified_context except: pass req = urllib.request.Request(url, data, headers=headers) response = urllib.request.urlopen(req, timeout=timeout) return response except Exception as ex: print(public.get_error_info()) return str(ex)
def _http_get(self, url, headers={}, timeout=30): if sys.version_info[0] == 2: try: import urllib2, ssl if sys.version_info[0] == 2: reload(urllib2) reload(ssl) try: ssl._create_default_https_context = ssl._create_unverified_context except: pass req = urllib2.Request(url, headers=headers) response = urllib2.urlopen( req, timeout=timeout, ) return response except Exception as ex: print(public.get_error_info()) return str(ex) else: try: import urllib.request, ssl try: ssl._create_default_https_context = ssl._create_unverified_context except: pass req = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(req, timeout=timeout) return response except Exception as ex: print(public.get_error_info()) return str(ex)
def recv(self): try: n = 0 while not self._web_socket.closed: self.not_send() #if n == 0: self.last_send() data = self._my_terms[self._host].tty.recv(1024) self.not_send() if not data: self.close() self._web_socket.send('连接已断开,连续按两次回车将尝试重新连接!') return try: result = data.decode() except: result = str(data) if not result: continue if self._web_socket.closed: self._my_terms[self._host].not_send = result return self.set_last_send(result) if not n: n = 1 self._web_socket.send(result) except: print(public.get_error_info())
def request_tmp(self,get): try: if not hasattr(get,'tmp_token'): return public.returnJson(False,'错误的参数!'),json_header if len(get.tmp_token) != 64: return public.returnJson(False,'错误的参数!'),json_header if not re.match(r"^\w+$",get.tmp_token):return public.returnJson(False,'错误的参数!'),json_header save_path = '/www/server/panel/config/api.json' data = json.loads(public.ReadFile(save_path)) if not 'tmp_token' in data or not 'tmp_time' in data: return public.returnJson(False,'验证失败!'),json_header if (time.time() - data['tmp_time']) > 120: return public.returnJson(False,'过期的Token'),json_header if get.tmp_token != data['tmp_token']: return public.returnJson(False,'错误的Token'),json_header userInfo = public.M('users').where("id=?",(1,)).field('id,username').find() session['login'] = True session['username'] = userInfo['username'] session['tmp_login'] = True public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT')))) self.limit_address('-') cache.delete('panelNum') cache.delete('dologin') sess_input_path = 'data/session_last.pl' public.writeFile(sess_input_path,str(int(time.time()))) del(data['tmp_token']) del(data['tmp_time']) public.writeFile(save_path,json.dumps(data)) self.set_request_token() self.login_token() self.set_cdn_host(get) return redirect('/') except: return public.returnJson(False,'登录失败,' + public.get_error_info()),json_header
def GetCertName(self, certPath): try: openssl = '/usr/local/openssl/bin/openssl' if not os.path.exists(openssl): openssl = 'openssl' result = public.ExecShell( openssl + " x509 -in " + certPath + " -noout -subject -enddate -startdate -issuer") tmp = result[0].split("\n") data = {} data['subject'] = tmp[0].split('=')[-1] data['notAfter'] = self.strfToTime(tmp[1].split('=')[1]) data['notBefore'] = self.strfToTime(tmp[2].split('=')[1]) if tmp[3].find('O=') == -1: data['issuer'] = tmp[3].split('CN=')[-1] else: data['issuer'] = tmp[3].split('O=')[-1].split(',')[0] if data['issuer'].find('/') != -1: data['issuer'] = data['issuer'].split('/')[0] result = public.ExecShell(openssl + " x509 -in " + certPath + " -noout -text|grep DNS") data['dns'] = result[0].replace('DNS:', '').replace(' ', '').strip().split(',') return data except: print(public.get_error_info()) return None
def select(self): #查询数据集 self.__GetConn() try: self.__get_columns() sql = "SELECT " + self.__OPT_FIELD + " FROM " + self.__DB_TABLE + self.__OPT_WHERE + self.__OPT_ORDER + self.__OPT_LIMIT self.__DB_CUR.execute(sql, self.__OPT_PARAM) data = self.__DB_CUR.fetchall() #构造字典系列 if self.__OPT_FIELD != "*": fields = self.__format_field(self.__OPT_FIELD.split(',')) tmp = [] for row in data: i = 0 tmp1 = {} for key in fields: tmp1[key.strip('`')] = row[i] i += 1 tmp.append(tmp1) del (tmp1) data = tmp del (tmp) else: #将元组转换成列表 tmp = list(map(list, data)) data = tmp del (tmp) self.__close() return data except Exception as ex: return public.get_error_info()
def Completed(self,get): self.__PDATA['data']['partnerOrderId'] = get.partnerOrderId; self.__PDATA['data'] = self.De_Code(self.__PDATA['data']); if hasattr(get,'siteName'): get.path = public.M('sites').where('name=?',(get.siteName,)).getField('path'); runPath = self.GetRunPath(get); if runPath != False and runPath != '/': get.path += runPath; sslInfo = json.loads(public.httpPost(self.__APIURL + '/SyncOrder',self.__PDATA)); sslInfo['data'] = self.En_Code(sslInfo['data']); try: spath = get.path + '/.well-known/pki-validation'; if not os.path.exists(spath): os.system("mkdir -p '" + spath + "'"); public.writeFile(spath + '/fileauth.txt',sslInfo['data']['authValue']); except: return public.returnMsg(False,'SSL_CHECK_WRITE_ERR'); try: result = json.loads(public.httpPost(self.__APIURL + '/Completed',self.__PDATA)); except: result = public.returnMsg(True,'CHECKING') n = 0; my_ok = False while True: if n > 5: break; time.sleep(5); rRet = json.loads(public.httpPost(self.__APIURL + '/SyncOrder',self.__PDATA)); n +=1 rRet['data'] = self.En_Code(rRet['data']); try: if rRet['data']['stateCode'] == 'COMPLETED': my_ok = True break; except: return public.get_error_info() if not my_ok: return result; return rRet;
def set_crond(): try: echo = public.md5(public.md5('renew_lets_ssl_bt')) cron_id = public.M('crontab').where('echo=?', (echo, )).getField('id') import crontab args_obj = public.dict_obj() if not cron_id: cronPath = public.GetConfigValue('setup_path') + '/cron/' + echo shell = 'python /www/server/panel/class/panelLets.py renew_lets_ssl' public.writeFile(cronPath, shell) args_obj.id = public.M('crontab').add( 'name,type,where1,where_hour,where_minute,echo,addtime,status,save,backupTo,sType,sName,sBody,urladdress', ("续签Let's Encrypt证书", 'day', '', '0', '10', echo, time.strftime('%Y-%m-%d %X', time.localtime()), 0, '', 'localhost', 'toShell', '', shell, '')) crontab.crontab().set_cron_status(args_obj) else: cron_path = public.get_cron_path() if os.path.exists(cron_path): cron_s = public.readFile(cron_path) if cron_s.find(echo) == -1: public.M('crontab').where('echo=?', (echo, )).setField('status', 0) args_obj.id = cron_id crontab.crontab().set_cron_status(args_obj) except: print(public.get_error_info())
def recv(self): try: n = 0 while not self._web_socket.closed: self.not_send() #if n == 0: self.last_send() data = self._my_terms[self._host].tty.recv(1024) self.not_send() if not data: self.close() self._web_socket.send( 'The connection has been disconnected and pressing Enter will attempt to reconnect!' ) return try: result = data.decode() except: result = str(data) if not result: continue if self._web_socket.closed: self._my_terms[self._host].not_send = result return self.set_last_send(result) if not n: n = 1 self._web_socket.send(result) except: print(public.get_error_info())
def request_tmp(self,get): try: if not hasattr(get,'tmp_token'): return public.returnJson(False,'INIT_ARGS_ERR'),json_header save_path = '/www/server/panel/config/api.json' data = json.loads(public.ReadFile(save_path)) if not 'tmp_token' in data or not 'tmp_time' in data: return public.returnJson(False,'VERIFICATION_FAILED'),json_header if (time.time() - data['tmp_time']) > 120: return public.returnJson(False,'EXPIRED_TOKEN'),json_header if get.tmp_token != data['tmp_token']: return public.returnJson(False,'INIT_TOKEN_ERR'),json_header userInfo = public.M('users').where("id=?",(1,)).field('id,username').find() session['login'] = True session['username'] = userInfo['username'] session['tmp_login'] = True public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],public.GetClientIp())) self.limit_address('-') cache.delete('panelNum') cache.delete('dologin') sess_input_path = 'data/session_last.pl' public.writeFile(sess_input_path,str(int(time.time()))) del(data['tmp_token']) del(data['tmp_time']) public.writeFile(save_path,json.dumps(data)) self.set_request_token() self.login_token() self.set_cdn_host(get) return redirect('/') except: return public.returnJson(False,'Login failed,' + public.get_error_info()),json_header
def set_httpd_format_log_to_website(self, args): ''' @name 设置网站日志格式 @author zhwen<*****@*****.**> @param sites aaa.com,bbb.com @param log_format_name ''' # sites = args.sites.split(',') sites = loads(args.sites) try: all_site = public.M('sites').field('name').select() reg = 'CustomLog\s+"/www.*{}\s*'.format(args.log_format_name) for site in all_site: website_conf_file = '/www/server/panel/vhost/apache/{}.conf'.format( site['name']) conf = public.readFile(website_conf_file) if not conf: return public.returnMsg(False, 'CONF_FILE_NOT_EXISTS') format_exist_reg = '(CustomLog\s+"/www.*\_log).*' access_log = re.search( format_exist_reg, conf).groups()[0] + '" ' + args.log_format_name if site['name'] not in sites and re.search( format_exist_reg, conf): access_log = ' '.join(access_log.split()[:-1]) conf = re.sub(reg, access_log, conf) public.writeFile(website_conf_file, conf) continue conf = re.sub(format_exist_reg, access_log, conf) public.writeFile(website_conf_file, conf) public.serviceReload() return public.returnMsg(True, 'SET_SUCCESS') except: return public.returnMsg(False, str(public.get_error_info()))
def getData(self,get): try: table = get.table data = self.GetSql(get) SQL = public.M(table) if table == 'backup': import os for i in range(len(data['data'])): if data['data'][i]['size'] == 0: if os.path.exists(data['data'][i]['filename']): data['data'][i]['size'] = os.path.getsize(data['data'][i]['filename']) elif table == 'sites' or table == 'databases': type = '0' if table == 'databases': type = '1' for i in range(len(data['data'])): data['data'][i]['backup_count'] = SQL.table('backup').where("pid=? AND type=?",(data['data'][i]['id'],type)).count() if table == 'sites': for i in range(len(data['data'])): data['data'][i]['domain'] = SQL.table('domain').where("pid=?",(data['data'][i]['id'],)).count() elif table == 'firewall': for i in range(len(data['data'])): if data['data'][i]['port'].find(':') != -1 or data['data'][i]['port'].find('.') != -1 or data['data'][i]['port'].find('-') != -1: data['data'][i]['status'] = -1 else: data['data'][i]['status'] = self.CheckPort(int(data['data'][i]['port'])) #返回 return data except: return public.get_error_info()
def SetCertToSite(self, get): try: result = self.GetCert(get) if not 'privkey' in result: return result siteName = get.siteName path = '/www/server/panel/vhost/cert/' + siteName if not os.path.exists(path): public.ExecShell('mkdir -p ' + path) csrpath = path + "/fullchain.pem" keypath = path + "/privkey.pem" #清理旧的证书链 public.ExecShell('rm -f ' + keypath) public.ExecShell('rm -f ' + csrpath) public.ExecShell('rm -rf ' + path + '-00*') public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName) public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName + '-00*') public.ExecShell('rm -f /etc/letsencrypt/renewal/' + get.siteName + '.conf') public.ExecShell('rm -f /etc/letsencrypt/renewal/' + get.siteName + '-00*.conf') public.ExecShell('rm -f ' + path + '/README') public.writeFile(keypath, result['privkey']) public.writeFile(csrpath, result['fullchain']) import panelSite panelSite.panelSite().SetSSLConf(get) public.serviceReload() return public.returnMsg(True, 'SET_SUCCESS') except Exception as ex: return public.returnMsg(False, 'SET_ERROR,' + public.get_error_info())
def recv(self): ''' @name 读取tty缓冲区数据 @author hwliang<2020-08-07> @return void ''' try: while not self._ws.closed: resp_line = self._ssh.recv(1024) if not resp_line: self._ws.send(public.getMsg('RECONNECT_SSH')) self.close() return if not resp_line: continue if self._ws.closed: return try: result = resp_line.decode() except: result = str(resp_line) self._ws.send(result) self.history_recv(result) except: self._ws.send(public.get_error_info()) self.close()
def get_plugin_price(self, get): try: userPath = 'data/userInfo.json' if not 'pluginName' in get and not 'product_id' in get: return public.returnMsg(False, 'INIT_ARGS_ERR') if not os.path.exists(userPath): return public.returnMsg(False, 'LOGIN_FIRST') params = {} if not hasattr(get, 'product_id'): params['product_id'] = self.get_plugin_info( get.pluginName)['id'] else: params['product_id'] = get.product_id data = self.send_cloud( '{}/api/product/prices'.format(self.__official_url), params) if not data['success']: return public.returnMsg(False, data['msg']) # if len(data['res']) == 6: # return data['res'][3:] return data['res'] except: del (session['get_product_list']) return public.returnMsg( False, 'Syncing information, please try again!\n' + public.get_error_info())
def add_nginx_access_log_format(self, args): ''' @name 添加日志格式 @author zhwen<*****@*****.**> @param log_format 需要设置的日志格式["$server_name","$remote_addr","-"....] @param log_format_name @param act 操作方式 add/edit ''' try: log_format = loads(args.log_format) data = """ #LOG_FORMAT_BEGIN_{n} log_format {n} '{c}'; #LOG_FORMAT_END_{n} """.format(n=args.log_format_name, c=' '.join(log_format)) data = data.replace('$http_user_agent', '"$http_user_agent"') data = data.replace('$request', '"$request"') if args.act == 'edit': self.del_nginx_access_log_format(args) conf = public.readFile(self.nginxconf) if not conf: return public.returnMsg(False, 'NGINX_CONF_NOT_EXISTS') reg = 'http(\n|\s)+{' conf = re.sub(reg, 'http\n\t{' + data, conf) public.writeFile(self.nginxconf, conf) public.serviceReload() return public.returnMsg(True, 'SET_SUCCESS') except: return public.returnMsg(False, str(public.get_error_info()))
def set_format_log_to_website(self, args): ''' @name 设置日志格式 @author zhwen<*****@*****.**> @param sites aaa.com,bbb.com @param log_format_name ''' # sites = args.sites.split(',') sites = loads(args.sites) try: all_site = public.M('sites').field('name').select() reg = 'access_log\s+/www.*{}\s*;'.format(args.log_format_name) for site in all_site: website_conf_file = '/www/server/panel/vhost/nginx/{}.conf'.format( site['name']) conf = public.readFile(website_conf_file) if not conf: return public.returnMsg(False, 'NGINX_CONF_NOT_EXISTS') format_exist_reg = '(access_log\s+/www.*\.log).*;' access_log = self.get_nginx_access_log(conf) if not access_log: continue access_log = 'access_log ' + access_log + ' ' + args.log_format_name + ';' if site['name'] not in sites and re.search( format_exist_reg, conf): access_log = ' '.join(access_log.split()[:-1]) + ';' conf = re.sub(reg, access_log, conf) public.writeFile(website_conf_file, conf) continue conf = re.sub(format_exist_reg, access_log, conf) public.writeFile(website_conf_file, conf) return public.returnMsg(True, 'SET_SUCCESS') except: return public.returnMsg(False, str(public.get_error_info()))
def check_files_panel(): python_bin = get_python_bin() while True: time.sleep(600) try: result = loads( os.popen('{} {}/script/check_files.py'.format( python_bin, base_path)).read()) except: logging.info(public.get_error_info()) continue if result in ['0']: continue if type(result) != list: continue class_path = '{}/class/'.format(base_path) for i in result: cf = class_path + i['name'] if not os.path.exists(cf): continue if public.FileMd5(cf) == i['md5']: continue public.writeFile(cf, i['body']) os.system("bash {}/init.sh reload &".format(base_path))
def add_httpd_access_log_format(self, args): ''' @name 添加httpd日志格式 @author zhwen<*****@*****.**> @param log_format 需要设置的日志格式["$server_name","$remote_addr","-"....] @param log_format_name @param act 操作方式 add/edit ''' try: log_format = loads(args.log_format) data = """ #LOG_FORMAT_BEGIN_{n} LogFormat '{c}' {n} #LOG_FORMAT_END_{n} """.format(n=args.log_format_name, c=' '.join(log_format)) data = data.replace('%{User-agent}i', '"%{User-agent}i"') data = data.replace('%{Referer}i', '"%{Referer}i"') if args.act == 'edit': self.del_httpd_access_log_format(args) conf = public.readFile(self.httpdconf) if not conf: return public.returnMsg(False, 'CONF_FILE_NOT_EXISTS') reg = '<IfModule log_config_module>' conf = re.sub(reg, '<IfModule log_config_module>' + data, conf) public.writeFile(self.httpdconf, conf) public.serviceReload() return public.returnMsg(True, 'SET_SUCCESS') except: return public.returnMsg(False, str(public.get_error_info()))
def clean_max_log(log_file, max_size=104857600, old_line=100): if not os.path.exists(log_file): return False if os.path.getsize(log_file) > max_size: try: old_body = public.GetNumLines(log_file, old_line) public.writeFile(log_file, old_body) except: print(public.get_error_info())
def resize(self, data): try: data = json.loads(data) self._my_terms[self._host].tty.resize_pty(width=data['width'], height=data['height'], width_pixels=data['width_px'], height_pixels=data['height_px']) return True except: print(public.get_error_info()) return False
def check_login(self): try: api_check = True g.api_request = False if not 'login' in session: api_check = self.get_sk() if api_check: session.clear() return api_check g.api_request = True else: if session['login'] == False: public.WriteLog('Login auth', 'The current session has been logged out') session.clear() return redirect('/login') if 'tmp_login_expire' in session: s_file = 'data/session/{}'.format(session['tmp_login_id']) if session['tmp_login_expire'] < time.time(): public.WriteLog('Login auth', 'Temporary authorization has expired {}'.format(public.get_client_ip())) session.clear() if os.path.exists(s_file): os.remove(s_file) return redirect('/login') if not os.path.exists(s_file): public.WriteLog('Login auth', 'Forced withdrawal due to cancellation of temporary authorization {}'.format(public.get_client_ip())) session.clear() return redirect('/login') ua_md5 = public.md5(g.ua) if ua_md5 != session.get('login_user_agent',ua_md5): public.WriteLog('Login auth', 'UA verification failed {}'.format(public.get_client_ip())) session.clear() return redirect('/login') if api_check: session_timeout = session.get('session_timeout',0) if session_timeout < time.time() and session_timeout != 0: public.WriteLog('Login auth', 'The session has expired {}'.format(public.get_client_ip())) session.clear() return redirect('/login?dologin=True&go=0') login_token = session.get('login_token','') if login_token: if login_token != public.get_login_token_auth(): public.WriteLog('Login auth', 'Session ID does not match {}'.format(public.get_client_ip())) session.clear() return redirect('/login?dologin=True&go=1') if api_check: filename = 'data/sess_files/' + public.get_sess_key() if not os.path.exists(filename): public.WriteLog('Login auth', 'Trigger CSRF defense {}'.format(public.get_client_ip())) session.clear() return redirect('/login?dologin=True&go=2') except: public.WriteLog('Login auth',public.get_error_info()) session.clear() return redirect('/login')
def check_login(self): try: api_check = True g.api_request = False if not 'login' in session: api_check = self.get_sk() if api_check: #session.clear() return api_check g.api_request = True else: if session['login'] == False: session.clear() return redirect('/login') if 'tmp_login_expire' in session: s_file = 'data/session/{}'.format(session['tmp_login_id']) if session['tmp_login_expire'] < time.time(): session.clear() if os.path.exists(s_file): os.remove(s_file) return redirect('/login') if not os.path.exists(s_file): session.clear() return redirect('/login') ua_md5 = public.md5(g.ua) if ua_md5 != session.get('login_user_agent', ua_md5): session.clear() return redirect('/login') if api_check: now_time = time.time() session_timeout = session.get('session_timeout', 0) if session_timeout < now_time and session_timeout != 0: session.clear() return redirect('/login?dologin=True&go=0') login_token = session.get('login_token', '') if login_token: if login_token != public.get_login_token_auth(): session.clear() return redirect('/login?dologin=True&go=1') # if api_check: # filename = 'data/sess_files/' + public.get_sess_key() # if not os.path.exists(filename): # session.clear() # return redirect('/login?dologin=True&go=2') # 标记新的会话过期时间 session['session_timeout'] = time.time( ) + public.get_session_timeout() except: public.WriteLog('Login auth', public.get_error_info()) session.clear() return redirect('/login')
def get_disk_iostat(self): iokey = 'iostat' diskio = cache.get(iokey) mtime = int(time.time()) if not diskio: diskio = {} diskio['info'] = None diskio['time'] = mtime diskio_1 = diskio['info'] stime = mtime - diskio['time'] if not stime: stime = 1 diskInfo = {} diskInfo['ALL'] = {} diskInfo['ALL']['read_count'] = 0 diskInfo['ALL']['write_count'] = 0 diskInfo['ALL']['read_bytes'] = 0 diskInfo['ALL']['write_bytes'] = 0 diskInfo['ALL']['read_time'] = 0 diskInfo['ALL']['write_time'] = 0 diskInfo['ALL']['read_merged_count'] = 0 diskInfo['ALL']['write_merged_count'] = 0 try: if os.path.exists('/proc/diskstats'): diskio_2 = psutil.disk_io_counters(perdisk=True) if not diskio_1: diskio_1 = diskio_2 for disk_name in diskio_2.keys(): diskInfo[disk_name] = {} diskInfo[disk_name]['read_count'] = int((diskio_2[disk_name].read_count - diskio_1[disk_name].read_count) / stime) diskInfo[disk_name]['write_count'] = int((diskio_2[disk_name].write_count - diskio_1[disk_name].write_count) / stime) diskInfo[disk_name]['read_bytes'] = int((diskio_2[disk_name].read_bytes - diskio_1[disk_name].read_bytes) / stime) diskInfo[disk_name]['write_bytes'] = int((diskio_2[disk_name].write_bytes - diskio_1[disk_name].write_bytes) / stime) diskInfo[disk_name]['read_time'] = int((diskio_2[disk_name].read_time - diskio_1[disk_name].read_time) / stime) diskInfo[disk_name]['write_time'] = int((diskio_2[disk_name].write_time - diskio_1[disk_name].write_time) / stime) diskInfo[disk_name]['read_merged_count'] = int((diskio_2[disk_name].read_merged_count - diskio_1[disk_name].read_merged_count) / stime) diskInfo[disk_name]['write_merged_count'] = int((diskio_2[disk_name].write_merged_count - diskio_1[disk_name].write_merged_count) / stime) diskInfo['ALL']['read_count'] += diskInfo[disk_name]['read_count'] diskInfo['ALL']['write_count'] += diskInfo[disk_name]['write_count'] diskInfo['ALL']['read_bytes'] += diskInfo[disk_name]['read_bytes'] diskInfo['ALL']['write_bytes'] += diskInfo[disk_name]['write_bytes'] if diskInfo['ALL']['read_time'] < diskInfo[disk_name]['read_time']: diskInfo['ALL']['read_time'] = diskInfo[disk_name]['read_time'] if diskInfo['ALL']['write_time'] < diskInfo[disk_name]['write_time']: diskInfo['ALL']['write_time'] = diskInfo[disk_name]['write_time'] diskInfo['ALL']['read_merged_count'] += diskInfo[disk_name]['read_merged_count'] diskInfo['ALL']['write_merged_count'] += diskInfo[disk_name]['write_merged_count'] cache.set(iokey,{'info':diskio_2,'time':mtime}) except: public.writeFile('/tmp/2',str(public.get_error_info())) return diskInfo return diskInfo
def get_plugin_price(self,get): try: userPath = 'data/userInfo.json' if not 'pluginName' in get: return public.returnMsg(False,'参数错误!') if not os.path.exists(userPath): return public.returnMsg(False,'请先登陆宝塔官网帐号!') params = {} params['pid'] = self.get_plugin_info(get.pluginName)['id'] #params['ajax2'] = '1'; data = self.send_cloud('get_product_discount', params) return data except: del(session['get_product_list']) return public.returnMsg(False,'正在同步信息,请重试!' + public.get_error_info())
def send_cloud(self,cloudURL,params): try: userInfo = self.create_serverid(None) if 'token' not in userInfo: return None url_headers = {"Content-Type": "application/json", "authorization": "bt {}".format(userInfo['token']) } resp = requests.post(cloudURL, params=params, headers=url_headers) resp = resp.json() if not resp['res']: return None return resp except: return public.get_error_info()
def start_task(self): noe = False while True: try: time.sleep(1); if not os.path.exists(self.__task_tips) and noe: continue; if os.path.exists(self.__task_tips): os.remove(self.__task_tips) public.M(self.__table).where('status=?',('-1',)).setField('status',0) task_list = self.get_task_list(0) for task_info in task_list: self.execute_task(task_info['id'],task_info['type'],task_info['shell'],task_info['other']) noe = True except: print(public.get_error_info())
def GetPHPStatus(self,get): #取指定PHP版本的负载状态 try: version = get.version uri = "/phpfpm_"+version+"_status" result = public.request_php(version,uri,uri,'json') tmp = json.loads(result) fTime = time.localtime(int(tmp['start time'])) tmp['start time'] = time.strftime('%Y-%m-%d %H:%M:%S',fTime) return tmp except Exception as ex: public.WriteLog('信息获取',"PHP负载状态获取失败: {}".format(public.get_error_info())) return public.returnMsg(False,'负载状态获取失败!')
def GetPHPStatus(self,get): #取指定PHP版本的负载状态 try: version = get.version uri = "/phpfpm_"+version+"_status?json" result = public.request_php(version,uri,'') tmp = json.loads(result) fTime = time.localtime(int(tmp['start time'])) tmp['start time'] = time.strftime('%Y-%m-%d %H:%M:%S',fTime) return tmp except Exception as ex: public.WriteLog('GET_INFO',"PHP_LOAD_ERR",(public.get_error_info(),)) return public.returnMsg(False,'PHP_LOAD_ERR1')
def get(url,timeout = 60,headers = {},verify = False,s_type = None): ''' GET请求 @param [url] string URL地址 @param [timeout] int 超时时间 默认60秒 @param [headers] dict 请求头 默认{"Content-type":"application/x-www-form-urlencoded","User-Agent":"BT-Panel"} @param [verify] bool 是否验证ssl证书 默认False @param [s_type] string 请求方法 默认python 可选:curl或php ''' p = http() try: return p.get(url,timeout,get_headers(headers),verify,get_stype(s_type)) except: raise Exception(public.get_error_info())