Exemplo n.º 1
0
 def get_port(self):
     ret = public.ReadFile('/www/server/panel/data/port.pl')
     ret = int(public.ReadFile('/www/server/panel/data/port.pl'))
     if ret == 8888:
         return False
     else:
         return True
Exemplo n.º 2
0
    def __init__(self):
        if not os.path.exists('/www/backup/site_backup'):
            os.system('mkdir /www/backup/site_backup -p')
        if not os.path.exists('/www/backup/database_backup'):
            os.system('mkdir /www/backup/database_backup')

        if not os.path.exists(self._check_database):
            ret = []
            public.writeFile(self._check_database, json.dumps(ret))
        else:
            ret = public.ReadFile(self._check_database)
            self._check_database_data = json.loads(ret)
        if not os.path.exists(self._check_site):
            ret = []
            public.writeFile(self._check_site, json.dumps(ret))
        else:
            ret = public.ReadFile(self._check_site)
            self._check_site_data = json.loads(ret)
        if not os.path.exists(self._chekc_path):
            ret = []
            public.writeFile(self._chekc_path, json.dumps(ret))
        else:
            ret = public.ReadFile(self._chekc_path)
            self._check_path_data = json.loads(ret)

        #下载所需要的
        if not os.path.exists(self._down_path):
            ret = []
            public.writeFile(self._down_path, json.dumps(ret))
        else:
            ret = public.ReadFile(self._down_path)
            self._down_path_data = json.loads(ret)
Exemplo n.º 3
0
    def request_get(self,get):
        #if os.path.exists('/www/server/panel/install.pl'): raise redirect('/install');
        if not 'title' in session: session['title'] = public.getMsg('NAME')
        domain = public.readFile('data/domain.conf')
        
        if domain:
            if(public.GetHost().lower() != domain.strip().lower()): 
                errorStr = public.ReadFile('./BTPanel/templates/' + public.GetConfigValue('template') + '/error2.html')
                try:
                    errorStr = errorStr.format(public.getMsg('PAGE_ERR_TITLE'),public.getMsg('PAGE_ERR_DOMAIN_H1'),public.getMsg('PAGE_ERR_DOMAIN_P1'),public.getMsg('PAGE_ERR_DOMAIN_P2'),public.getMsg('PAGE_ERR_DOMAIN_P3'),public.getMsg('NAME'),public.getMsg('PAGE_ERR_HELP'))
                except IndexError:pass
                return errorStr
        if os.path.exists('data/limitip.conf'):
            iplist = public.readFile('data/limitip.conf')
            if iplist:
                iplist = iplist.strip()
                if not public.GetClientIp() in iplist.split(','):
                    errorStr = public.ReadFile('./BTPanel/templates/' + public.GetConfigValue('template') + '/error2.html')
                    try:
                        errorStr = errorStr.format(public.getMsg('PAGE_ERR_TITLE'),public.getMsg('PAGE_ERR_IP_H1'),public.getMsg('PAGE_ERR_IP_P1',(public.GetClientIp(),)),public.getMsg('PAGE_ERR_IP_P2'),public.getMsg('PAGE_ERR_IP_P3'),public.getMsg('NAME'),public.getMsg('PAGE_ERR_HELP'))
                    except IndexError:pass
                    return errorStr

        if 'login' in session:
            if session['login'] == True:
                return redirect('/')
        
        if not 'code' in session:
            session['code'] = False
        self.error_num(False)
Exemplo n.º 4
0
    def get_api_config(self):
        tmp = public.ReadFile(self.save_path)
        if not tmp or not os.path.exists(self.save_path):
            data = {"open": False, "token": "", "limit_addr": []}
            public.WriteFile(self.save_path, json.dumps(data))
            public.ExecShell("chmod 600 " + self.save_path)
            tmp = public.ReadFile(self.save_path)
        data = json.loads(tmp)

        is_save = False
        if not 'binds' in data:
            data['binds'] = []
            is_save = True

        if not 'apps' in data:
            data['apps'] = []
            is_save = True

        data['binds'] = sorted(data['binds'],
                               key=lambda x: x['time'],
                               reverse=True)
        if len(data['binds']) > 5:
            data['binds'] = data['binds'][:5]
            is_save = True

        if is_save:
            self.save_api_config(data)
        return data
