Beispiel #1
0
 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
Beispiel #2
0
    def request_post(self,post):
        if not hasattr(post, 'username') or not hasattr(post, 'password'):
            return public.returnJson(False,'LOGIN_USER_EMPTY'),json_header
        
        self.error_num(False)
        if self.limit_address('?') < 1: return public.returnJson(False,'LOGIN_ERR_LIMIT'),json_header
        
        post.username = post.username.strip();
        password = public.md5(post.password.strip());
        sql = db.Sql();
        userInfo = sql.table('users').where("id=?",(1,)).field('id,username,password').find()
        m_code = cache.get('codeStr')
        if 'code' in session:
            if session['code'] and not 'is_verify_password' in session:
                if not hasattr(post, 'code'): return public.returnJson(False,'验证码不能为空!'),json_header
                if not public.checkCode(post.code):
                    public.WriteLog('TYPE_LOGIN','LOGIN_ERR_CODE',('****','****',public.GetClientIp()));
                    return public.returnJson(False,'CODE_ERR'),json_header
        try:
            s_pass = public.md5(public.md5(userInfo['password'] + '_bt.cn'))
            if userInfo['username'] != post.username or s_pass != password:
                public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',('****','******',public.GetClientIp()));
                num = self.limit_address('+');
                return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)),json_header
            _key_file = "/www/server/panel/data/two_step_auth.txt"
            if hasattr(post,'vcode'):
                if self.limit_address('?',v="vcode") < 1: return public.returnJson(False,'您多次验证失败,禁止10分钟'),json_header
                import pyotp
                secret_key = public.readFile(_key_file)
                if not secret_key:
                    return public.returnJson(False, "没有找到key,请尝试在命令行关闭谷歌验证后在开启"),json_header
                t = pyotp.TOTP(secret_key)
                result = t.verify(post.vcode)
                if not result:
                    if public.sync_date(): result = t.verify(post.vcode)
                    if not result:
                        num = self.limit_address('++',v="vcode")
                        return public.returnJson(False, '验证失败,您还可以尝试[{}]次!'.format(num)), json_header
                now = int(time.time())
                public.writeFile("/www/server/panel/data/dont_vcode_ip.txt",json.dumps({"client_ip":public.GetClientIp(),"add_time":now}))
                self.limit_address('--',v="vcode")
                return self._set_login_session(userInfo)

            acc_client_ip = self.check_two_step_auth()

            if not os.path.exists(_key_file) or acc_client_ip:
                return self._set_login_session(userInfo)
            self.limit_address('-')
            session['is_verify_password'] = True
            return "1"
        except Exception as ex:
            stringEx = str(ex)
            if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1: 
                os.system("rm -f /tmp/sess_*")
                os.system("rm -f /www/wwwlogs/*log")
                public.ServiceReload()
                return public.returnJson(False,'USER_INODE_ERR'),json_header
            public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',('****','******',public.GetClientIp()));
            num = self.limit_address('+');
            return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)),json_header
Beispiel #3
0
def test():
    qb = pQbClient()
    # magnet_link = "magnet:?xt=urn:btih:57a0ec92a61c60585f1b7a206a75798aa69285a5"
    # print qb.download_from_link(magnet_link)
    torrents = qb.torrents(filter='downloading')
    for torrent in torrents:
        print public.returnJson(False, torrent)
Beispiel #4
0
 def POST(self):
     get = web.input(backupfile={}, data=[])
     if not public.checkToken(get):
         return public.returnJson(False, '无效的Token!')
     if not self.CheckPlugin(get.name):
         return public.returnJson(False, '您没有权限访问当前插件!')
     return self.funObj()
