def setPhpVer(): args = getArgs() if not 'phpver' in args: return 'phpver missing' cacheFile = getServerDir() + '/php.pl' mw.writeFile(cacheFile, args['phpver']) file_tpl = getPluginDir() + '/conf/xhprof.conf' file_run = getConf() centent = mw.readFile(file_tpl) centent = contentReplacePHP(centent, args['phpver']) mw.writeFile(file_run, centent) mw.restartWeb() return 'ok'
def addSiteRule(): args = getArgs() data = checkArgs(args, ['siteName', 'ruleName', 'ruleValue']) if not data[0]: return data[1] siteName = args['siteName'] siteRule = args['ruleName'] ruleValue = args['ruleValue'] path = getJsonPath('site') content = mw.readFile(path) content = json.loads(content) content[siteName][siteRule].append(ruleValue) cjson = mw.getJson(content) mw.writeFile(path, cjson) return mw.returnJson(True, '设置成功!')
def saveConf(): # 设置memcached缓存大小 import re confFile = getConf() print confFile try: args = getArgs() content = mw.readFile(confFile) content = re.sub('IP=.+', 'IP=' + args['ip'], content) content = re.sub('PORT=\d+', 'PORT=' + args['port'], content) content = re.sub('MAXCONN=\d+', 'MAXCONN=' + args['maxconn'], content) content = re.sub('CACHESIZE=\d+', 'CACHESIZE=' + args['cachesize'], content) mw.writeFile(confFile, content) restart() return 'save ok' except Exception as e: pass return 'fail'
def setObjOpen(): args = getArgs() data = checkArgs(args, ['obj']) if not data[0]: return data[1] conf = getJsonPath('config') content = mw.readFile(conf) cobj = json.loads(content) o = args['obj'] if cobj[o]["open"]: cobj[o]["open"] = False else: cobj[o]["open"] = True cjson = mw.getJson(cobj) mw.writeFile(conf, cjson) return mw.returnJson(True, '设置成功!')
def removeRule(): args = getArgs() data = checkArgs(args, ['ruleName', 'index']) if not data[0]: return data[1] index = int(args['index']) ruleName = args['ruleName'] fpath = getRuleJsonPath(ruleName) content = mw.readFile(fpath) content = json.loads(content) k = content[index] content.remove(k) cjson = mw.getJson(content) mw.writeFile(fpath, cjson) return mw.returnJson(True, '设置成功!', content)
def modFtpPort(): import re args = getArgs() if not 'port' in args: return 'port missing' try: port = args['port'] if int(port) < 1 or int(port) > 65535: return '端口范围不正确!' file = file = getServerDir() + '/etc/pure-ftpd.conf' conf = mw.readFile(file) rep = u"\n#?\s*Bind\s+[0-9]+\.[0-9]+\.[0-9]+\.+[0-9]+,([0-9]+)" # preg_match(rep,conf,tmp) conf = re.sub(rep, "\nBind 0.0.0.0," + port, conf) mw.writeFile(file, conf) restart() return 'ok' except Exception as ex: return str(ex)
def removeSiteRule(): args = getArgs() data = checkArgs(args, ['siteName', 'ruleName', 'index']) if not data[0]: return data[1] siteName = args['siteName'] siteRule = args['ruleName'] index = args['index'] path = getJsonPath('site') content = mw.readFile(path) content = json.loads(content) ruleValue = content[siteName][siteRule][int(index)] content[siteName][siteRule].remove(ruleValue) cjson = mw.getJson(content) mw.writeFile(path, cjson) return mw.returnJson(True, '设置成功!')
def getCsvnPwd(user): if app_debug: return user + '123' pwd_file = 'data/csvn_sync.pl' if os.path.exists(pwd_file): return mw.readFile(pwd_file).strip() import time cur_time = time.time() rand_pwd = mw.md5(str(cur_time)) pwd = user + rand_pwd[:5] htpasswd = getServerDir() + "/bin/htpasswd" svn_auth_file = getServerDir() + "/data/conf/svn_auth_file" cmd = htpasswd + ' -b ' + svn_auth_file + ' ' + user + ' ' + pwd data = mw.execShell(cmd) mw.writeFile(pwd_file, pwd) return pwd
def setDisableFunc(version): filename = mw.getServerDir() + '/php/' + version + '/etc/php.ini' if not os.path.exists(filename): return mw.returnJson(False, '指定PHP版本不存在!') args = getArgs() disable_functions = args['disable_functions'] phpini = mw.readFile(filename) rep = "disable_functions\s*=\s*.*\n" phpini = re.sub(rep, 'disable_functions = ' + disable_functions + "\n", phpini) msg = mw.getInfo('修改PHP-{1}的禁用函数为[{2}]', ( version, disable_functions, )) mw.writeLog('插件管理[PHP]', msg) mw.writeFile(filename, phpini) reload(version) return mw.returnJson(True, '设置成功!')
def sphinxConfParse(): file = getConf() bin_dir = getServerDir() content = mw.readFile(file) rep = 'index\s(.*)' sindex = re.findall(rep, content) indexlen = len(sindex) cmd = {} if indexlen > 0: cmd_index = [] cmd_delta = [] for x in range(indexlen): if sindex[x].find(':') != -1: cmd_delta.append(sindex[x]) else: cmd_index.append(sindex[x]) cmd['index'] = cmd_index cmd['delta'] = cmd_delta cmd['cmd'] = bin_dir + '/bin/bin/indexer -c ' + bin_dir + '/sphinx.conf' return cmd
def projectListCmd(): args = getArgs() if not 'name' in args: return 'missing name!' file = getServerDir() + '/' + args['name'] + '.json' if not os.path.exists(file): return 'not configured file!' content = mw.readFile(file) contentObj = json.loads(content) asyncUser = contentObj['client_email'] cmd = getServerDir() + '/google-cloud-sdk/bin/' pName = contentObj['project_id'] projectDir = mw.getWwwDir() + '/' + args['name'] setUserCmd = 'sudo ' + cmd + 'gcloud config set account ' + asyncUser setUserCmd += ' && sudo ' + cmd + 'gcloud config set project ' + pName asyncCmd = setUserCmd + ' && sudo cd ' + projectDir + \ ' && sudo ' + cmd + 'gcloud app deploy <<y' return asyncCmd
def runInfo(): # 获取memcached状态 import telnetlib import re port = getMemPort() try: tn = telnetlib.Telnet('127.0.0.1', int(port)) tn.write(b"stats\n") 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") result = {} 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 result[t[0]] = int(t[1]) result['hit'] = 1 if result['get_hits'] > 0 and result['cmd_get'] > 0: result['hit'] = float(result['get_hits']) / \ float(result['cmd_get']) * 100 conf = mw.readFile(getConf()) result['bind'] = re.search('IP=(.+)', conf).groups()[0] result['port'] = int(re.search('PORT=(\d+)', conf).groups()[0]) result['maxconn'] = int(re.search('MAXCONN=(\d+)', conf).groups()[0]) result['cachesize'] = int( re.search('CACHESIZE=(\d+)', conf).groups()[0]) return mw.getJson(result) except Exception as e: return mw.getJson({})
def delRec(): args = getArgs() data = checkArgs(args, ['name']) if not data[0]: return data[1] args_name = args['name'] cmd = "sed -i '_bak' '/" + args_name + "/d' " + appConfPwd() mw.execShell(cmd) try: path = appConf() content = mw.readFile(path) ret_list = getRecListData() ret_list_len = len(ret_list) is_end = False next_name = '' for x in range(ret_list_len): tmp = ret_list[x] if tmp['name'] == args_name: if x + 1 == ret_list_len: is_end = True else: next_name = ret_list[x + 1]['name'] reg = '' if is_end: reg = '\[' + args_name + '\]\s*(.*)' else: reg = '\[' + args_name + '\]\s*(.*)\s*\[' + next_name + '\]' conre = re.search(reg, content, re.S) content = content.replace( "[" + args_name + "]\n" + conre.groups()[0], '') mw.writeFile(path, content) return mw.returnJson(True, '删除成功!') except Exception as e: return mw.returnJson(False, '删除失败!')
def setMaxSize(version): args = getArgs() if not 'max' in args: return 'missing time args!' max = args['max'] if int(max) < 2: return mw.returnJson(False, '上传大小限制不能小于2MB!') path = getServerDir() + '/' + version + '/etc/php.ini' conf = mw.readFile(path) rep = u"\nupload_max_filesize\s*=\s*[0-9]+M" conf = re.sub(rep, u'\nupload_max_filesize = ' + max + 'M', conf) rep = u"\npost_max_size\s*=\s*[0-9]+M" conf = re.sub(rep, u'\npost_max_size = ' + max + 'M', conf) mw.writeFile(path, conf) msg = mw.getInfo('设置PHP-{1}最大上传大小为[{2}MB]!', ( version, max, )) mw.writeLog('插件管理[PHP]', msg) return mw.returnJson(True, '设置成功!')
def setSshStatusApi(self): if mw.isAppleSystem(): return mw.returnJson(True, '开发机不能操作!') status = request.form.get('status', '1').strip() version = mw.readFile('/etc/redhat-release') if int(status) == 1: msg = 'SSH服务已停用' act = 'stop' else: msg = 'SSH服务已启用' act = 'start' if not os.path.exists('/etc/redhat-release'): mw.execShell('service ssh ' + act) elif version.find(' 7.') != -1: mw.execShell("systemctl " + act + " sshd.service") else: mw.execShell("/etc/init.d/sshd " + act) mw.writeLog("防火墙管理", msg) return mw.returnJson(True, '操作成功!')
def getAllAclList(): svn_access_file = getServerDir() + '/data/conf/svn_access_file' aData = mw.readFile(svn_access_file) aData = re.sub('#.*', '', aData) aData = aData.strip().split('[')[1:] allAcl = {} for i in range(len(aData)): oData = aData[i].strip().split(']') name = oData[0].strip('/').strip(':') if oData[1] == '': allAcl[name] = [] else: user = oData[1].strip().split('\n') userAll = [] for iu in range(len(user)): ulist = user[iu].split('=') utmp = {} utmp['user'] = ulist[0].strip() utmp['acl'] = ulist[1].strip() userAll.append(utmp) allAcl[name] = userAll return allAcl
def initInitD(): script = mw.getRunDir() + '/scripts/init.d/mw.tpl' script_bin = mw.getRunDir() + '/scripts/init.d/mw' # if os.path.exists(script_bin): # return content = mw.readFile(script) content = content.replace("{$SERVER_PATH}", mw.getRunDir()) mw.writeFile(script_bin, content) mw.execShell('chmod +x ' + script_bin) mw.setHostAddr(mw.getLocalIp()) if not mw.isAppleSystem(): initd_bin = '/etc/init.d/mw' if not os.path.exists(initd_bin): import shutil shutil.copyfile(script_bin, initd_bin) mw.execShell('chmod +x ' + initd_bin) # 加入自启动 mw.execShell('chkconfig --add mw')
def setUserPwd(): args = getArgs() data = checkArgs(args, ['password', 'name']) if not data[0]: return data[1] newpassword = args['password'] username = args['name'] id = args['id'] try: pdb = pMysqlDb() psdb = pSqliteDb('databases') name = psdb.where('id=?', (id,)).getField('name') m_version = mw.readFile(getServerDir() + '/version.pl') if m_version.find('5.7') == 0 or m_version.find('8.0') == 0: tmp = pdb.query( "select Host from mysql.user where User='******' AND Host!='localhost'") accept = mapToList(tmp) pdb.execute( "update mysql.user set authentication_string='' where User='******'") result = pdb.execute( "ALTER USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username, newpassword)) for my_host in accept: pdb.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % ( username, my_host[0], newpassword)) else: result = pdb.execute("update mysql.user set Password=password('" + newpassword + "') where User='******'") isError = isSqlError(result) if isError != None: return isError pdb.execute("flush privileges") psdb.where("id=?", (id,)).setField('password', newpassword) return mw.returnJson(True, mw.getInfo('修改数据库[{1}]密码成功!', (name,))) except Exception as ex: # print str(ex) return mw.returnJson(False, mw.getInfo('修改数据库[{1}]密码失败!', (name,)))
def setCcConf(): args = getArgs() data = checkArgs(args, ['siteName', 'cycle', 'limit', 'endtime', 'is_open_global', 'increase']) if not data[0]: return data[1] conf = getJsonPath('config') content = mw.readFile(conf) cobj = json.loads(content) tmp = cobj['cc'] tmp['cycle'] = int(args['cycle']) tmp['limit'] = int(args['limit']) tmp['endtime'] = int(args['endtime']) tmp['is_open_global'] = args['is_open_global'] tmp['increase'] = args['increase'] cobj['cc'] = tmp cjson = mw.getJson(cobj) mw.writeFile(conf, cjson) return mw.returnJson(True, '设置成功!', [])
def setRuleState(): args = getArgs() data = checkArgs(args, ['ruleName', 'index']) if not data[0]: return data[1] index = int(args['index']) ruleName = args['ruleName'] fpath = getRuleJsonPath(ruleName) content = mw.readFile(fpath) content = json.loads(content) b = content[index][0] if b == 1: content[index][0] = 0 else: content[index][0] = 1 cjson = mw.getJson(content) mw.writeFile(fpath, cjson) return mw.returnJson(True, '设置成功!', content)
def getAllListPage(self, sType='0', page=1, pageSize=10): plugins_info = [] for dirinfo in os.listdir(self.__plugin_dir): if dirinfo[0:1] == '.': continue path = self.__plugin_dir + '/' + dirinfo if os.path.isdir(path): json_file = path + '/info.json' if os.path.exists(json_file): try: data = json.loads(mw.readFile(json_file)) tmp_data = self.makeList(data, sType) for index in range(len(tmp_data)): plugins_info.append(tmp_data[index]) except Exception as e: print(e) start = (page - 1) * pageSize end = start + pageSize _plugins_info = plugins_info[start:end] _plugins_info = self.checkStatusMThreads(_plugins_info) return (_plugins_info, len(plugins_info))
def getAllListProcess(self, sType='0'): plugins_info = [] tmp_list = [] manager = multiprocessing.Manager() return_dict = manager.dict() jobs = [] for dirinfo in os.listdir(self.__plugin_dir): if dirinfo[0:1] == '.': continue path = self.__plugin_dir + '/' + dirinfo if os.path.isdir(path): json_file = path + '/info.json' if os.path.exists(json_file): data = json.loads(mw.readFile(json_file)) if sType == '0': tmp_list.append(data) if (data['pid'] == sType): tmp_list.append(data) ntmp_list = range(len(tmp_list)) for i in ntmp_list: p = multiprocessing.Process(target=self.makeListProcess, args=(tmp_list[i], sType, i, return_dict)) jobs.append(p) p.start() for proc in jobs: proc.join() returnData = return_dict.values() for i in ntmp_list: for index in range(len(returnData[i])): plugins_info.append(returnData[i][index]) return plugins_info
def initReplace(version): makeOpenrestyConf() makePhpIni(version) initD_path = getServerDir() + '/init.d' if not os.path.exists(initD_path): os.mkdir(initD_path) file_bin = initD_path + '/php' + version if not os.path.exists(file_bin): file_tpl = getPluginDir() + '/init.d/php.tpl' if version == '52': file_tpl = getPluginDir() + '/init.d/php52.tpl' content = mw.readFile(file_tpl) content = contentReplace(content, version) mw.writeFile(file_bin, content) mw.execShell('chmod +x ' + file_bin) phpPrependFile(version) phpFpmWwwReplace(version) phpFpmReplace(version) session_path = '/tmp/session' if not os.path.exists(session_path): os.mkdir(session_path) if not mw.isAppleSystem(): mw.execShell('chown -R www:www ' + session_path) upload_path = '/tmp/upload' if not os.path.exists(upload_path): os.mkdir(upload_path) if not mw.isAppleSystem(): mw.execShell('chown -R www:www ' + upload_path) return file_bin
def setDbStatus(): gets = ['key_buffer_size', 'query_cache_size', 'tmp_table_size', 'max_heap_table_size', 'innodb_buffer_pool_size', 'innodb_log_buffer_size', 'max_connections', 'query_cache_type', 'table_open_cache', 'thread_cache_size', 'sort_buffer_size', 'read_buffer_size', 'read_rnd_buffer_size', 'join_buffer_size', 'thread_stack', 'binlog_cache_size'] emptys = ['max_connections', 'query_cache_type', 'thread_cache_size', 'table_open_cache'] args = getArgs() conFile = getConf() content = mw.readFile(conFile) n = 0 for g in gets: s = 'M' if n > 5: s = 'K' if g in emptys: s = '' rep = '\s*' + g + '\s*=\s*\d+(M|K|k|m|G)?\n' c = g + ' = ' + args[g] + s + '\n' if content.find(g) != -1: content = re.sub(rep, '\n' + c, content, 1) else: content = content.replace('[mysqld]\n', '[mysqld]\n' + c) n += 1 mw.writeFile(conFile, content) return mw.returnJson(True, '设置成功!')
def checkPHPVersion(version): try: url = 'http://127.0.0.1/phpfpm_status_' + version result = mw.httpGet(url) # print version,result # 检查nginx if result.find('Bad Gateway') != -1: return False if result.find('HTTP Error 404: Not Found') != -1: return False # 检查Web服务是否启动 if result.find('Connection refused') != -1: global isTask if os.path.exists(isTask): isStatus = mw.readFile(isTask) if isStatus == 'True': return True filename = '/etc/init.d/openresty' if os.path.exists(filename): os.system(filename + ' start') return True except: return True
def siteEdate(): # 网站到期处理 global oldEdate try: if not oldEdate: oldEdate = mw.readFile('data/edate.pl') if not oldEdate: oldEdate = '0000-00-00' mEdate = time.strftime('%Y-%m-%d', time.localtime()) if oldEdate == mEdate: return False edateSites = mw.M('sites').where('edate>? AND edate<? AND (status=? OR status=?)', ('0000-00-00', mEdate, 1, u'正在运行')).field('id,name').select() import panelSite siteObject = panelSite.panelSite() for site in edateSites: get = MyBad('') get.id = site['id'] get.name = site['name'] siteObject.SiteStop(get) oldEdate = mEdate mw.writeFile('data/edate.pl', mEdate) except: pass
def installApi(self): rundir = mw.getRunDir() name = request.form.get('name', '') version = request.form.get('version', '') mmsg = '安装' if hasattr(request.form, 'upgrade'): mtype = 'update' mmsg = 'upgrade' if name.strip() == '': return mw.returnJson(False, '缺少插件名称!', ()) if version.strip() == '': return mw.returnJson(False, '缺少版本信息!', ()) infoJsonPos = self.__plugin_dir + '/' + name + '/' + 'info.json' # print infoJsonPos if not os.path.exists(infoJsonPos): return mw.returnJson(False, '配置文件不存在!', ()) pluginInfo = json.loads(mw.readFile(infoJsonPos)) execstr = "cd " + os.getcwd() + "/plugins/" + \ name + " && /bin/bash " + pluginInfo["shell"] \ + " install " + version if mw.isAppleSystem(): print(execstr) taskAdd = (None, mmsg + '[' + name + '-' + version + ']', 'execshell', '0', time.strftime('%Y-%m-%d %H:%M:%S'), execstr) mw.M('tasks').add('id,name,type,status,addtime, execstr', taskAdd) return mw.returnJson(True, '已将安装任务添加到队列!')
def get(self): data = {} data['title'] = mw.getConfig('title') data['site_path'] = mw.getWwwDir() data['backup_path'] = mw.getBackupDir() sformat = 'date +"%Y-%m-%d %H:%M:%S %Z %z"' data['systemdate'] = mw.execShell(sformat)[0].strip() data['port'] = mw.getHostPort() data['ip'] = mw.getHostAddr() admin_path_file = 'data/admin_path.pl' if not os.path.exists(admin_path_file): data['admin_path'] = '/' else: data['admin_path'] = mw.readFile(admin_path_file) ipv6_file = 'data/ipv6.pl' if os.path.exists('data/ipv6.pl'): data['ipv6'] = 'checked' else: data['ipv6'] = '' ssl_file = 'data/ssl.pl' if os.path.exists('data/ssl.pl'): data['ssl'] = 'checked' else: data['ssl'] = '' data['site_count'] = mw.M('sites').count() data['username'] = mw.M('users').where( "id=?", (1,)).getField('username') return data
def getTaskSpeedApi(self): tempFile = os.getcwd() + '/tmp/panelExec.log' freshFile = os.getcwd() + '/tmp/panelFresh' find = mw.M('tasks').where( 'status=? OR status=?', ('-1', '0')).field('id,type,name,execstr').find() if not len(find): return mw.returnJson(False, '当前没有任务队列在执行-2!') isTask = os.getcwd() + '/tmp/panelTask.pl' mw.writeFile(isTask, 'True') echoMsg = {} echoMsg['name'] = find['name'] echoMsg['execstr'] = find['execstr'] if find['type'] == 'download': import json try: tmp = mw.readFile(tempFile) if len(tmp) < 10: return mw.returnJson(False, '当前没有任务队列在执行-3!') echoMsg['msg'] = json.loads(tmp) echoMsg['isDownload'] = True except: mw.M('tasks').where("id=?", (find['id'], )).save('status', ('0', )) return mw.returnJson(False, '当前没有任务队列在执行-4!') else: echoMsg['msg'] = mw.getLastLine(tempFile, 10) echoMsg['isDownload'] = False echoMsg['task'] = mw.M('tasks').where( "status!=?", ('1', )).field('id,status,name,type').order("id asc").select() return mw.getJson(echoMsg)
def getNetWorkApi(self): # 取网络流量信息 try: tmpfile = 'data/network.temp' networkIo = psutil.net_io_counters()[:4] if not os.path.exists(tmpfile): mw.writeFile( tmpfile, str(networkIo[0]) + '|' + str(networkIo[1]) + '|' + str(int(time.time()))) lastValue = mw.readFile(tmpfile).split('|') ntime = time.time() networkInfo = {} networkInfo['upTotal'] = networkIo[0] networkInfo['downTotal'] = networkIo[1] networkInfo['up'] = round( float(networkIo[0] - int(lastValue[0])) / 1024 / (ntime - int(lastValue[2])), 2) networkInfo['down'] = round( float(networkIo[1] - int(lastValue[1])) / 1024 / (ntime - int(lastValue[2])), 2) networkInfo['downPackets'] = networkIo[3] networkInfo['upPackets'] = networkIo[2] mw.writeFile( tmpfile, str(networkIo[0]) + '|' + str(networkIo[1]) + '|' + str(int(time.time()))) # networkInfo['cpu'] = self.GetCpuInfo(0.1) return networkInfo except: return None