Exemplo n.º 5
0
 def checkWebType(self):
     if os.path.exists(self.setupPath + '/nginx'):
         session['webserver'] = 'nginx'
     else:
         session['webserver'] = 'apache'
     if os.path.exists(self.setupPath+'/'+session['webserver']+'/version.pl'):
         session['webversion'] = public.ReadFile(self.setupPath+'/'+session['webserver']+'/version.pl').strip()
     filename = self.setupPath+'/data/phpmyadminDirName.pl'
     if os.path.exists(filename):
         session['phpmyadminDir'] = public.ReadFile(filename).strip()
Exemplo n.º 6
0
    def __init__(self):
        # QQ邮箱基础实例化
        if not os.path.exists(self.__mail_list_data):
            ret = []
            public.writeFile(self.__mail_list_data, json.dumps(ret))
        else:
            try:
                mail_data = json.loads(public.ReadFile(self.__mail_list_data))
                self.__mail_list = mail_data
            except:
                ret = []
                public.writeFile(self.__mail_list_data, json.dumps(ret))

        if not os.path.exists(self.__mail_config):
            ret = []
            public.writeFile(self.__mail_config, json.dumps(ret))
        else:
            try:
                qq_mail_info = json.loads(public.ReadFile(self.__mail_config))
                if 'qq_mail' in qq_mail_info and 'qq_stmp_pwd' in qq_mail_info and 'hosts' in qq_mail_info:
                    self.__qq_mail_user = qq_mail_info
            except:
                ret = []
                public.writeFile(self.__mail_config, json.dumps(ret))

        # 初始化钉钉
        if not os.path.exists(self.__dingding_config):
            ret = []
            public.writeFile(self.__dingding_config, json.dumps(ret))
        else:
            try:
                dingding_info = json.loads(
                    public.ReadFile(self.__dingding_config))
                if 'dingding_url' in dingding_info and 'isAtAll' in dingding_info and 'user' in dingding_info:
                    self.__dingding_info = dingding_info
            except:
                ret = []
                public.writeFile(self.__dingding_config, json.dumps(ret))

        # 初始化微信
        if not os.path.exists(self.__weixin_config):
            ret = []
            public.writeFile(self.__weixin_config, json.dumps(ret))
        else:
            try:
                weixin_info = json.loads(public.ReadFile(self.__weixin_config))
                if 'corpid' in weixin_info and 'corpsecret' in weixin_info and 'user_id' in weixin_info and 'agentid' in weixin_info:
                    self.__weixin_info = weixin_info
            except:
                ret = []
                public.writeFile(self.__weixin_config, json.dumps(ret))
Exemplo n.º 7
0
 def GetOS(self):
     if not 'server_os' in session:
         tmp = {}
         if os.path.exists('/etc/redhat-release'):
             tmp['x'] = 'RHEL';
             tmp['osname'] = public.ReadFile('/etc/redhat-release').split()[0];
         elif os.path.exists('/usr/bin/yum'):
             tmp['x'] = 'RHEL';
             tmp['osname'] = public.ReadFile('/etc/issue').split()[0];
         elif os.path.exists('/etc/issue'): 
             tmp['x'] = 'Debian';
             tmp['osname'] = public.ReadFile('/etc/issue').split()[0];
         session['server_os'] = tmp
         
Exemplo n.º 8
0
 def get_settings(self):
     qq_mail_info = json.loads(public.ReadFile(self.__mail_config))
     if len(qq_mail_info) == 0:
         user_mail = False
     else:
         user_mail = True
     dingding_info = json.loads(public.ReadFile(self.__dingding_config))
     if len(dingding_info) == 0:
         dingding = False
     else:
         dingding = True
     ret = {}
     ret['user_mail'] = {"user_name": user_mail, "mail_list": self.__mail_list, "info": self.get_user_mail()}
     ret['dingding'] = {"dingding": dingding, "info": self.get_dingding()}
     return ret