Beispiel #5
0
    def setFileAccessApi(self):

        if public.isAppleSystem():
            return public.returnJson(True, '开发机不设置!')

        filename = request.form.get('filename', '').encode('utf-8')
        user = request.form.get('user', '').encode('utf-8')
        access = request.form.get('access', '755')
        sall = '-R'
        try:
            if not self.checkDir(filename):
                return public.returnJson(False, '请不要花样作死')

            if not os.path.exists(filename):
                return public.returnJson(False, '指定文件不存在!')

            os.system('chmod ' + sall + ' ' + access + " '" + filename + "'")
            os.system('chown ' + sall + ' ' + user +
                      ':' + user + " '" + filename + "'")
            msg = public.getInfo(
                '设置[{1}]权限为[{2}]所有者为[{3}]', (filename, access, user,))
            public.writeLog('文件管理', msg)
            return public.returnJson(True, '设置成功!')
        except:
            return public.returnJson(False, '设置失败!')
Beispiel #6
0
def panel_safe():
    get = get_input()
    pluginPath = 'plugin/safelogin'
    if hasattr(get, 'check'):
        if os.path.exists(pluginPath + '/safelogin_main.py'): return 'True'
        return 'False'
    get.data = check_token(get.data)
    if not get.data: return public.returnJson(False, 'INIT_CHECK_ERR')
    comm.setSession()
    comm.init()
    comm.checkWebType()
    comm.GetOS()
    sys.path.append(pluginPath)
    import safelogin_main
    reload(safelogin_main)
    s = safelogin_main.safelogin_main()
    if not hasattr(s, get.data['action']):
        return public.returnJson(False, 'INIT_FUN_NOT_EXISTS')
    defs = ('GetServerInfo', 'add_ssh_limit', 'remove_ssh_limit',
            'get_ssh_limit', 'get_login_log', 'get_panel_limit',
            'add_panel_limit', 'remove_panel_limit', 'close_ssh_limit',
            'close_panel_limit', 'get_system_info', 'get_service_info',
            'get_ssh_errorlogin')
    if not get.data['action'] in defs: return 'False'
    return public.getJson(eval('s.' + get.data['action'] + '(get)'))
Beispiel #7
0
def modUser():

    args = getArgs()
    data = checkArgs(args, ['username', 'password'])
    if not data[0]:
        return data[1]

    path = getPathFile()
    username = args['username']
    password = args['password']

    # sed -i "/^\<${user}\>/d" /etc/ppp/chap-secrets
    # echo "${user}    l2tpd    ${pass}       *" >> /etc/ppp/chap-secrets

    if public.isAppleSystem():
        public.execShell("sed -i .bak '/^\(" + username + "\)/d' " + path)
    else:
        public.execShell("sed -i '/^\(" + username + "\)/d' " + path)
    # print 'echo "' + username + "    l2tpd    " + password + "      *\" >>"
    # + path
    ret = public.execShell("echo \"" + username +
                           "    l2tpd    " + password + "       *\" >>" + path)
    if ret[1] == '':
        return public.returnJson(True, '修改成功!')
    return public.returnJson(False, '修改失败')
Beispiel #8
0
 def _set_login_session(self, userInfo):
     try:
         session['login'] = True
         session['username'] = userInfo['username']
         session['uid'] = userInfo['id']
         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())))
         self.set_request_token()
         self.login_token()
         return public.returnJson(True, 'LOGIN_SUCCESS'), json_header
     except Exception as ex:
         stringEx = str(ex)
         if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1:
             os.system("rm -f /tmp/sess_*")
             os.system("rm -f /www/wwwlogs/*log")
             public.ServiceReload()
             return public.returnJson(False, 'USER_INODE_ERR'), json_header
         public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS',
                         ('****', '******', public.GetClientIp()))
         num = self.limit_address('+')
         return public.returnJson(False, 'LOGIN_USER_ERR',
                                  (str(num), )), json_header
Beispiel #9
0
def getUserList():
    import re
    path = getPathFile()
    if not os.path.exists(path):
        return public.returnJson(False, '密码配置文件不存在!')
    conf = public.readFile(path)

    conf = re.sub('#(.*)\n', '', conf)

    if conf.strip() == '':
        return public.returnJson(True, 'ok', [])

    ulist = conf.strip().split('\n')

    user = []
    for line in ulist:
        line_info = {}
        line = re.match(r'(\w*)\s*(\w*)\s*(\w*)\s*(.*)',
                        line.strip(), re.M | re.I).groups()
        line_info['user'] = line[0]
        line_info['pwd'] = line[2]
        line_info['type'] = line[1]
        line_info['ip'] = line[3]
        user.append(line_info)

    return public.returnJson(True, 'ok', user)
