diff --git a/BTPanel/static/js/crontab.js b/BTPanel/static/js/crontab.js index 0b0274b0..566e25c4 100644 --- a/BTPanel/static/js/crontab.js +++ b/BTPanel/static/js/crontab.js @@ -910,9 +910,35 @@ function toFile(){ //从脚本 function toShell(){ - var tBody = ""; + var shell_body = ''; + var shell_name = ''; + if($("b[val='toShell']").text() === '同步时间'){ + shell_name = '定期同步服务器时间'; + shell_body = 'echo "|-正在尝试从0.pool.bt.cn同步时间..";\n\ +ntpdate -u 0.pool.bt.cn\n\ +if [ $? = 1 ];then\n\ + echo "|-正在尝试从1.pool.bt.cn同步时间..";\n\ + ntpdate -u 1.pool.bt.cn\n\ +fi\n\ +if [ $? = 1 ];then\n\ + echo "|-正在尝试从0.asia.pool.ntp.org同步时间..";\n\ + ntpdate -u 0.asia.pool.ntp.org\n\ +fi\n\ +if [ $? = 1 ];then\n\ + echo "|-正在尝试从www.bt.cn同步时间..";\n\ + getBtTime=$(curl -sS --connect-timeout 3 -m 60 http://www.bt.cn/api/index/get_time)\n\ + if [ "${getBtTime}" ];then \n\ + date -s "$(date -d @$getBtTime +"%Y-%m-%d %H:%M:%S")"\n\ + fi\n\ +fi\n\ +echo "|-正在尝试将当前系统时间写入硬件..";\n\ +hwclock -w\n\ +date\n\ +echo "|-时间同步完成!";' + } + var tBody = ""; $("#implement").html(tBody); - $(".planname input[name='name']").removeAttr('readonly style').val(""); + $(".planname input[name='name']").removeAttr('readonly style').val(shell_name); } function toPath() { diff --git a/BTPanel/templates/default/crontab.html b/BTPanel/templates/default/crontab.html index 233aabce..95d8ec76 100644 --- a/BTPanel/templates/default/crontab.html +++ b/BTPanel/templates/default/crontab.html @@ -36,6 +36,9 @@

{{data['lan']['H3']}}

  • 备份目录
  • +
  • + 同步时间 +
  • {{data['lan']['TT5']}}
  • @@ -44,7 +47,7 @@

    {{data['lan']['H3']}}

    - *{{data['lan']['PS']}} + *{{data['lan']['PS']}}、备份目录、同步时间
    {{data['lan']['T2']}} diff --git a/class/acme_v2.py b/class/acme_v2.py index 3d6eafb4..d02092f7 100644 --- a/class/acme_v2.py +++ b/class/acme_v2.py @@ -1109,7 +1109,9 @@ def get_account_key(self): self._config['account'][k] = {} if not 'key' in self._config['account'][k]: - self._config['account'][k]['key'] = self.create_key().encode() + self._config['account'][k]['key'] = self.create_key() + if type(self._config['account'][k]['key']) == bytes: + self._config['account'][k]['key'] = self._config['account'][k]['key'].decode() self.save_config() return self._config['account'][k]['key'] @@ -1120,10 +1122,12 @@ def create_certificate_key(self, index): return self._config['orders'][index]['private_key'] # 创建新的私钥 private_key = self.create_key() + if type(private_key) == bytes: + private_key = private_key.decode() # 保存私钥到订单配置文件 self._config['orders'][index]['private_key'] = private_key self.save_config() - return private_key.decode() + return private_key # 创建Key def create_key(self, key_type=OpenSSL.crypto.TYPE_RSA): @@ -1322,8 +1326,6 @@ def echo_err(msg): exit() # 写日志 - - def write_log(log_str, mode="ab+"): if __name__ == "__main__": print(log_str) diff --git a/class/ajax.py b/class/ajax.py index 46b115ee..58631c63 100644 --- a/class/ajax.py +++ b/class/ajax.py @@ -6,7 +6,7 @@ # +------------------------------------------------------------------- # | Author: 黄文良 <287962566@qq.com> # +------------------------------------------------------------------- -from BTPanel import session +from BTPanel import session,request import public,os,json,time,apache,psutil class ajax: @@ -74,10 +74,10 @@ def GetPHPStatus(self,get): return public.returnMsg(False,'负载状态获取失败!') def CheckStatusConf(self): - if public.get_webserver() != 'nginx': return; - filename = session['setupPath'] + '/panel/vhost/nginx/phpfpm_status.conf'; + if public.get_webserver() != 'nginx': return + filename = session['setupPath'] + '/panel/vhost/nginx/phpfpm_status.conf' if os.path.exists(filename): - if public.ReadFile(filename).find('nginx_status')!=-1: return; + if public.ReadFile(filename).find('nginx_status')!=-1: return conf = '''server { listen 80; @@ -88,8 +88,8 @@ def CheckStatusConf(self): access_log off; } }''' - public.writeFile(filename,conf); - public.serviceReload(); + public.writeFile(filename,conf) + public.serviceReload() def GetTaskCount(self,get): @@ -99,89 +99,89 @@ def GetTaskCount(self,get): def GetSoftList(self,get): #取软件列表 import json,os - tmp = public.readFile('data/softList.conf'); + tmp = public.readFile('data/softList.conf') data = json.loads(tmp) tasks = public.M('tasks').where("status!=?",('1',)).field('status,name').select() for i in range(len(data)): - data[i]['check'] = public.GetConfigValue('root_path')+'/'+data[i]['check']; + data[i]['check'] = public.GetConfigValue('root_path')+'/'+data[i]['check'] for n in range(len(data[i]['versions'])): #处理任务标记 - isTask = '1'; + isTask = '1' for task in tasks: tmp = public.getStrBetween('[',']',task['name']) - if not tmp:continue; - tmp1 = tmp.split('-'); + if not tmp:continue + tmp1 = tmp.split('-') if data[i]['name'] == 'PHP': if tmp1[0].lower() == data[i]['name'].lower() and tmp1[1] == data[i]['versions'][n]['version']: isTask = task['status']; else: - if tmp1[0].lower() == data[i]['name'].lower(): isTask = task['status']; + if tmp1[0].lower() == data[i]['name'].lower(): isTask = task['status'] #检查安装状态 if data[i]['name'] == 'PHP': data[i]['versions'][n]['task'] = isTask - checkFile = data[i]['check'].replace('VERSION',data[i]['versions'][n]['version'].replace('.','')); + checkFile = data[i]['check'].replace('VERSION',data[i]['versions'][n]['version'].replace('.','')) else: data[i]['task'] = isTask - version = public.readFile(public.GetConfigValue('root_path')+'/server/'+data[i]['name'].lower()+'/version.pl'); - if not version:continue; - if version.find(data[i]['versions'][n]['version']) == -1:continue; - checkFile = data[i]['check']; - data[i]['versions'][n]['status'] = os.path.exists(checkFile); + version = public.readFile(public.GetConfigValue('root_path')+'/server/'+data[i]['name'].lower()+'/version.pl') + if not version:continue + if version.find(data[i]['versions'][n]['version']) == -1:continue + checkFile = data[i]['check'] + data[i]['versions'][n]['status'] = os.path.exists(checkFile) return data def GetLibList(self,get): #取插件列表 import json,os - tmp = public.readFile('data/libList.conf'); + tmp = public.readFile('data/libList.conf') data = json.loads(tmp) for i in range(len(data)): - data[i]['status'] = self.CheckLibInstall(data[i]['check']); - data[i]['optstr'] = self.GetLibOpt(data[i]['status'], data[i]['opt']); + data[i]['status'] = self.CheckLibInstall(data[i]['check']) + data[i]['optstr'] = self.GetLibOpt(data[i]['status'], data[i]['opt']) return data def CheckLibInstall(self,checks): for cFile in checks: - if os.path.exists(cFile): return '已安装'; - return '未安装'; + if os.path.exists(cFile): return '已安装' + return '未安装' #取插件操作选项 def GetLibOpt(self,status,libName): - optStr = ''; + optStr = '' if status == '未安装': - optStr = '安装'; + optStr = '安装' else: - libConfig = '配置'; - if(libName == 'beta'): libConfig = '内测资料'; + libConfig = '配置' + if(libName == 'beta'): libConfig = '内测资料' - optStr = ''+libConfig+' | 卸载'; - return optStr; + optStr = ''+libConfig+' | 卸载' + return optStr #取插件AS def GetQiniuAS(self,get): - filename = public.GetConfigValue('setup_path') + '/panel/data/'+get.name+'As.conf'; - if not os.path.exists(filename): public.writeFile(filename,''); + filename = public.GetConfigValue('setup_path') + '/panel/data/'+get.name+'As.conf' + if not os.path.exists(filename): public.writeFile(filename,'') data = {} - data['AS'] = public.readFile(filename).split('|'); - data['info'] = self.GetLibInfo(get.name); + data['AS'] = public.readFile(filename).split('|') + data['info'] = self.GetLibInfo(get.name) if len(data['AS']) < 3: - data['AS'] = ['','','','']; - return data; + data['AS'] = ['','','',''] + return data #设置插件AS def SetQiniuAS(self,get): - info = self.GetLibInfo(get.name); - filename = public.GetConfigValue('setup_path') + '/panel/data/'+get.name+'As.conf'; - conf = get.access_key.strip() + '|' + get.secret_key.strip() + '|' + get.bucket_name.strip() + '|' + get.bucket_domain.strip(); - public.writeFile(filename,conf); + info = self.GetLibInfo(get.name) + filename = public.GetConfigValue('setup_path') + '/panel/data/'+get.name+'As.conf' + conf = get.access_key.strip() + '|' + get.secret_key.strip() + '|' + get.bucket_name.strip() + '|' + get.bucket_domain.strip() + public.writeFile(filename,conf) public.ExecShell("chmod 600 " + filename) result = public.ExecShell("python " + public.GetConfigValue('setup_path') + "/panel/script/backup_"+get.name+".py list") if result[0].find("ERROR:") == -1: - public.WriteLog("插件管理", "设置插件["+info['name']+"]AS!"); - return public.returnMsg(True, '设置成功!'); - return public.returnMsg(False, 'ERROR: 无法连接到'+info['name']+'服务器,请检查[AK/SK/存储空间]设置是否正确!'); + public.WriteLog("插件管理", "设置插件["+info['name']+"]AS!") + return public.returnMsg(True, '设置成功!') + return public.returnMsg(False, 'ERROR: 无法连接到'+info['name']+'服务器,请检查[AK/SK/存储空间]设置是否正确!') #设置内测 def SetBeta(self,get): @@ -191,33 +191,33 @@ def SetBeta(self,get): data['email'] = get.email result = public.httpPost(public.GetConfigValue('home') + '/Api/LinuxBeta',data); import json; - data = json.loads(result); + data = json.loads(result) if data['status']: public.writeFile('data/beta.pl',get.bbs_name + '|' + get.qq + '|' + get.email); - return data; + return data #取内测资格状态 def GetBetaStatus(self,get): try: - return public.readFile('data/beta.pl').strip(); + return public.readFile('data/beta.pl').strip() except: - return 'False'; + return 'False' #获取指定插件信息 def GetLibInfo(self,name): import json - tmp = public.readFile('data/libList.conf'); + tmp = public.readFile('data/libList.conf') data = json.loads(tmp) for lib in data: - if name == lib['opt']: return lib; - return False; + if name == lib['opt']: return lib + return False #获取文件列表 def GetQiniuFileList(self,get): try: import json result = public.ExecShell("python " + public.GetConfigValue('setup_path') + "/panel/script/backup_"+get.name+".py list") - return json.loads(result[0]); + return json.loads(result[0]) except: return public.returnMsg(False, '获取列表失败,请检查[AK/SK/存储空间]设是否正确!'); @@ -244,30 +244,30 @@ def GetNetWorkList(self,get): networkList.append(tmp) del(p) del(tmp) - networkList = sorted(networkList, key=lambda x : x['status'], reverse=True); - return networkList; + networkList = sorted(networkList, key=lambda x : x['status'], reverse=True) + return networkList #取进程列表 def GetProcessList(self,get): import psutil,pwd - Pids = psutil.pids(); + Pids = psutil.pids() processList = [] for pid in Pids: try: tmp = {} - p = psutil.Process(pid); - if p.exe() == "": continue; + p = psutil.Process(pid) + if p.exe() == "": continue tmp['name'] = p.name(); #进程名称 - if self.GoToProcess(tmp['name']): continue; + if self.GoToProcess(tmp['name']): continue tmp['pid'] = pid; #进程标识 tmp['status'] = p.status(); #进程状态 tmp['user'] = p.username(); #执行用户 cputimes = p.cpu_times() - tmp['cpu_percent'] = p.cpu_percent(0.1); + tmp['cpu_percent'] = p.cpu_percent(0.1) tmp['cpu_times'] = cputimes.user #进程占用的CPU时间 tmp['memory_percent'] = round(p.memory_percent(),3) #进程占用的内存比例 pio = p.io_counters() @@ -275,27 +275,27 @@ def GetProcessList(self,get): tmp['io_read_bytes'] = pio.read_bytes #进程总共读取字节数 tmp['threads'] = p.num_threads() #进程总线程数 - processList.append(tmp); + processList.append(tmp) del(p) del(tmp) except: - continue; + continue import operator - processList = sorted(processList, key=lambda x : x['memory_percent'], reverse=True); - processList = sorted(processList, key=lambda x : x['cpu_times'], reverse=True); + processList = sorted(processList, key=lambda x : x['memory_percent'], reverse=True) + processList = sorted(processList, key=lambda x : x['cpu_times'], reverse=True) return processList #结束指定进程 def KillProcess(self,get): #return public.returnMsg(False,'演示服务器,禁止此操作!'); import psutil - p = psutil.Process(int(get.pid)); - name = p.name(); - if name == 'python': return public.returnMsg(False,'KILL_PROCESS_ERR'); + p = psutil.Process(int(get.pid)) + name = p.name() + if name == 'python': return public.returnMsg(False,'KILL_PROCESS_ERR') - p.kill(); - public.WriteLog('TYPE_PROCESS','KILL_PROCESS',(get.pid,name)); - return public.returnMsg(True,'KILL_PROCESS',(get.pid,name)); + p.kill() + public.WriteLog('TYPE_PROCESS','KILL_PROCESS',(get.pid,name)) + return public.returnMsg(True,'KILL_PROCESS',(get.pid,name)) def GoToProcess(self,name): ps = ['sftp-server','login','nm-dispatcher','irqbalance','qmgr','wpa_supplicant','lvmetad','auditd','master','dbus-daemon','tapdisk','sshd','init','ksoftirqd','kworker','kmpathd','kmpath_handlerd','python','kdmflush','bioset','crond','kthreadd','migration','rcu_sched','kjournald','iptables','systemd','network','dhclient','systemd-journald','NetworkManager','systemd-logind','systemd-udevd','polkitd','tuned','rsyslogd'] @@ -309,20 +309,20 @@ def GoToProcess(self,name): def GetNetWorkIo(self,get): #取指定时间段的网络Io data = public.M('network').dbfile('system').where("addtime>=? AND addtime<=?",(get.start,get.end)).field('id,up,down,total_up,total_down,down_packets,up_packets,addtime').order('id asc').select() - return self.ToAddtime(data); + return self.ToAddtime(data) def GetDiskIo(self,get): #取指定时间段的磁盘Io data = public.M('diskio').dbfile('system').where("addtime>=? AND addtime<=?",(get.start,get.end)).field('id,read_count,write_count,read_bytes,write_bytes,read_time,write_time,addtime').order('id asc').select() - return self.ToAddtime(data); + return self.ToAddtime(data) def GetCpuIo(self,get): #取指定时间段的CpuIo data = public.M('cpuio').dbfile('system').where("addtime>=? AND addtime<=?",(get.start,get.end)).field('id,pro,mem,addtime').order('id asc').select() - return self.ToAddtime(data,True); + return self.ToAddtime(data,True) def get_load_average(self,get): data = public.M('load_average').dbfile('system').where("addtime>=? AND addtime<=?",(get.start,get.end)).field('id,pro,one,five,fifteen,addtime').order('id asc').select() - return self.ToAddtime(data); + return self.ToAddtime(data) def ToAddtime(self,data,tomem = False): @@ -332,11 +332,11 @@ def ToAddtime(self,data,tomem = False): if tomem: import psutil mPre = (psutil.virtual_memory().total / 1024 / 1024) / 100 - length = len(data); - he = 1; - if length > 100: he = 1; - if length > 1000: he = 3; - if length > 10000: he = 15; + length = len(data) + he = 1 + if length > 100: he = 1 + if length > 1000: he = 3 + if length > 10000: he = 15 if he == 1: for i in range(length): data[i]['addtime'] = time.strftime('%m/%d %H:%M',time.localtime(float(data[i]['addtime']))) @@ -344,47 +344,47 @@ def ToAddtime(self,data,tomem = False): return data else: - count = 0; + count = 0 tmp = [] for value in data: if count < he: - count += 1; - continue; + count += 1 + continue value['addtime'] = time.strftime('%m/%d %H:%M',time.localtime(float(value['addtime']))) if tomem and value['mem'] > 100: value['mem'] = value['mem'] / mPre - tmp.append(value); - count = 0; - return tmp; + tmp.append(value) + count = 0 + return tmp def GetInstalleds(self,softlist): - softs = ''; + softs = '' for soft in softlist['data']: try: for v in soft['versions']: - if v['status']: softs += soft['name'] + '-' + v['version'] + '|'; + if v['status']: softs += soft['name'] + '-' + v['version'] + '|' except: pass - return softs; + return softs #获取SSH爆破次数 def get_ssh_intrusion(self): - fp = open('/var/log/secure','rb'); - l = fp.readline(); - intrusion_total = 0; + fp = open('/var/log/secure','rb') + l = fp.readline() + intrusion_total = 0 while l: - if l.find('Failed password for root') != -1: intrusion_total += 1; - l = fp.readline(); - fp.close(); - return intrusion_total; + if l.find('Failed password for root') != -1: intrusion_total += 1 + l = fp.readline() + fp.close() + return intrusion_total #申请内测版 def apple_beta(self,get): try: userInfo = json.loads(public.ReadFile('data/userInfo.json')) p_data = {} - p_data['uid'] = userInfo['uid']; + p_data['uid'] = userInfo['uid'] p_data['access_key'] = userInfo['access_key'] p_data['username'] = userInfo['username'] result = public.HttpPost(public.GetConfigValue('home') + '/api/panel/apple_beta',p_data,5) @@ -397,7 +397,7 @@ def to_not_beta(self,get): try: userInfo = json.loads(public.ReadFile('data/userInfo.json')) p_data = {} - p_data['uid'] = userInfo['uid']; + p_data['uid'] = userInfo['uid'] p_data['access_key'] = userInfo['access_key'] p_data['username'] = userInfo['username'] result = public.HttpPost(public.GetConfigValue('home') + '/api/panel/to_not_beta',p_data,5) @@ -410,7 +410,7 @@ def to_beta(self): try: userInfo = json.loads(public.ReadFile('data/userInfo.json')) p_data = {} - p_data['uid'] = userInfo['uid']; + p_data['uid'] = userInfo['uid'] p_data['access_key'] = userInfo['access_key'] p_data['username'] = userInfo['username'] public.HttpPost(public.GetConfigValue('home') + '/api/panel/to_beta',p_data,5) @@ -432,111 +432,112 @@ def get_beta_logs(self,get): def UpdatePanel(self,get): try: - if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK'); + 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); + 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']; + updateInfo = session['updateInfo'] else: - logs = ''; + logs = '' import psutil,system,sys - mem = psutil.virtual_memory(); + mem = psutil.virtual_memory() import panelPlugin - mplugin = panelPlugin.panelPlugin(); + mplugin = panelPlugin.panelPlugin() - mplugin.ROWS = 10000; - panelsys = system.system(); + 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['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['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"); + 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; + session['updateInfo'] = updateInfo #检查是否需要升级 if updateInfo['is_beta'] == 1: - if updateInfo['beta']['version'] ==session['version']: return public.returnMsg(False,updateInfo); + if updateInfo['beta']['version'] ==session['version']: return public.returnMsg(False,updateInfo) else: - if updateInfo['version'] ==session['version']: return public.returnMsg(False,updateInfo); + 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 + '/'); + 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('/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 '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'],)); + 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); + public.ExecShell('rm -rf /www/server/phpinfo/*') + return public.returnMsg(True,updateInfo) except Exception as ex: - return public.returnMsg(False,"CONNECT_ERR"); + return public.returnMsg(False,"CONNECT_ERR") #检查是否安装任何 def CheckInstalled(self,get): - checks = ['nginx','apache','php','pure-ftpd','mysql']; + checks = ['nginx','apache','php','pure-ftpd','mysql'] import os for name in checks: filename = public.GetConfigValue('root_path') + "/server/" + name - if os.path.exists(filename): return True; - return False; + if os.path.exists(filename): return True + return False #取已安装软件列表 def GetInstalled(self,get): import system data = system.system().GetConcifInfo() - return data; + return data #取PHP配置 def GetPHPConfig(self,get): import re,json filename = public.GetConfigValue('setup_path') + '/php/' + get.version + '/etc/php.ini' - if not os.path.exists(filename): return public.returnMsg(False,'PHP_NOT_EXISTS'); - phpini = public.readFile(filename); + if not os.path.exists(filename): return public.returnMsg(False,'PHP_NOT_EXISTS') + phpini = public.readFile(filename) data = {} rep = "disable_functions\s*=\s{0,1}(.*)\n" - tmp = re.search(rep,phpini).groups(); - data['disable_functions'] = tmp[0]; + tmp = re.search(rep,phpini).groups() + data['disable_functions'] = tmp[0] rep = "upload_max_filesize\s*=\s*([0-9]+)(M|m|K|k)" tmp = re.search(rep,phpini).groups() @@ -549,17 +550,17 @@ def GetPHPConfig(self,get): else: data['pathinfo'] = True self.getCloudPHPExt(get) - phplib = json.loads(public.readFile('data/phplib.conf')); - libs = []; + phplib = json.loads(public.readFile('data/phplib.conf')) + libs = [] tasks = public.M('tasks').where("status!=?",('1',)).field('status,name').select() for lib in phplib: - lib['task'] = '1'; + lib['task'] = '1' for task in tasks: tmp = public.getStrBetween('[',']',task['name']) - if not tmp:continue; - tmp1 = tmp.split('-'); + if not tmp:continue + tmp1 = tmp.split('-') if tmp1[0].lower() == lib['name'].lower(): - lib['task'] = task['status']; + lib['task'] = task['status'] lib['phpversions'] = [] lib['phpversions'].append(tmp1[1]) if phpini.find(lib['check']) == -1: @@ -569,7 +570,7 @@ def GetPHPConfig(self,get): libs.append(lib) - data['libs'] = libs; + data['libs'] = libs return data #获取PHP扩展 @@ -577,33 +578,33 @@ def getCloudPHPExt(self,get): import json try: if 'php_ext' in session: return True - if not session.get('download_url'): session['download_url'] = 'http://download.bt.cn'; + if not session.get('download_url'): session['download_url'] = 'http://download.bt.cn' download_url = session['download_url'] + '/install/lib/phplib.json' tstr = public.httpGet(download_url) - data = json.loads(tstr); - if not data: return False; - public.writeFile('data/phplib.conf',json.dumps(data)); + data = json.loads(tstr) + if not data: return False + public.writeFile('data/phplib.conf',json.dumps(data)) session['php_ext'] = True - return True; + return True except: - return False; + return False #取PHPINFO信息 def GetPHPInfo(self,get): - sPath = '/www/server/phpinfo'; + sPath = '/www/server/phpinfo' if os.path.exists(sPath): - public.ExecShell("rm -rf " + sPath); + public.ExecShell("rm -rf " + sPath) p_file = '/dev/shm/phpinfo.php' - public.writeFile(p_file,''); + public.writeFile(p_file,'') phpinfo = public.request_php(get.version,'/phpinfo.php',p_file,'') if os.path.exists(p_file): os.remove(p_file) return phpinfo; #清理日志 def delClose(self,get): - public.M('logs').where('id>?',(0,)).delete(); - public.WriteLog('TYPE_CONFIG','LOG_CLOSE'); - return public.returnMsg(True,'LOG_CLOSE'); + public.M('logs').where('id>?',(0,)).delete() + public.WriteLog('TYPE_CONFIG','LOG_CLOSE') + return public.returnMsg(True,'LOG_CLOSE') def __get_webserver_conffile(self): if public.get_webserver() == 'nginx': @@ -805,132 +806,132 @@ def setPHPMyAdmin(self,get): import re; #try: filename = self.__get_webserver_conffile() - conf = public.readFile(filename); - if not conf: return public.returnMsg(False,'ERROR'); + conf = public.readFile(filename) + if not conf: return public.returnMsg(False,'ERROR') if hasattr(get,'port'): - mainPort = public.readFile('data/port.pl').strip(); + mainPort = public.readFile('data/port.pl').strip() rulePort = ['80','443','21','20','8080','8081','8089','11211','6379'] if get.port in rulePort: - return public.returnMsg(False,'AJAX_PHPMYADMIN_PORT_ERR'); + return public.returnMsg(False,'AJAX_PHPMYADMIN_PORT_ERR') if public.get_webserver() == 'nginx': rep = "listen\s+([0-9]+)\s*;" - oldPort = re.search(rep,conf).groups()[0]; - conf = re.sub(rep,'listen ' + get.port + ';\n',conf); + oldPort = re.search(rep,conf).groups()[0] + conf = re.sub(rep,'listen ' + get.port + ';\n',conf) else: - rep = "Listen\s+([0-9]+)\s*\n"; - oldPort = re.search(rep,conf).groups()[0]; - conf = re.sub(rep,"Listen " + get.port + "\n",conf,1); + rep = "Listen\s+([0-9]+)\s*\n" + oldPort = re.search(rep,conf).groups()[0] + conf = re.sub(rep,"Listen " + get.port + "\n",conf,1) rep = "VirtualHost\s+\*:[0-9]+" - conf = re.sub(rep,"VirtualHost *:" + get.port,conf,1); + conf = re.sub(rep,"VirtualHost *:" + get.port,conf,1) - if oldPort == get.port: return public.returnMsg(False,'SOFT_PHPVERSION_ERR_PORT'); + if oldPort == get.port: return public.returnMsg(False,'SOFT_PHPVERSION_ERR_PORT') - public.writeFile(filename,conf); + public.writeFile(filename,conf) import firewalls - get.ps = public.getMsg('SOFT_PHPVERSION_PS'); - fw = firewalls.firewalls(); + get.ps = public.getMsg('SOFT_PHPVERSION_PS') + fw = firewalls.firewalls() fw.AddAcceptPort(get); - public.serviceReload(); + public.serviceReload() public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_PORT',(get.port,)) - get.id = public.M('firewall').where('port=?',(oldPort,)).getField('id'); - get.port = oldPort; - fw.DelAcceptPort(get); - return public.returnMsg(True,'SET_PORT_SUCCESS'); + get.id = public.M('firewall').where('port=?',(oldPort,)).getField('id') + get.port = oldPort + fw.DelAcceptPort(get) + return public.returnMsg(True,'SET_PORT_SUCCESS') if hasattr(get,'phpversion'): if public.get_webserver() == 'nginx': - filename = public.GetConfigValue('setup_path') + '/nginx/conf/enable-php.conf'; - conf = public.readFile(filename); + filename = public.GetConfigValue('setup_path') + '/nginx/conf/enable-php.conf' + conf = public.readFile(filename) rep = "php-cgi.*\.sock" - conf = re.sub(rep,'php-cgi-' + get.phpversion + '.sock',conf,1); + conf = re.sub(rep,'php-cgi-' + get.phpversion + '.sock',conf,1) else: rep = "php-cgi.*\.sock" - conf = re.sub(rep,'php-cgi-' + get.phpversion + '.sock',conf,1); + conf = re.sub(rep,'php-cgi-' + get.phpversion + '.sock',conf,1) - public.writeFile(filename,conf); - public.serviceReload(); + public.writeFile(filename,conf) + public.serviceReload() public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_PHP',(get.phpversion,)) - return public.returnMsg(True,'SOFT_PHPVERSION_SET'); + return public.returnMsg(True,'SOFT_PHPVERSION_SET') if hasattr(get,'password'): import panelSite; if(get.password == 'close'): - return panelSite.panelSite().CloseHasPwd(get); + return panelSite.panelSite().CloseHasPwd(get) else: - return panelSite.panelSite().SetHasPwd(get); + return panelSite.panelSite().SetHasPwd(get) if hasattr(get,'status'): if conf.find(public.GetConfigValue('setup_path') + '/stop') != -1: - conf = conf.replace(public.GetConfigValue('setup_path') + '/stop',public.GetConfigValue('setup_path') + '/phpmyadmin'); + conf = conf.replace(public.GetConfigValue('setup_path') + '/stop',public.GetConfigValue('setup_path') + '/phpmyadmin') msg = public.getMsg('START') else: - conf = conf.replace(public.GetConfigValue('setup_path') + '/phpmyadmin',public.GetConfigValue('setup_path') + '/stop'); + conf = conf.replace(public.GetConfigValue('setup_path') + '/phpmyadmin',public.GetConfigValue('setup_path') + '/stop') msg = public.getMsg('STOP') - public.writeFile(filename,conf); - public.serviceReload(); + public.writeFile(filename,conf) + public.serviceReload() public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_STATUS',(msg,)) - return public.returnMsg(True,'SOFT_PHPMYADMIN_STATUS',(msg,)); + return public.returnMsg(True,'SOFT_PHPMYADMIN_STATUS',(msg,)) #except: #return public.returnMsg(False,'ERROR'); def ToPunycode(self,get): import re; - get.domain = get.domain.encode('utf8'); - tmp = get.domain.split('.'); - newdomain = ''; + get.domain = get.domain.encode('utf8') + tmp = get.domain.split('.') + newdomain = '' for dkey in tmp: #匹配非ascii字符 - match = re.search(u"[\x80-\xff]+",dkey); + match = re.search(u"[\x80-\xff]+",dkey) if not match: - newdomain += dkey + '.'; + newdomain += dkey + '.' else: newdomain += 'xn--' + dkey.decode('utf-8').encode('punycode') + '.' - return newdomain[0:-1]; + return newdomain[0:-1] #保存PHP排序 def phpSort(self,get): - if public.writeFile('/www/server/php/sort.pl',get.ssort): return public.returnMsg(True,'SUCCESS'); - return public.returnMsg(False,'ERROR'); + if public.writeFile('/www/server/php/sort.pl',get.ssort): return public.returnMsg(True,'SUCCESS') + return public.returnMsg(False,'ERROR') #获取广告代码 def GetAd(self,get): try: - return public.HttpGet(public.GetConfigValue('home') + '/Api/GetAD?name='+get.name + '&soc=' + get.soc); + return public.HttpGet(public.GetConfigValue('home') + '/Api/GetAD?name='+get.name + '&soc=' + get.soc) except: - return ''; + return '' #获取进度 def GetSpeed(self,get): - return public.getSpeed(); + return public.getSpeed() #检查登陆状态 def CheckLogin(self,get): - return True; + return True #获取警告标识 def GetWarning(self,get): warningFile = 'data/warning.json' - if not os.path.exists(warningFile): return public.returnMsg(False,'AJAX_WARNING_ERR'); + if not os.path.exists(warningFile): return public.returnMsg(False,'AJAX_WARNING_ERR') import json,time; - wlist = json.loads(public.readFile(warningFile)); - wlist['time'] = int(time.time()); - return wlist; + wlist = json.loads(public.readFile(warningFile)) + wlist['time'] = int(time.time()) + return wlist #设置警告标识 def SetWarning(self,get): - wlist = self.GetWarning(get); - id = int(get.id); + wlist = self.GetWarning(get) + id = int(get.id) import time,json; for i in xrange(len(wlist['data'])): if wlist['data'][i]['id'] == id: - wlist['data'][i]['ignore_count'] += 1; - wlist['data'][i]['ignore_time'] = int(time.time()); + wlist['data'][i]['ignore_count'] += 1 + wlist['data'][i]['ignore_time'] = int(time.time()) warningFile = 'data/warning.json' - public.writeFile(warningFile,json.dumps(wlist)); - return public.returnMsg(True,'SET_SUCCESS'); + public.writeFile(warningFile,json.dumps(wlist)) + return public.returnMsg(True,'SET_SUCCESS') #获取memcached状态 def GetMemcachedStatus(self,get): @@ -946,12 +947,12 @@ def GetMemcachedStatus(self,get): tn.write(b"quit\n") data = tn.read_all() if type(data) == bytes: data = data.decode('utf-8') - data = data.replace('STAT','').replace('END','').split("\n"); + data = data.replace('STAT','').replace('END','').split("\n") res = ['cmd_get','get_hits','get_misses','limit_maxbytes','curr_items','bytes','evictions','limit_maxbytes','bytes_written','bytes_read','curr_connections']; for d in data: - if len(d)<3: continue; - t = d.split(); - if not t[0] in res: continue; + if len(d)<3: continue + t = d.split() + if not t[0] in res: continue result[t[0]] = int(t[1]) result['hit'] = 1 if result['get_hits'] > 0 and result['cmd_get'] > 0: @@ -962,15 +963,15 @@ def GetMemcachedStatus(self,get): #设置memcached缓存大小 def SetMemcachedCache(self,get): import re - confFile = '/etc/init.d/memcached'; - conf = public.readFile(confFile); - conf = re.sub('IP=.+','IP='+get.ip,conf); - conf = re.sub('PORT=\d+','PORT='+get.port,conf); - conf = re.sub('MAXCONN=\d+','MAXCONN='+get.maxconn,conf); - conf = re.sub('CACHESIZE=\d+','CACHESIZE='+get.cachesize,conf); - public.writeFile(confFile,conf); - public.ExecShell(confFile + ' reload'); - return public.returnMsg(True,'SET_SUCCESS'); + confFile = '/etc/init.d/memcached' + conf = public.readFile(confFile) + conf = re.sub('IP=.+','IP='+get.ip,conf) + conf = re.sub('PORT=\d+','PORT='+get.port,conf) + conf = re.sub('MAXCONN=\d+','MAXCONN='+get.maxconn,conf) + conf = re.sub('CACHESIZE=\d+','CACHESIZE='+get.cachesize,conf) + public.writeFile(confFile,conf) + public.ExecShell(confFile + ' reload') + return public.returnMsg(True,'SET_SUCCESS') #取redis状态 def GetRedisStatus(self,get): @@ -997,32 +998,32 @@ def GetRedisStatus(self,get): 'keyspace_hits', #查找数据库键成功的次数 'keyspace_misses', #查找数据库键失败的次数 'latest_fork_usec' #最近一次 fork() 操作耗费的毫秒数 - ]; - data = data.split("\n"); + ] + data = data.split("\n") result = {} for d in data: - if len(d)<3: continue; - t = d.strip().split(':'); - if not t[0] in res: continue; - result[t[0]] = t[1]; - return result; + if len(d)<3: continue + t = d.strip().split(':') + if not t[0] in res: continue + result[t[0]] = t[1] + return result #取PHP-FPM日志 def GetFpmLogs(self,get): - path = '/www/server/php/' + get.version + '/var/log/php-fpm.log'; - if not os.path.exists(path): return public.returnMsg(False,'AJAX_LOG_FILR_NOT_EXISTS'); - return public.returnMsg(True,public.GetNumLines(path,1000)); + path = '/www/server/php/' + get.version + '/var/log/php-fpm.log' + if not os.path.exists(path): return public.returnMsg(False,'AJAX_LOG_FILR_NOT_EXISTS') + return public.returnMsg(True,public.GetNumLines(path,1000)) #取PHP慢日志 def GetFpmSlowLogs(self,get): - path = '/www/server/php/' + get.version + '/var/log/slow.log'; - if not os.path.exists(path): return public.returnMsg(False,'AJAX_LOG_FILR_NOT_EXISTS'); - return public.returnMsg(True,public.GetNumLines(path,1000)); + path = '/www/server/php/' + get.version + '/var/log/slow.log' + if not os.path.exists(path): return public.returnMsg(False,'AJAX_LOG_FILR_NOT_EXISTS') + return public.returnMsg(True,public.GetNumLines(path,1000)) #取指定日志 def GetOpeLogs(self,get): - if not os.path.exists(get.path): return public.returnMsg(False,'AJAX_LOG_FILR_NOT_EXISTS'); - return public.returnMsg(True,public.GetNumLines(get.path,1000)); + if not os.path.exists(get.path): return public.returnMsg(False,'AJAX_LOG_FILR_NOT_EXISTS') + return public.returnMsg(True,public.GetNumLines(get.path,1000)) #检查用户绑定是否正确 def check_user_auth(self,get): @@ -1035,7 +1036,7 @@ def check_user_auth(self,get): if os.path.exists(u_path): os.remove(u_path) return public.returnMsg(False,'宝塔帐户绑定已失效,请在[设置]页面重新绑定!') pdata = {'access_key':userInfo['access_key'],'secret_key':userInfo['secret_key']} - result = public.HttpPost(public.GetConfigValue('home') + '/api/panel/check_auth_key',pdata,3); + result = public.HttpPost(public.GetConfigValue('home') + '/api/panel/check_auth_key',pdata,3) if result == '0': if os.path.exists(u_path): os.remove(u_path) return public.returnMsg(False,'宝塔帐户绑定已失效,请在[设置]页面重新绑定!') diff --git a/class/crontab.py b/class/crontab.py index af83440c..544aa59f 100644 --- a/class/crontab.py +++ b/class/crontab.py @@ -431,11 +431,10 @@ def get_cron_file(self): cron_path = c_file if not os.path.exists(u_path): cron_path=c_file - if os.path.exists("/usr/bin/apt-get"): - cron_path = u_file - elif os.path.exists('/usr/bin/yum'): + if os.path.exists('/usr/bin/yum'): cron_path = c_file - + elif os.path.exists("/usr/bin/apt-get"): + cron_path = u_file if cron_path == u_file: if not os.path.exists(u_path): diff --git a/class/panelDnsapi.py b/class/panelDnsapi.py index cb8e0dc0..dd76516c 100644 --- a/class/panelDnsapi.py +++ b/class/panelDnsapi.py @@ -297,7 +297,8 @@ def sign(self, accessKeySecret, parameters): # '''签名方法 def percent_encode(encodeStr): encodeStr = str(encodeStr) if sys.version_info[0] == 3: - res = urlparse.quote(encodeStr, '') + import urllib.request + res = urllib.request.quote(encodeStr, '') else: res = urllib2.quote(encodeStr, '') res = res.replace('+', '%20')