Exemplo n.º 9
0
 def checkWebType(self):
     if os.path.exists('/usr/local/lsws/bin/lswsctrl'):
         session['webserver'] = 'openlitespeed'
     elif os.path.exists(self.setupPath + '/apache'):
         session['webserver'] = 'apache'
     else:
         session['webserver'] = 'nginx'
     if os.path.exists(self.setupPath + '/' + session['webserver'] +
                       '/version.pl'):
         session['webversion'] = public.ReadFile(self.setupPath + '/' +
                                                 session['webserver'] +
                                                 '/version.pl').strip()
     filename = self.setupPath + '/data/phpmyadminDirName.pl'
     if os.path.exists(filename):
         session['phpmyadminDir'] = public.ReadFile(filename).strip()
Exemplo n.º 10
0
    def Renew_SSL(self, get):
        if not os.path.isfile("/www/server/panel/vhost/crontab.json"):
            return {"status": False, "msg": "当前没有可以续订的证书!"}
        cmd_list = json.loads(
            public.ReadFile("/www/server/panel/vhost/crontab.json"))
        import panelTask
        task = panelTask.bt_task()
        Renew = True
        for xt in task.get_task_list():
            if xt['status'] != 1: Renew = False
        if not Renew:
            return {"status": False, "msg": "当前有续订任务正在执行!"}
        for j in cmd_list:
            siteName = j['siteName']
            home_path = os.path.join("/www/server/panel/vhost/cert/", siteName)
            public.ExecShell("mkdir -p {}".format(home_path))
            public.ExecShell(
                '''cd {} && rm -rf  check_authorization_status_response Confirmation_verification domain_txt_dns_value.json apply_for_cert_issuance_response timeout_info'''
                .format(home_path))
            cmd = j['cmd']
            for x in task.get_task_list():
                if x['name'] == siteName:
                    get.id = x['id']
                    task.remove_task(get)  # 删除旧的任务
            task.create_task(siteName, 0, cmd)

        return {"status": True, "msg": "已将续订任务添加到队列!"}
Exemplo n.º 11
0
    def set_token(self, get):
        if 'request_token' in get:
            return public.returnMsg(False, 'CANT_SET_API_WIFTH_API')
        save_path = '/www/server/panel/config/api.json'
        data = json.loads(public.ReadFile(save_path))
        if get.t_type == '1':
            token = public.GetRandomString(32)
            data['token'] = public.md5(token)
            public.WriteLog('SET_API', 'REGENERATE_API_TOKEN')
        elif get.t_type == '2':
            data['open'] = not data['open']
            stats = {
                True: public.GetMsg("TURN_ON"),
                False: public.GetMsg("CLOSE")
            }
            public.WriteLog('SET_API', 'API_INTERFACE',
                            (stats[data['open']], ))
            token = stats[data['open']] + public.GetMsg("SUCCESS")
        elif get.t_type == '3':
            data['limit_addr'] = get.limit_addr.split('\n')
            public.WriteLog('SET_API', 'CHANGE_IP_LIMIT', (get.limit_addr))
            token = public.GetMsg("SAVE_SUCCESS")

        public.WriteFile(save_path, json.dumps(data))
        return public.returnMsg(True, token)