Beispiel #10
0
 def _set_login_session(self, userInfo):
     try:
         session['login'] = True
         session['username'] = userInfo['username']
         session['uid'] = userInfo['id']
         session['login_user_agent'] = public.md5(
             request.headers.get('User-Agent', ''))
         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')
         session['session_timeout'] = time.time(
         ) + public.get_session_timeout()
         self.set_request_token()
         self.login_token()
         login_type = 'data/app_login.pl'
         if os.path.exists(login_type):
             os.remove(login_type)
         return public.returnJson(True, 'LOGIN_SUCCESS'), json_header
     except Exception as ex:
         stringEx = str(ex)
         if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1:
             public.ExecShell("rm -f /tmp/sess_*")
             public.ExecShell("rm -f /www/wwwlogs/*log")
             public.ServiceReload()
             return public.returnJson(False, 'USER_INODE_ERR'), json_header
         public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS',
                         ('****', '******', public.GetClientIp()))
         num = self.limit_address('+')
         return public.returnJson(False, 'LOGIN_USER_ERR',
                                  (str(num), )), json_header
Beispiel #11
0
 def GET(self):
     get = web.input()
     if not public.checkToken(get):
         return public.returnJson(False, '无效的Token!')
     if not self.CheckPlugin(get.name):
         return public.returnJson(False, '您没有权限访问当前插件!')
     return self.funObj()
Beispiel #12
0
 def logsApi(self):
     sid = request.form.get('id', '')
     echo = public.M('crontab').where("id=?", (sid, )).field('echo').find()
     logFile = public.getServerDir() + '/cron/' + echo['echo'] + '.log'
     if not os.path.exists(logFile):
         return public.returnJson(False, '当前日志为空!')
     log = public.getNumLines(logFile, 2000)
     return public.returnJson(True, log)
Beispiel #13
0
 def delLogsApi(self):
     sid = request.form.get('id', '')
     try:
         echo = public.M('crontab').where("id=?", (sid, )).getField('echo')
         logFile = public.getServerDir() + '/cron/' + echo + '.log'
         os.remove(logFile)
         return public.returnJson(True, '任务日志已清空!')
     except:
         return public.returnJson(False, '任务日志清空失败!')
Beispiel #14
0
    def modifyCrondApi(self):
        sid = request.form.get('id', '')
        iname = request.form.get('name', '')
        field_type = request.form.get('type', '')
        week = request.form.get('week', '')
        where1 = request.form.get('where1', '')
        hour = request.form.get('hour', '')
        minute = request.form.get('minute', '')
        save = request.form.get('save', '')
        backup_to = request.form.get('backup_to', '')
        stype = request.form.get('stype', '')
        sname = request.form.get('sname', '')
        sbody = request.form.get('sbody', '')
        urladdress = request.form.get('urladdress', '')

        if len(iname) < 1:
            return public.returnJson(False, '任务名称不能为空!')

        params = {
            'name': iname,
            'type': field_type,
            'week': week,
            'where1': where1,
            'hour': hour,
            'minute': minute,
            'save': save,
            'backup_to': backup_to,
            'stype': stype,
            'sname': sname,
            'sbody': sbody,
            'urladdress': urladdress,
        }
        cuonConfig, get, name = self.getCrondCycle(params)
        cronInfo = public.M('crontab').where('id=?',
                                             (sid, )).field(self.field).find()
        del (cronInfo['id'])
        del (cronInfo['addtime'])
        cronInfo['name'] = get['name']
        cronInfo['type'] = get['type']
        cronInfo['where1'] = get['where1']
        cronInfo['where_hour'] = get['hour']
        cronInfo['where_minute'] = get['minute']
        cronInfo['save'] = get['save']
        cronInfo['backup_to'] = get['backup_to']
        cronInfo['sbody'] = get['sbody']
        cronInfo['urladdress'] = get['urladdress']

        addData = public.M('crontab').where('id=?', (sid, )).save(
            'name,type,where1,where_hour,where_minute,save,backup_to,sbody,urladdress',
            (get['name'], field_type, get['where1'], get['hour'],
             get['minute'], get['save'], get['backup_to'], get['sbody'],
             get['urladdress']))
        self.removeForCrond(cronInfo['echo'])
        self.syncToCrond(cronInfo)
        public.writeLog('计划任务', '修改计划任务[' + cronInfo['name'] + ']成功')
        return public.returnJson(True, '修改成功')
