def addDropAddressApi(self): import re port = request.form.get('port', '').strip() ps = request.form.get('ps', '').strip() rep = "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/\d{1,2})?$" if not re.search(rep, port): return mw.returnJson(False, '您输入的IP地址不合法!') address = port if mw.M('firewall').where("port=?", (address,)).count() > 0: return mw.returnJson(False, '您要放屏蔽的IP已存在屏蔽列表,无需重复处理!') if self.__isUfw: mw.execShell('ufw deny from ' + address + ' to any') else: if self.__isFirewalld: cmd = 'firewall-cmd --permanent --add-rich-rule=\'rule family=ipv4 source address="' + \ address + '" drop\'' mw.execShell(cmd) else: cmd = 'iptables -I INPUT -s ' + address + ' -j DROP' mw.execShell(cmd) msg = mw.getInfo('屏蔽IP[{1}]成功!', (address,)) mw.writeLog("防火墙管理", msg) addtime = time.strftime('%Y-%m-%d %X', time.localtime()) mw.M('firewall').add('port,ps,addtime', (address, ps, addtime)) self.firewallReload() return mw.returnJson(True, '添加成功!')
def removeTaskApi(self): mid = request.form.get('id', '').encode('utf-8') try: name = mw.M('tasks').where('id=?', (mid, )).getField('name') status = mw.M('tasks').where('id=?', (mid, )).getField('status') mw.M('tasks').delete(mid) if status == '-1': os.system( "kill `ps -ef |grep 'python panelSafe.pyc'|grep -v grep|grep -v panelExec|awk '{print $2}'`" ) os.system( "kill `ps aux | grep 'python task.pyc$'|awk '{print $2}'`") os.system(''' pids=`ps aux | grep 'sh'|grep -v grep|grep install|awk '{print $2}'` arr=($pids) for p in ${arr[@]} do kill -9 $p done ''') os.system('rm -f ' + name.replace('扫描目录[', '').replace(']', '') + '/scan.pl') isTask = mw.getRootDir() + '/tmp/panelTask.pl' mw.writeFile(isTask, 'True') os.system('/etc/init.d/mw start') except: os.system('/etc/init.d/mw start') return mw.returnJson(True, '任务已删除!')
def delPanelInfoApi(self): mid = request.form.get('id', '') isExists = mw.M('panel').where('id=?', (mid,)).count() if not isExists: return mw.returnJson(False, '指定面板资料不存在!') mw.M('panel').where('id=?', (mid,)).delete() return mw.returnJson(True, '删除成功!')
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 addAcceptPortApi(self): if not self.getFwStatus(): return mw.returnJson(False, '防火墙启动时,才能添加规则!') import re import time port = request.form.get('port', '').strip() ps = request.form.get('ps', '').strip() stype = request.form.get('type', '').strip() rep = "^\d{1,5}(:\d{1,5})?$" if not re.search(rep, port): return mw.returnJson(False, '端口范围不正确!') if mw.M('firewall').where("port=?", (port,)).count() > 0: return mw.returnJson(False, '您要放行的端口已存在,无需重复放行!') msg = mw.getInfo('放行端口[{1}]成功', (port,)) mw.writeLog("防火墙管理", msg) addtime = time.strftime('%Y-%m-%d %X', time.localtime()) mw.M('firewall').add('port,ps,addtime', (port, ps, addtime)) self.addAcceptPort(port) self.firewallReload() return mw.returnJson(True, '添加放行(' + port + ')端口成功!')
def initUserInfo(): data = mw.M('users').where('id=?', (1, )).getField('password') if data == '21232f297a57a5a743894a0e4a801fc3': pwd = mw.getRandomString(8).lower() file_pw = mw.getRunDir() + '/data/default.pl' mw.writeFile(file_pw, pwd) mw.M('users').where('id=?', (1, )).setField('password', mw.md5(pwd))
def pftpDB(): file = getServerDir() + '/ftps.db' if not os.path.exists(file): conn = mw.M('ftps').dbPos(getServerDir(), 'ftps') csql = mw.readFile(getPluginDir() + '/conf/ftps.sql') csql_list = csql.split(';') for index in range(len(csql_list)): conn.execute(csql_list[index], ()) else: conn = mw.M('ftps').dbPos(getServerDir(), 'ftps') return conn
def pSqliteDb(dbname='databases'): file = getServerDir() + '/mysql.db' name = 'mysql' if not os.path.exists(file): conn = mw.M(dbname).dbPos(getServerDir(), name) csql = mw.readFile(getPluginDir() + '/conf/mysql.sql') csql_list = csql.split(';') for index in range(len(csql_list)): conn.execute(csql_list[index], ()) else: conn = mw.M(dbname).dbPos(getServerDir(), name) return conn
def addPanelInfoApi(self): title = request.form.get('title', '') url = request.form.get('url', '') username = request.form.get('username', '') password = request.form.get('password', '') # 校验是还是重复 isAdd = mw.M('panel').where( 'title=? OR url=?', (title, url)).count() if isAdd: return mw.returnJson(False, '备注或面板地址重复!') isRe = mw.M('panel').add('title,url,username,password,click,addtime', (title, url, username, password, 0, int(time.time()))) if isRe: return mw.returnJson(True, '添加成功!') return mw.returnJson(False, '添加失败!')
def delAcceptPortApi(self): port = request.form.get('port', '').strip() sid = request.form.get('id', '').strip() mw_port = mw.readFile('data/port.pl') try: if(port == mw_port): return mw.returnJson(False, '失败,不能删除当前面板端口!') if self.__isUfw: mw.execShell('ufw delete allow ' + port + '/tcp') else: if self.__isFirewalld: mw.execShell( 'firewall-cmd --permanent --zone=public --remove-port=' + port + '/tcp') mw.execShell( 'firewall-cmd --permanent --zone=public --remove-port=' + port + '/udp') else: mw.execShell( 'iptables -D INPUT -p tcp -m state --state NEW -m tcp --dport ' + port + ' -j ACCEPT') msg = mw.getInfo('删除防火墙放行端口[{1}]成功!', (port,)) mw.writeLog("防火墙管理", msg) mw.M('firewall').where("id=?", (sid,)).delete() self.firewallReload() return mw.returnJson(True, '删除成功!') except Exception as e: return mw.returnJson(False, '删除失败!:' + str(e))
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 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 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 getLibConf(version): fname = mw.getServerDir() + '/php/' + version + '/etc/php.ini' if not os.path.exists(fname): return mw.returnJson(False, '指定PHP版本不存在!') phpini = mw.readFile(fname) libpath = getPluginDir() + '/versions/phplib.conf' phplib = json.loads(mw.readFile(libpath)) libs = [] tasks = mw.M('tasks').where("status!=?", ('1', )).field('status,name').select() for lib in phplib: lib['task'] = '1' for task in tasks: tmp = mw.getStrBetween('[', ']', task['name']) if not tmp: continue tmp1 = tmp.split('-') if tmp1[0].lower() == lib['name'].lower(): lib['task'] = task['status'] lib['phpversions'] = [] lib['phpversions'].append(tmp1[1]) if phpini.find(lib['check']) == -1: lib['status'] = False else: lib['status'] = True libs.append(lib) return mw.returnJson(True, 'OK!', libs)
def backupDatabaseAll(self, save): db_path = mw.getServerDir() + '/mysql' db_name = 'mysql' databases = mw.M('databases').dbPos(db_path, db_name).field('name').select() for database in databases: self.backupDatabase(database['name'], save)
def delDropAddressApi(self): if not self.getFwStatus(): return mw.returnJson(False, '防火墙启动时,才能删除规则!') port = request.form.get('port', '').strip() ps = request.form.get('ps', '').strip() sid = request.form.get('id', '').strip() address = port if self.__isUfw: mw.execShell('ufw delete deny from ' + address + ' to any') else: if self.__isFirewalld: mw.execShell( 'firewall-cmd --permanent --remove-rich-rule=\'rule family=ipv4 source address="' + address + '" drop\'') elif self.__isMac: pass else: cmd = 'iptables -D INPUT -s ' + address + ' -j DROP' mw.execShell(cmd) msg = mw.getInfo('解除IP[{1}]的屏蔽!', (address,)) mw.writeLog("防火墙管理", msg) mw.M('firewall').where("id=?", (sid,)).delete() self.firewallReload() return mw.returnJson(True, '删除成功!')
def uninstallOldApi(self): rundir = mw.getRunDir() name = request.form.get('name', '') version = request.form.get('version', '') if name.strip() == '': return mw.returnJson(False, "缺少插件名称!", ()) if version.strip() == '': return mw.returnJson(False, "缺少版本信息!", ()) infoJsonPos = self.__plugin_dir + '/' + name + '/' + 'info.json' 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"] \ + " uninstall " + version taskAdd = (None, '卸载[' + 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 projectListAsync(): import subprocess 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/' projectDir = mw.getWwwDir() + '/' + args['name'] if not checkUserExist(cmd, asyncUser): mw.execShell( cmd + 'gcloud auth activate-service-account --key-file ' + file) pName = contentObj['project_id'] setUserCmd = cmd + 'gcloud config set account ' + asyncUser setUserCmd += ' && ' + cmd + 'gcloud config set project ' + pName asyncCmd = setUserCmd + ' && cd ' + projectDir + \ ' && ' + cmd + 'gcloud app deploy << y' taskAdd = (None, 'gae[async]', 'execshell', '0', time.strftime('%Y-%m-%d %H:%M:%S'), asyncCmd) mw.M('tasks').add('id,name,type,status,addtime, execstr', taskAdd) return 'ok'
def getNetWorkIoData(self, start, end): # 取指定时间段的网络Io data = mw.M('network').dbfile('system').where( "addtime>=? AND addtime<=?", (start, end) ).field( 'id,up,down,total_up,total_down,down_packets,up_packets,addtime' ).order('id asc').select() return self.toAddtime(data)
def getList(self, page, limit): start = (page - 1) * limit _list = mw.M('firewall').field('id,port,ps,addtime').limit( str(start) + ',' + str(limit)).order('id desc').select() data = {} data['data'] = _list count = mw.M('firewall').count() _page = {} _page['count'] = count _page['tojs'] = 'showAccept' _page['p'] = page data['page'] = mw.getPage(_page) return mw.getJson(data)
def getDiskIoData(self, start, end): # 取指定时间段的磁盘Io data = mw.M('diskio').dbfile('system').where( "addtime>=? AND addtime<=?", (start, end) ).field( 'id,read_count,write_count,read_bytes,write_bytes,read_time,write_time,addtime' ).order('id asc').select() return self.toAddtime(data)
def setPanelInfoApi(self): title = request.form.get('title', '') url = request.form.get('url', '') username = request.form.get('username', '') password = request.form.get('password', '') mid = request.form.get('id', '') # 校验是还是重复 isSave = mw.M('panel').where( '(title=? OR url=?) AND id!=?', (title, url, mid)).count() if isSave: return mw.returnJson(False, '备注或面板地址重复!') # 更新到数据库 isRe = mw.M('panel').where('id=?', (mid,)).save( 'title,url,username,password', (title, url, username, password)) if isRe: return mw.returnJson(True, '修改成功!') return mw.returnJson(False, '修改失败!')
def setPasswordApi(self): password1 = request.form.get('password1', '') password2 = request.form.get('password2', '') if password1 != password2: return mw.returnJson(False, '两次输入的密码不一致,请重新输入!') if len(password1) < 5: return mw.returnJson(False, '用户密码不能小于5位!') mw.M('users').where("username=?", (session['username'],)).setField( 'password', mw.md5(password1.strip())) return mw.returnJson(True, '密码修改成功!')
def getSystemTotal(self, interval=1): # 取系统统计信息 data = self.getMemInfo() cpu = self.getCpuInfo(interval) data['cpuNum'] = cpu[1] data['cpuRealUsed'] = cpu[0] data['time'] = self.getBootTime() data['system'] = self.getSystemVersion() data['isuser'] = mw.M('users').where('username=?', ('admin', )).count() data['version'] = '0.0.1' return data
def doLogin(): username = request.form.get('username', '').strip() password = request.form.get('password', '').strip() code = request.form.get('code', '').strip() # print(session) if 'code' in session: if session['code'] != mw.md5(code): return mw.returnJson(False, '验证码错误,请重新输入!') userInfo = mw.M('users').where("id=?", (1, )).field('id,username,password').find() # print(userInfo) # print(password) password = mw.md5(password) # print('md5-pass', password) login_cache_count = 5 login_cache_limit = cache.get('login_cache_limit') filename = 'data/close.pl' if os.path.exists(filename): return mw.returnJson(False, '面板已经关闭!') if userInfo['username'] != username or userInfo['password'] != password: msg = "<a style='color: red'>密码错误</a>,帐号:{1},密码:{2},登录IP:{3}", (( '****', '******', request.remote_addr)) if login_cache_limit == None: login_cache_limit = 1 else: login_cache_limit = int(login_cache_limit) + 1 if login_cache_limit >= login_cache_count: mw.writeFile(filename, 'True') return mw.returnJson(False, '面板已经关闭!') cache.set('login_cache_limit', login_cache_limit, timeout=10000) login_cache_limit = cache.get('login_cache_limit') mw.writeLog('用户登录', mw.getInfo(msg)) return mw.returnJson( False, mw.getInfo("用户名或密码错误,您还可以尝试[{1}]次!", (str(login_cache_count - login_cache_limit)))) cache.delete('login_cache_limit') session['login'] = True session['username'] = userInfo['username'] #print('do_login', session) # fix 跳转时,数据消失,可能是跨域问题 mw.writeFile('data/api_login.txt', userInfo['username']) return mw.returnJson(True, '登录成功,正在跳转...')
def getLogList(self, page, limit, search=''): find_search = '' if search != '': find_search = "type like '%" + search + "%' or log like '%" + \ search + "%' or addtime like '%" + search + "%'" start = (page - 1) * limit _list = mw.M('logs').where(find_search, ()).field( 'id,type,log,addtime').limit(str(start) + ',' + str(limit)).order('id desc').select() data = {} data['data'] = _list count = mw.M('logs').where(find_search, ()).count() _page = {} _page['count'] = count _page['tojs'] = 'getLogs' _page['p'] = page data['page'] = mw.getPage(_page) return mw.getJson(data)
def setNameApi(self): name1 = request.form.get('name1', '') name2 = request.form.get('name2', '') if name1 != name2: return mw.returnJson(False, '两次输入的用户名不一致,请重新输入!') if len(name1) < 3: return mw.returnJson(False, '用户名长度不能少于3位') mw.M('users').where("username=?", (session['username'],)).setField( 'username', name1.strip()) session['username'] = name1 return mw.returnJson(True, '用户修改成功!')
def listApi(self): p = request.form.get('p', '1') limit = request.form.get('limit', '10').strip() search = request.form.get('search', '').strip() start = (int(p) - 1) * int(limit) limit_str = str(start) + ',' + str(limit) _list = mw.M('tasks').where('', ()).field( 'id,name,type,status,addtime,start,end').limit(limit_str).order('id desc').select() _ret = {} _ret['data'] = _list count = mw.M('tasks').where('', ()).count() _page = {} _page['count'] = count _page['tojs'] = 'remind' _page['p'] = p _ret['page'] = mw.getPage(_page) return mw.getJson(_ret)
def initDomainInfo(): data = [] path_domains = getJsonPath('domains') _list = mw.M('sites').field('id,name,path').where( 'status=?', ('1', )).order('id desc').select() for i in range(len(_list)): tmp = {} tmp['name'] = _list[i]['name'] tmp['path'] = _list[i]['path'] _list_domain = mw.M('domain').field('name').where( 'pid=?', (_list[i]['id'], )).order('id desc').select() tmp_j = [] for j in range(len(_list_domain)): tmp_j.append(_list_domain[j]['name']) tmp['domains'] = tmp_j data.append(tmp) cjson = mw.getJson(data) mw.writeFile(path_domains, cjson)
def installLib(version): args = getArgs() data = checkArgs(args, ['name']) if not data[0]: return data[1] name = args['name'] execstr = "cd " + getPluginDir() + '/versions/' + version + " && /bin/bash " + \ name + '.sh' + ' install ' + version rettime = time.strftime('%Y-%m-%d %H:%M:%S') insert_info = (None, '安装[' + name + '-' + version + ']', 'execshell', '0', rettime, execstr) mw.M('tasks').add('id,name,type,status,addtime,execstr', insert_info) return mw.returnJson(True, '已将下载任务添加到队列!')
def downloadFileApi(self): import db import time url = request.form.get('url', '').encode('utf-8') path = request.form.get('path', '').encode('utf-8') filename = request.form.get('filename', '').encode('utf-8') isTask = mw.getRootDir() + '/tmp/panelTask.pl' execstr = url + '|mw|' + path + '/' + filename mw.M('tasks').add('name,type,status,addtime,execstr', ('下载文件[' + filename + ']', 'download', '0', time.strftime('%Y-%m-%d %H:%M:%S'), execstr)) mw.writeFile(isTask, 'True') # self.setFileAccept(path + '/' + filename) return mw.returnJson(True, '已将下载任务添加到队列!')