Exemplo n.º 12
0
 def setSession(self):
     session['menus'] = sorted(json.loads(
         public.ReadFile('config/menu.json')),
                               key=lambda x: x['sort'])
     session['yaer'] = datetime.now().year
     session['download_url'] = 'http://download.bt.cn'
     session["top_tips"] = public.GetMsg("TOP_TIPS")
     session["bt_help"] = public.GetMsg("BT_HELP")
     # session["manual"] = public.GetMsg("MANUAL")
     session["download"] = public.GetMsg("DOWNLOAD")
     if not 'brand' in session:
         session['brand'] = public.GetConfigValue('brand')
         session['product'] = public.GetConfigValue('product')
         session['rootPath'] = '/www'
         session['download_url'] = 'http://download.bt.cn'
         session['setupPath'] = session['rootPath'] + '/server'
         session['logsPath'] = '/www/wwwlogs'
         session['yaer'] = datetime.now().year
     if not 'menu' in session:
         session['menu'] = public.GetLan('menu')
     if not 'lan' in session:
         session['lan'] = public.GetLanguage()
     if not 'home' in session:
         session['home'] = 'https://console.aapanel.com'
     return None
Exemplo n.º 13
0
    def request_tmp(self,get):
        try:
            if not hasattr(get,'tmp_token'): return public.returnJson(False,'错误的参数!'),json_header
            if len(get.tmp_token) != 64: return public.returnJson(False,'错误的参数!'),json_header
            if not re.match(r"^\w+$",get.tmp_token):return public.returnJson(False,'错误的参数!'),json_header

            save_path = '/www/server/panel/config/api.json'
            data = json.loads(public.ReadFile(save_path))
            if not 'tmp_token' in data or not 'tmp_time' in data: return public.returnJson(False,'验证失败!'),json_header
            if (time.time() - data['tmp_time']) > 120: return public.returnJson(False,'过期的Token'),json_header
            if get.tmp_token != data['tmp_token']: return public.returnJson(False,'错误的Token'),json_header
            userInfo = public.M('users').where("id=?",(1,)).field('id,username').find()
            session['login'] = True
            session['username'] = userInfo['username']
            session['tmp_login'] = True
            public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT'))))
            self.limit_address('-')
            cache.delete('panelNum')
            cache.delete('dologin')
            sess_input_path = 'data/session_last.pl'
            public.writeFile(sess_input_path,str(int(time.time())))
            del(data['tmp_token'])
            del(data['tmp_time'])
            public.writeFile(save_path,json.dumps(data))
            self.set_request_token()
            self.login_token()
            self.set_cdn_host(get)
            return redirect('/')
        except:
            return public.returnJson(False,'登录失败,' + public.get_error_info()),json_header
Exemplo n.º 14
0
    def renew_lets_ssl(self):        
        cpath = self.setupPath + '/panel/vhost/cert/crontab.json'
        if not os.path.exists(cpath):  
            print("|-当前没有可以续订的证书. " );        
        else:
            old_list = json.loads(public.ReadFile(cpath))    
            print('=======================================================================')
            print('|-%s 共计[%s]续签证书任务.' % (time.strftime('%Y-%m-%d %X',time.localtime()),len(old_list)))                        
            cron_list = self.get_renew_lets_bytimeout(old_list)

            tlist = []
            for siteName in old_list:                 
                if not siteName in cron_list: tlist.append(siteName)
            print('|-[%s]未到期或网站未使用Let\'s Encrypt证书.' % (','.join(tlist)))
            print('|-%s 等待续签[%s].' % (time.strftime('%Y-%m-%d %X',time.localtime()),len(cron_list)))
            
            sucess_list  = []
            err_list = []
            for siteName in cron_list:
                data = cron_list[siteName]
                ret = self.renew_lest_cert(data)
                if ret['status']:
                    sucess_list.append(siteName)
                else:
                    err_list.append({"siteName":siteName,"msg":ret['msg']})
            print("|-任务执行完毕,共需续订[%s],续订成功[%s],续订失败[%s]. " % (len(cron_list),len(sucess_list),len(err_list)));        
            if len(sucess_list) > 0:       
                print("|-续订成功:%s" % (','.join(sucess_list)))
            if len(err_list) > 0:       
                print("|-续订失败:")
                for x in err_list:
                    print("    %s ->> %s" % (x['siteName'],x['msg']))

            print('=======================================================================')
            print(" ");