Beispiel #15
0
def reload_mod():
    comReturn = comm.local()
    if comReturn: return comReturn
    args = get_input()
    mod_name = None
    if 'mod_name' in args:
        mod_name = args.mod_name
    result = public.reload_mod(mod_name)
    if result: return public.returnJson(True,result),json_header
    return public.returnJson(False,'Reload failure!'),json_header
Beispiel #16
0
    def getBody(self, path):
        if not os.path.exists(path):
            return public.returnJson(False, '文件不存在', (path,))

        if os.path.getsize(path) > 2097152:
            return public.returnJson(False, u'不能在线编辑大于2MB的文件!')

        fp = open(path, 'rb')
        data = {}
        data['status'] = True
        try:
            if fp:
                from chardet.universaldetector import UniversalDetector
                detector = UniversalDetector()
                srcBody = b""
                for line in fp.readlines():
                    detector.feed(line)
                    srcBody += line
                detector.close()
                char = detector.result
                data['encoding'] = char['encoding']
                if char['encoding'] == 'GB2312' or not char['encoding'] or char[
                        'encoding'] == 'TIS-620' or char['encoding'] == 'ISO-8859-9':
                    data['encoding'] = 'GBK'
                if char['encoding'] == 'ascii' or char[
                        'encoding'] == 'ISO-8859-1':
                    data['encoding'] = 'utf-8'
                if char['encoding'] == 'Big5':
                    data['encoding'] = 'BIG5'
                if not char['encoding'] in ['GBK', 'utf-8',
                                            'BIG5']:
                    data['encoding'] = 'utf-8'
                try:
                    if sys.version_info[0] == 2:
                        data['data'] = srcBody.decode(
                            data['encoding']).encode('utf-8', errors='ignore')
                    else:
                        data['data'] = srcBody.decode(data['encoding'])
                except:
                    data['encoding'] = char['encoding']
                    if sys.version_info[0] == 2:
                        data['data'] = srcBody.decode(
                            data['encoding']).encode('utf-8', errors='ignore')
                    else:
                        data['data'] = srcBody.decode(data['encoding'])
            else:
                if sys.version_info[0] == 2:
                    data['data'] = srcBody.decode('utf-8').encode('utf-8')
                else:
                    data['data'] = srcBody.decode('utf-8')
                data['encoding'] = u'utf-8'

            return public.returnJson(True, 'OK', data)
        except Exception as ex:
            return public.returnJson(False, u'文件编码不被兼容,无法正确读取文件!' + str(ex))
Beispiel #17
0
    def getLastBodyApi(self):
        path = request.form.get('path', '').encode('utf-8')
        line = request.form.get('line', '100')

        if not os.path.exists(path):
            return public.returnJson(False, '文件不存在', (path,))

        try:
            data = public.getNumLines(path, int(line))
            return public.returnJson(True, 'OK', data)
        except Exception as ex:
            return public.returnJson(False, u'无法正确读取文件!' + str(ex))
Beispiel #18
0
def addUser():
    if public.isAppleSystem():
        return public.returnJson(False, "Apple Computer does not support")

    args = getArgs()
    data = checkArgs(args, ['username'])
    if not data[0]:
        return data[1]
    ret = public.execShell('echo ' + args['username'] + '|l2tp -a')
    if ret[1] == '':
        return public.returnJson(True, '添加成功!:' + ret[0])
    return public.returnJson(False, '添加失败:' + ret[0])