Exemplo n.º 15
0
    def renew_lets_ssl(self):        
        cpath = self.setupPath + '/panel/vhost/cert/crontab.json'
        if not os.path.exists(cpath):  
            print("|-There are currently no certificates to renew." );
        else:
            old_list = json.loads(public.ReadFile(cpath))    
            print('=======================================================================')
            print('|-%s Total [%s] renewal of visa tasks' % (time.strftime('%Y-%m-%d %X',time.localtime()),len(old_list)))
            cron_list = self.get_renew_lets_bytimeout(old_list)

            tlist = []
            for siteName in old_list:                 
                if not siteName in cron_list: tlist.append(siteName)
            print('|-[%s]Not expired or the site does not use the Let\'s Encrypt certificate.' % (','.join(tlist)))
            print('|-%s Waiting for renewal[%s].' % (time.strftime('%Y-%m-%d %X',time.localtime()),len(cron_list)))
            
            sucess_list  = []
            err_list = []
            for siteName in cron_list:
                data = cron_list[siteName]
                ret = self.renew_lest_cert(data)
                if ret['status']:
                    sucess_list.append(siteName)
                else:
                    err_list.append({"siteName":siteName,"msg":ret['msg']})
            print("|-After the task is completed, a total of renewals are required.[%s], renewal success [%s], renewal failed [%s]. " % (len(cron_list),len(sucess_list),len(err_list)));
            if len(sucess_list) > 0:       
                print("|-Renewal success:%s" % (','.join(sucess_list)))
            if len(err_list) > 0:       
                print("|-Renewal failed:")
                for x in err_list:
                    print("    %s ->> %s" % (x['siteName'],x['msg']))

            print('=======================================================================')
            print(" ");
Exemplo n.º 16
0
 def get_config(self, args):  # 获取配置文件信息
     # 处理前端传过来的参数
     args = self.processing_parameter(args)
     config_file_path = self.get_data_directory(args)['data'] + "/postgresql.conf"
     config_file_info = public.ReadFile(config_file_path.strip(), mode='r')
     # 返回数据到前端
     return {'data': config_file_info, "status": True}
Exemplo n.º 17
0
 def del_pgsql_db(self, args):  # 删除数据库
     del_info = ''
     args = self.processing_parameter(args)  # 处理前端传过来的参数
     port = self.get_port(args)['data']
     database = args.database
     del_bak = args.del_bak
     if int(del_bak) == 1:
         public.ExecShell("rm -rf {}_*".format(os.path.join(self.db_back_dir, database)))
         del_info += '删除备份文件成功  '
     public.ExecShell('''echo "drop database {};"|su - postgres -c "/www/server/pgsql/bin/psql  -p {} " '''.format(database, port))
     dbuser_info_path = self.dbuser_info_path
     dbuser_info = ''
     if os.path.isfile(dbuser_info_path):
         with open(dbuser_info_path) as f:
             for i in f:
                 if not i.strip(): continue
                 if json.loads(i)['database'] == database:
                     public.ExecShell('''echo "drop user {};"|su - postgres -c "/www/server/pgsql/bin/psql  -p {} " '''.format(json.loads(i)['username'], port))
                     continue
                 dbuser_info += i
     public.WriteFile(dbuser_info_path, dbuser_info, mode='w')
     # 删除客户端认证相关配置
     config_file_path = self.get_data_directory(args)['data'] + "/pg_hba.conf"
     old_config = public.ReadFile(config_file_path)
     new_config = re.sub(r'host\s*{}.*'.format(database), '', old_config).strip()
     public.WriteFile(config_file_path, new_config)
     public.ExecShell("/etc/init.d/pgsql reload")
     # 返回数据到前端
     return {'data': del_info + "删除数据库成功", "status": True}
Exemplo n.º 18
0
 def get_data_directory(self, args):  # 获取储存路径
     if os.path.isfile("/www/server/pgsql/data_directory"):
         data_directory = public.ReadFile("/www/server/pgsql/data_directory", mode='r')
     else:
         data_directory = "/www/server/pgsql/data"
     # 返回数据到前端
     return {'data': data_directory.strip(), "status": True}