Beispiel #19
0
    def batchPasteApi(self):
        path = request.form.get('path', '').encode('utf-8')
        stype = request.form.get('type', '').encode('utf-8')
        # filename = request.form.get('filename', '').encode('utf-8')
        import shutil
        if not self.checkDir(path):
            return public.returnJson(False, '请不要花样作死!')
        i = 0
        myfiles = json.loads(session['selected']['data'])
        l = len(myfiles)
        if stype == '1':
            for key in myfiles:
                i += 1
                public.writeSpeed(key, i, l)
                try:

                    sfile = session['selected'][
                        'path'] + '/' + key.encode('utf-8')
                    dfile = path + '/' + key.encode('utf-8')

                    if os.path.isdir(sfile):
                        shutil.copytree(sfile, dfile)
                    else:
                        shutil.copyfile(sfile, dfile)
                    stat = os.stat(sfile)
                    os.chown(dfile, stat.st_uid, stat.st_gid)
                except:
                    continue
            msg = public.getInfo('从[{1}]批量复制到[{2}]成功',
                                 (session['selected']['path'], path,))
            public.writeLog('文件管理', msg)
        else:
            for key in myfiles:
                try:
                    i += 1
                    public.writeSpeed(key, i, l)

                    sfile = session['selected'][
                        'path'] + '/' + key.encode('utf-8')
                    dfile = path + '/' + key.encode('utf-8')

                    shutil.move(sfile, dfile)
                except:
                    continue
            msg = public.getInfo('从[{1}]批量移动到[{2}]成功',
                                 (session['selected']['path'], path,))
            public.writeLog('文件管理', msg)
        public.writeSpeed(None, 0, 0)
        errorCount = len(myfiles) - i
        del(session['selected'])
        msg = public.getInfo('批量操作成功[{1}],失败[{2}]', (str(i), str(errorCount)))
        return public.returnJson(True, msg)
Beispiel #20
0
 def recycleBinApi(self):
     c = 'data/recycle_bin.pl'
     db = request.form.get('db', '').encode('utf-8')
     if db != '':
         c = 'data/recycle_bin_db.pl'
     if os.path.exists(c):
         os.remove(c)
         public.writeLog('文件管理', '已关闭回收站功能!')
         return public.returnJson(True, '已关闭回收站功能!')
     else:
         public.writeFile(c, 'True')
         public.writeLog('文件管理', '已开启回收站功能!')
         return public.returnJson(True, '已开启回收站功能!')
Beispiel #21
0
 def get_sk(self,):
     save_path = '/www/server/panel/config/api.json'
     if not os.path.exists(save_path): return redirect('/login')
     api_config = json.loads(public.ReadFile(save_path))
     if not api_config['open']: return redirect('/login')
     from BTPanel import get_input
     get = get_input()
     if not 'request_token' in get or not 'request_time' in get: return redirect('/login')
     client_ip = public.GetClientIp()
     if not client_ip in api_config['limit_addr']: return public.returnJson(False,'IP校验失败,您的访问IP为['+client_ip+']')
     request_token = public.md5(get.request_time + api_config['token'])
     if get.request_token == request_token: return False
     return public.returnJson(False,'密钥校验失败')
Beispiel #22
0
 def createDirApi(self):
     path = request.form.get('path', '').encode('utf-8')
     try:
         if not self.checkFileName(path):
             return public.returnJson(False, '目录名中不能包含特殊字符!')
         if os.path.exists(path):
             return public.returnJson(False, '指定目录已存在!')
         os.makedirs(path)
         self.setFileAccept(path)
         msg = public.getInfo('创建目录[{1}]成功!', (path,))
         public.writeLog('文件管理', msg)
         return public.returnJson(True, '目录创建成功!')
     except Exception as e:
         return public.returnJson(False, '目录创建失败!')