Exemplo n.º 19
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
Exemplo n.º 20
0
    def Nginx_Apache_security(self):
        ret = []
        Nginx_Get_version = {
            'id': 70,
            "type": "file",
            "name": "Nginx 版本泄露",
            "harm": "低",
            'level': "1",
            "repaired": "0",
            "file": '/www/server/nginx/conf/nginx.conf',
            "Suggestions": "加固建议, 在%s expose_php的值修改为Off中修改" % ('/www/server/nginx/conf/nginx.conf'),
            "repair": "expose_php = Off",
            "rule": [
                {"re": "server_tokens\s*(.+)", "check": {"type": "string", "value": ['off;']}}]
        }
        if not self.check_san_baseline(Nginx_Get_version):
            ret.append(Nginx_Get_version)
        if os.path.exists('/www/server/nginx/version.pl'):
            ret2 = public.ReadFile('/www/server/nginx/version.pl')
            if ret2 == '1.8':
                Nginx_Get_version = {
                    'id': 71,
                    "type": "file",
                    'level': "1",
                    "repaired": "0",
                    "name": "Nginx 版本过低",
                    "harm": "低",
                    "file": '/www/server/nginx/conf/nginx.conf',
                    "Suggestions": "加固建议, 升级至最新版的Nginx 软件",
                    "repair": "例如:Nignx1.17 或者Nginx1.16",
                }
                ret.append(Nginx_Get_version)

        return ret
Exemplo n.º 21
0
 def stop_jian(self,get):
     data = public.ReadFile('/etc/bashrc')
     if re.search('{}\/www\/server\/panel\/class\/ssh_security.py'.format(".*python\s+"), data):
         public.WriteFile('/etc/bashrc',re.sub('\n.*python\s+\/www\/server\/panel\/class\/ssh_security.py.*','',data))
         return public.returnMsg(True, 'Closed successfully')
     else:
         return public.returnMsg(True, 'Closed successfully')
Exemplo n.º 22
0
 def checkLimitIp(self):
     if os.path.exists('data/limitip.conf'):
         iplist = public.ReadFile('data/limitip.conf')
         if iplist:
             iplist = iplist.strip()
             if not request.remote_addr in iplist.split(','):
                 return redirect('/login')
Exemplo n.º 23
0
 def get_jian(self, get):
     data = public.ReadFile('/etc/bashrc')
     if re.search('python /www/server/panel/class/ssh_security.py login',
                  data):
         return public.returnMsg(True, '1')
     else:
         return public.returnMsg(False, '1')
Exemplo n.º 24
0
 def checkDomain(self):
     try:
         api_check = True
         if not 'login' in session: 
             api_check = self.get_sk()
             if api_check: return api_check
         else:
             if session['login'] == False: return redirect('/login')
         tmp = public.GetHost()
         domain = public.ReadFile('data/domain.conf')
         if domain:
             if(tmp.strip().lower() != domain.strip().lower()): return redirect('/login')
         if api_check:
             try:
                 sess_out_path = 'data/session_timeout.pl'
                 sess_input_path = 'data/session_last.pl'
                 if not os.path.exists(sess_out_path): public.writeFile(sess_out_path,'86400')
                 if not os.path.exists(sess_input_path): public.writeFile(sess_input_path,str(int(time.time())))
                 session_timeout = int(public.readFile(sess_out_path))
                 session_last = int(public.readFile(sess_input_path))
                 if time.time() - session_last > session_timeout: 
                     os.remove(sess_input_path)
                     session['login'] = False;
                     cache.set('dologin',True)
                     return redirect('/login')
                 public.writeFile(sess_input_path,str(int(time.time())))
             except:pass
     except:
         return redirect('/login')
Exemplo n.º 25
0
 def checkLimitIp(self):
     if os.path.exists('data/limitip.conf'):
         iplist = public.ReadFile('data/limitip.conf')
         if iplist:
             iplist = iplist.strip()
             if not public.GetClientIp() in iplist.split(','):
                 return redirect('/login')
Exemplo n.º 26
0
 def stop_jian(self,get):
     data = public.ReadFile('/etc/bashrc')
     if re.search('python /www/server/panel/class/ssh_security.py', data):
         public.WriteFile('/etc/bashrc',data.replace('python /www/server/panel/class/ssh_security.py login',''))
         return public.returnMsg(True, 'Closed successfully')
     else:
         return public.returnMsg(True, 'Closed successfully')
Exemplo n.º 27
0
 def check_san_baseline(self, base_json):
     if base_json['type'] == 'file':
         if 'check_file' in base_json:
             if not os.path.exists(base_json['check_file']):
                 return False
         else:
             if os.path.exists(base_json['file']):
                 ret = public.ReadFile(base_json['file'])
                 for i in base_json['rule']:
                     valuse = re.findall(i['re'], ret)
                     print(valuse)
                     if i['check']['type'] == 'number':
                         if not valuse: return False
                         if not valuse[0]: return False
                         valuse = int(valuse[0])
                         if valuse > i['check']['min'] and valuse < i['check']['max']:
                             return True
                         else:
                             return False
                     elif i['check']['type'] == 'string':
                         if not valuse: return False
                         if not valuse[0]: return False
                         valuse = valuse[0]
                         print(valuse)
                         if valuse in i['check']['value']:
                             return True
                         else:
                             return False
             return True
Exemplo n.º 28
0
    def renew_lets_ssl(self, get):
        if not os.path.exists('vhost/cert/crontab.json'):
            return public.returnMsg(False, '当前没有可以续订的证书!')

        old_list = json.loads(public.ReadFile("vhost/cert/crontab.json"))
        cron_list = old_list
        if hasattr(get, 'siteName'):
            if not get.siteName in old_list:
                return public.returnMsg(False, '当前网站没有可以续订的证书.')
            cron_list = {}
            cron_list[get.siteName] = old_list[get.siteName]

        import panelLets
        lets = panelLets.panelLets()

        result = {}
        result['status'] = True
        result['sucess_list'] = []
        result['err_list'] = []
        for siteName in cron_list:
            data = cron_list[siteName]
            ret = lets.renew_lest_cert(data)
            if ret['status']:
                result['sucess_list'].append(siteName)
            else:
                result['err_list'].append({
                    "siteName": siteName,
                    "msg": ret['msg']
                })
        return result
Exemplo n.º 29
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()
        client_ip = public.GetClientIp()
        if not 'client_bind_token' in get:
            if not 'request_token' in get or not 'request_time' in get:
                return redirect('/login')

            num_key = client_ip + '_api'
            if not public.get_error_num(num_key,20):
                return public.returnJson(False,'AUTH_FAILED1')


            if not client_ip in api_config['limit_addr']:
                public.set_error_num(num_key)
                return public.returnJson(False,'%s[' % public.GetMsg("AUTH_FAILED1")+client_ip+']')
        else:
            num_key = client_ip + '_app'
            if not public.get_error_num(num_key,20):
                return public.returnJson(False,'AUTH_FAILED1')
            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):
                    public.set_error_num(num_key)
                    return public.returnJson(False,'UNBOUND_DEVICE')
                public.writeFile(a_file,'')

            if not 'key' in api_config:
                public.set_error_num(num_key)
                return public.returnJson(False, 'KEY_ERR')
            if not 'form_data' in get:
                public.set_error_num(num_key)
                return public.returnJson(False, 'FORM_DATA_ERR')

            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:
            public.set_error_num(num_key,True)
            return False
        public.set_error_num(num_key)
        return public.returnJson(False,'SECRET_KEY_CHECK_FALSE')
Exemplo n.º 30
0
 def get_limitip(self):
     if os.path.exists('/www/server/panel/data/limitip.conf'):
         ret = public.ReadFile('/www/server/panel/data/limitip.conf')
         if not ret:
             return False
         return True
     else:
         return False