Beispiel #23
0
def panel_cloud():
    comReturn = comm.local()
    if comReturn: return comReturn
    get = get_input()
    if not os.path.exists('plugin/' + get.filename + '/' + get.filename +
                          '_main.py'):
        return public.returnJson(False, '指定插件不存在!'), json_header
    sys.path.append('plugin/' + get.filename)
    plugin_main = __import__(get.filename + '_main')
    reload(plugin_main)
    tmp = eval("plugin_main.%s_main()" % get.filename)
    if not hasattr(tmp, 'download_file'):
        return public.returnJson(False, '指定插件没有文件下载方法!'), json_header
    return redirect(tmp.download_file(get.name))
Beispiel #24
0
def panel_pluginApi():
    get = get_input()
    if not public.checkToken(get): return public.returnJson(False,'INIT_TOKEN_ERR');
    infoFile = 'plugin/' + get.name + '/info.json';
    if not os.path.exists(infoFile): return False;
    import json
    info = json.loads(public.readFile(infoFile));
    if not info['api']:  return public.returnJson(False,'INIT_PLU_ACC_ERR');

    import panelPlugin
    pluginObject = panelPlugin.panelPlugin()
    
    defs = ('install','unInstall','getPluginList','getPluginInfo','getPluginStatus','setPluginStatus','a','getCloudPlugin','getConfigHtml','savePluginSort')
    return publicObject(pluginObject,defs);
Beispiel #25
0
 def reRecycleBinApi(self):
     rPath = self.rPath
     path = request.form.get('path', '').encode('utf-8')
     dFile = path.replace('_mw_', '/').split('_t_')[0]
     try:
         import shutil
         shutil.move(rPath + path, dFile)
         msg = public.getInfo('移动文件[{1}]到回收站成功!', (dFile,))
         public.writeLog('文件管理', msg)
         return public.returnJson(True, '恢复成功!')
     except Exception as e:
         msg = public.getInfo('从回收站恢复[{1}]失败!', (dFile,))
         public.writeLog('文件管理', msg)
         return public.returnJson(False, '恢复失败!')
Beispiel #26
0
    def get_sk(self):
        save_path = '/www/server/panel/config/api.json'
        if not os.path.exists(save_path):
            return redirect('/login')
        try:
            api_config = json.loads(public.ReadFile(save_path))
        except:
            os.remove(save_path)
            return redirect('/login')

        if not api_config['open']:
            return redirect('/login')
        from BTPanel import get_input
        get = get_input()

        if not 'client_bind_token' in get:
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')
            client_ip = public.GetClientIp()
            if not client_ip in api_config['limit_addr']:
                return public.returnJson(False,
                                         'IP校验失败,您的访问IP为[' + client_ip + ']')
        else:
            a_file = '/dev/shm/' + get.client_bind_token
            if not os.path.exists(a_file):
                import panelApi
                if not panelApi.panelApi().get_app_find(get.client_bind_token):
                    return public.returnMsg(False, '未绑定的设备')
                public.writeFile(a_file, '')

            if not 'key' in api_config:
                return public.returnJson(False, '密钥校验失败')
            if not 'form_data' in get:
                return public.returnJson(False, '没有找到form_data数据')

            g.form_data = json.loads(
                public.aes_decrypt(get.form_data, api_config['key']))

            get = get_input()
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')
            g.is_aes = True
            g.aes_key = api_config['key']

        request_token = public.md5(get.request_time + api_config['token'])
        if get.request_token == request_token:
            return False
        return public.returnJson(False, '密钥校验失败')
Beispiel #27
0
    def get_sk(self):
        save_path = '/www/server/panel/config/api.json'
        if not os.path.exists(save_path):
            return redirect('/login')
        try:
            api_config = json.loads(public.ReadFile(save_path))
        except:
            os.remove(save_path)
            return redirect('/login')

        if not api_config['open']:
            return redirect('/login')
        from BTPanel import get_input
        get = get_input()

        if not 'client_bind_token' in get:
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')
            client_ip = public.GetClientIp()
            if not client_ip in api_config['limit_addr']:
                return public.returnJson(
                    False,
                    '%s[' % public.GetMsg("CHECK_IP_FALSE") + client_ip + ']')
        else:
            a_file = '/dev/shm/' + get.client_bind_token
            if not os.path.exists(a_file):
                import panelApi
                if not panelApi.panelApi().get_app_find(get.client_bind_token):
                    return public.returnMsg(False, 'Unbound device')
                public.writeFile(a_file, '')

            if not 'key' in api_config:
                return public.returnJson(False, 'Key verification failed')
            if not 'form_data' in get:
                return public.returnJson(False, 'No form_data data found')

            g.form_data = json.loads(
                public.aes_decrypt(get.form_data, api_config['key']))

            get = get_input()
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')
            g.is_aes = True
            g.aes_key = api_config['key']
        request_token = public.md5(get.request_time + api_config['token'])
        if get.request_token == request_token:
            return False
        return public.returnJson(False, 'SECRET_KEY_CHECK_FALSE')
Beispiel #28
0
 def pobject(self):
     get = web.input()
     pluginPath = '/www/server/panel/plugin/safelogin';
     if hasattr(get,'check'):
         if os.path.exists(pluginPath + '/safelogin_main.py'): return 'True';
         return 'False';
     get.data = self.check_token(get.data);
     if not get.data: return public.returnJson(False,'验证失败');
     sys.path.append(pluginPath);
     import safelogin_main;
     reload(safelogin_main);
     s = safelogin_main.safelogin_main();
     if not hasattr(s,get.data['action']): return public.returnJson(False,'方法不存在');
     defs = ('GetServerInfo','add_ssh_limit','remove_ssh_limit','get_ssh_limit','get_login_log','get_panel_limit','add_panel_limit','remove_panel_limit','close_ssh_limit','close_panel_limit','get_system_info','get_service_info','get_ssh_errorlogin')
     if not get.data['action'] in defs: return 'False';
     return public.getJson(eval('s.' + get.data['action'] + '(get)'));
Beispiel #29
0
 def startTaskApi(self):
     sid = request.form.get('id', '')
     echo = public.M('crontab').where('id=?', (sid, )).getField('echo')
     execstr = public.getServerDir() + '/cron/' + echo
     os.system('chmod +x ' + execstr)
     os.system('nohup ' + execstr + ' >> ' + execstr + '.log 2>&1 &')
     return public.returnJson(True, '任务已执行!')
Beispiel #30
0
 def getRecycleBinApi(self):
     rPath = self.rPath
     if not os.path.exists(rPath):
         os.system('mkdir -p ' + rPath)
     data = {}
     data['dirs'] = []
     data['files'] = []
     data['status'] = os.path.exists('data/recycle_bin.pl')
     data['status_db'] = os.path.exists('data/recycle_bin_db.pl')
     for file in os.listdir(rPath):
         try:
             tmp = {}
             fname = rPath + file
             tmp1 = file.split('_mw_')
             tmp2 = tmp1[len(tmp1) - 1].split('_t_')
             tmp['rname'] = file
             tmp['dname'] = file.replace('_mw_', '/').split('_t_')[0]
             tmp['name'] = tmp2[0]
             tmp['time'] = int(float(tmp2[1]))
             if os.path.islink(fname):
                 filePath = os.readlink(fname)
                 link = ' -> ' + filePath
                 if os.path.exists(filePath):
                     tmp['size'] = os.path.getsize(filePath)
                 else:
                     tmp['size'] = 0
             else:
                 tmp['size'] = os.path.getsize(fname)
             if os.path.isdir(fname):
                 data['dirs'].append(tmp)
             else:
                 data['files'].append(tmp)
         except:
             continue
     return public.returnJson(True, 'OK', data)
Beispiel #31
0
 def pobject(self):
     get = web.input()
     pluginPath = '/www/server/panel/plugin/safelogin';
     if hasattr(get,'check'):
         if os.path.exists(pluginPath + '/safelogin_main.py'): return 'True';
         return 'False';
     get.data = self.check_token(get.data);
     if not get.data: return public.returnJson(False,'验证失败');
     sys.path.append(pluginPath);
     import safelogin_main;
     reload(safelogin_main);
     s = safelogin_main.safelogin_main();
     if not hasattr(s,get.data['action']): return public.returnJson(False,'方法不存在');
     defs = ('GetServerInfo','add_ssh_limit','remove_ssh_limit','get_ssh_limit','get_login_log','get_panel_limit','add_panel_limit','remove_panel_limit','close_ssh_limit','close_panel_limit','get_system_info','get_service_info','get_ssh_errorlogin')
     if not get.data['action'] in defs: return 'False';
     return public.getJson(eval('s.' + get.data['action'] + '(get)'));
Beispiel #32
0
def publicObject(toObject,defs):
    get = web.input(zunfile = {},data = []);
    if hasattr(get,'path'):
            get.path = get.path.replace('//','/').replace('\\','/');
            if get.path.find('->') != -1:
                get.path = get.path.split('->')[0].strip();
    for key in defs:
        if key == get.action:
            fun = 'toObject.'+key+'(get)'
            if hasattr(get,'html'):
                return eval(fun)
            else:
                return public.getJson(eval(fun))
    return public.returnJson(False,'ARGS_ERR')
Beispiel #33
0
 def POST(self):
     post = web.input()
     web.ctx.session.lan = public.get_language();
     if not (hasattr(post, 'username') or hasattr(post, 'password') or hasattr(post, 'code')):
         return public.returnJson(False,'LOGIN_USER_EMPTY');
     
     if not self.errorNum(False): return public.returnJson(False,'防暴破机制已被启动,解除命令: rm -f /tmp/panelN*.pl');
     if self.limitAddress('?') < 1: return public.returnJson(False,'LOGIN_ERR_LIMIT');
     
     post.username = post.username.strip();
     password = public.md5(post.password.strip());
     sql = db.Sql();
     userInfo = sql.table('users').where("id=?",(1,)).field('id,username,password').find()
     if hasattr(web.ctx.session,'code'):
         if web.ctx.session.code:
             if not public.checkCode(post.code):
                 public.WriteLog('TYPE_LOGIN','LOGIN_ERR_CODE',(userInfo['username'],web.ctx.session.code,web.ctx.ip));
                 return public.returnJson(False,'CODE_ERR');
     try:
         if userInfo['username'] != post.username or userInfo['password'] != password:
             public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',(userInfo['username'],'******',web.ctx.ip));
             num = self.limitAddress('+');
             return public.returnJson(False,'LOGIN_USER_ERR',(str(num),));
         
         import time;
         login_temp = 'data/login.temp'
         if not os.path.exists(login_temp): public.writeFile(login_temp,'');
         login_logs = public.readFile(login_temp);
         public.writeFile(login_temp,login_logs + web.ctx.ip + '|' + str(int(time.time())) + ',');
         web.ctx.session.login = True;
         web.ctx.session.username = userInfo['username'];
         public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],web.ctx.ip));
         self.limitAddress('-');
         numFile = '/tmp/panelNum.pl';
         timeFile = '/tmp/panelNime.pl';
         if os.path.exists(numFile): os.remove(numFile);
         if os.path.exists(timeFile): os.remove(timeFile);
         return public.returnJson(True,'LOGIN_SUCCESS');
     except:
         public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',(userInfo['username'],'******',web.ctx.ip));
         num = self.limitAddress('+');
         return public.returnJson(False,'LOGIN_USER_ERR',(str(num),));
Beispiel #34
0
 def GET(self):
     get = web.input();
     if not public.checkToken(get): return public.returnJson(False,'无效的Token!');
     if not self.CheckPlugin(get.name): return public.returnJson(False,'您没有权限访问当前插件!');
     return self.funObj();
Beispiel #35
0
 def POST(self):
     get = web.input(backupfile={},data=[]);
     if not public.checkToken(get): return public.returnJson(False,'无效的Token!');
     if not self.CheckPlugin(get.name): return public.returnJson(False,'您没有权限访问当前插件!');
     return self.funObj();
Beispiel #36
0
 def POST(self):
     get = web.input(backup={},data=[]);
     public.writeFile('test.pl',get['backup'].file.read());
     return public.returnJson(True,'OK!')