Esempio n. 1
0
def site(pdata = None):
    comReturn = comm.local()
    if comReturn: return comReturn
    if request.method == method_get[0] and not pdata:
        data = {}
        data['isSetup'] = True;
        data['lan'] = public.getLan('site');
        if os.path.exists(public.GetConfigValue('setup_path')+'/nginx') == False and os.path.exists(public.GetConfigValue('setup_path')+'/apache') == False: data['isSetup'] = False;
        return render_template( 'site.html',data=data)
    import panelSite
    siteObject = panelSite.panelSite()
        
    defs = ('GetRedirectFile','SaveRedirectFile','DeleteRedirect','GetRedirectList','CreateRedirect','ModifyRedirect','GetSiteLogs','GetSiteDomains','GetSecurity','SetSecurity','ProxyCache','CloseToHttps','HttpToHttps','SetEdate','SetRewriteTel','GetCheckSafe','CheckSafe','GetDefaultSite','SetDefaultSite','CloseTomcat','SetTomcat','apacheAddPort','AddSite','GetPHPVersion','SetPHPVersion','DeleteSite','AddDomain','DelDomain','GetDirBinding','AddDirBinding','GetDirRewrite','DelDirBinding','get_site_types','add_site_type','remove_site_type','modify_site_type_name','set_site_type','UpdateRulelist','SetSiteRunPath','GetSiteRunPath','SetPath','SetIndex','GetIndex','GetDirUserINI','SetDirUserINI','GetRewriteList','SetSSL','SetSSLConf','CreateLet','CloseSSLConf','GetSSL','SiteStart','SiteStop','Set301Status','Get301Status','CloseLimitNet','SetLimitNet','GetLimitNet','RemoveProxy','GetProxyList','GetProxyDetals','CreateProxy','ModifyProxy','GetProxyFile','SaveProxyFile','ToBackup','DelBackup','GetSitePHPVersion','logsOpen','GetLogsStatus','CloseHasPwd','SetHasPwd','GetHasPwd','GetDnsApi','SetDnsApi')
    return publicObject(siteObject,defs,None,pdata);
Esempio n. 2
0
 def sync_to_crond(self, cronInfo):
     if 'status' in cronInfo:
         if cronInfo['status'] == 0: return False
     if 'where_hour' in cronInfo:
         cronInfo['hour'] = cronInfo['where_hour']
         cronInfo['minute'] = cronInfo['where_minute']
         cronInfo['week'] = cronInfo['where1']
     cuonConfig, cronInfo, name = self.GetCrondCycle(cronInfo)
     cronPath = public.GetConfigValue('setup_path') + '/cron'
     cronName = self.GetShell(cronInfo)
     if type(cronName) == dict: return cronName
     cuonConfig += ' ' + cronPath + '/' + cronName + ' >> ' + cronPath + '/' + cronName + '.log 2>&1'
     self.WriteShell(cuonConfig)
     self.CrondReload()
Esempio n. 3
0
def ftp(pdata = None):
    comReturn = comm.local()
    if comReturn: return comReturn
    if request.method == method_get[0] and not pdata:
        FtpPort()
        data = {}
        data['isSetup'] = True;
        if os.path.exists(public.GetConfigValue('setup_path') + '/pure-ftpd') == False: data['isSetup'] = False;
        data['lan'] = public.GetLan('ftp')
        return render_template('ftp.html',data=data)
    import ftp
    ftpObject = ftp.ftp()
    defs = ('AddUser','DeleteUser','SetUserPassword','SetStatus','setPort')
    return publicObject(ftpObject,defs,None,pdata);
Esempio n. 4
0
 def BtcoInstall(self, get):
     v = public.version()
     if v[-2] == '.':
         if v < '6.9.1':
             public.returnMsg(False, '抱歉,面板当前版本不支持BTCO,请升级面板至最新版')
         else:
             if v < '6.9.15':
                 public.returnMsg(False, '抱歉,面板当前版本不支持BTCO,请升级面板至最新版')
     if not public.GetConfigValue('btco'):
         initobj = open(
             '/www/server/panel/BTPanel/templates/default/layout.html', 'r')
         for initLine in initobj:
             for btcoin in ['<!--BTCO-->']:
                 if btcoin.upper() in initLine.upper():
                     self.BtcoIns.append(btcoin)
             if len(self.BtcoIns) != 0:
                 initobj.close()
                 public.SetConfigValue('btco', True)
                 public.SetConfigValue('btco_init', True)
                 return public.returnMsg(True, '您已安装过了。')
         # BTCO 强制跳转写入
         BtcoAdd = '<!--BTCO-->\n   <script> if(navigator.userAgent.match(/mobile/i)){let a=document.location.toString().split("//"),urlArr=["/","/config"],thisUrl=urlArr.indexOf(a[1].substring(a[1].indexOf("/")));if(thisUrl>-1)window.location.href="/btco/index.html#"+urlArr[thisUrl]} </script> \n   <!--BTCO-->'
         initCoutent = open(
             '/www/server/panel/BTPanel/templates/default/layout.html', 'r')
         BtcoAddIn = initCoutent.read().split("</head>")
         initCoutent.close()
         BtcoAddin = open(
             '/www/server/panel/BTPanel/templates/default/layout.html', 'w')
         BtcoAddin.write(BtcoAddIn[0] + BtcoAdd + "</head>" + BtcoAddIn[1])
         BtcoAddin.close()
         public.restart_panel()
         public.SetConfigValue('btco', True)
         public.SetConfigValue('btco_init', True)
         return public.returnMsg(True, '安装成功,感谢支持.')
     elif public.GetConfigValue('btco'):
         return public.returnMsg(True, '您已安装过了.')
     return public.returnMsg(False, '安装失败')
Esempio n. 5
0
 def setPHPDisable(self, get):
     filename = public.GetConfigValue(
         'setup_path') + '/php/' + get.version + '/etc/php.ini'
     if not os.path.exists(filename):
         return public.returnMsg(False, 'PHP_NOT_EXISTS')
     phpini = public.readFile(filename)
     rep = "disable_functions\s*=\s*.*\n"
     phpini = re.sub(rep,
                     'disable_functions = ' + get.disable_functions + "\n",
                     phpini)
     public.WriteLog('TYPE_PHP', 'PHP_DISABLE_FUNCTION',
                     (get.version, get.disable_functions))
     public.writeFile(filename, phpini)
     public.phpReload(get.version)
     return public.returnMsg(True, 'SET_SUCCESS')
Esempio n. 6
0
 def setPHPMaxTime(self,get):
     time = get.time
     version = get.version;
     if int(time) < 30 or int(time) > 86400: return public.returnMsg(False,'PHP_TIMEOUT_ERR');
     file = public.GetConfigValue('setup_path')+'/php/'+version+'/etc/php-fpm.conf';
     conf = public.readFile(file);
     rep = "request_terminate_timeout\s*=\s*([0-9]+)\n";
     conf = re.sub(rep,"request_terminate_timeout = "+time+"\n",conf);    
     public.writeFile(file,conf)
     
     file = '/www/server/php/'+version+'/etc/php.ini';
     phpini = public.readFile(file);
     rep = "max_execution_time\s*=\s*([0-9]+)\r?\n";
     phpini = re.sub(rep,"max_execution_time = "+time+"\n",phpini);
     rep = "max_input_time\s*=\s*([0-9]+)\r?\n";
     phpini = re.sub(rep,"max_input_time = "+time+"\n",phpini);
     public.writeFile(file,phpini)
     
     if public.get_webserver() == 'nginx':
         #设置Nginx
         path = public.GetConfigValue('setup_path')+'/nginx/conf/nginx.conf';
         conf = public.readFile(path);
         rep = "fastcgi_connect_timeout\s+([0-9]+);";
         tmp = re.search(rep, conf).groups();
         if int(tmp[0]) < int(time):
             conf = re.sub(rep,'fastcgi_connect_timeout '+time+';',conf);
             rep = "fastcgi_send_timeout\s+([0-9]+);";
             conf = re.sub(rep,'fastcgi_send_timeout '+time+';',conf);
             rep = "fastcgi_read_timeout\s+([0-9]+);";
             conf = re.sub(rep,'fastcgi_read_timeout '+time+';',conf);
             public.writeFile(path,conf);
             
     public.WriteLog("TYPE_PHP", "PHP_TIMEOUT",(version,time));
     public.serviceReload()
     public.phpReload(version);
     return public.returnMsg(True, 'SET_SUCCESS');
Esempio n. 7
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'] = 'http://www.aapanel.com'
Esempio n. 8
0
    def get_phpmyadmin_phpversion(self):
        '''
            @name 获取当前phpmyadmin设置的PHP版本
            @author hwliang<2020-07-13>
            @return string
        '''
        ikey = 'pma_phpv'
        phpv = cache.get(ikey)
        if phpv: return phpv
        webserver = public.get_webserver()
        if webserver == 'nginx':
            filename = public.GetConfigValue(
                'setup_path') + '/nginx/conf/enable-php.conf'
            conf = public.readFile(filename)
            if not conf: return None
            rep = r"php-cgi-(\d+)\.sock"
            phpv = re.findall(rep, conf)
        elif webserver == 'openlitespeed':
            filename = public.GetConfigValue(
                'setup_path'
            ) + "/panel/vhost/openlitespeed/detail/phpmyadmin.conf"
            conf = public.readFile(filename)
            if not conf: return None
            rep = r"/usr/local/lsws/lsphp(\d+)/bin/lsphp"
            phpv = re.findall(rep, conf)
        else:
            filename = public.GetConfigValue(
                'setup_path') + '/apache/conf/extra/httpd-vhosts.conf'
            conf = public.readFile(filename)
            if not conf: return None
            rep = r"php-cgi-(\d+)\.sock"
            phpv = re.findall(rep, conf)

        if not phpv: return None
        cache.set(ikey, phpv[0], 3)
        return phpv[0]
Esempio n. 9
0
 def BT_index(self, get):
     v_info = sys.version_info
     BTIndex = {}
     BTIndex['siteCount'] = public.M('sites').count()
     BTIndex['ftpCount'] = public.M('ftps').count()
     BTIndex['databaseCount'] = public.M('databases').count()
     BTIndex['BTTitle'] = public.GetConfigValue('title')
     BTIndex['time'] = self.GetBootTime()
     BTIndex['version'] = session['version']
     BTIndex['system'] = self.GetSystemVersion()
     BTIndex['webserver'] = session['webserver']
     BTIndex['py'] = str(v_info.major) + '.' + str(
         v_info.minor) + '.' + str(v_info.micro)
     BTIndex['check'] = self.is_pro()
     BTIndex['ip'] = public.GetLocalIp()
     return BTIndex
Esempio n. 10
0
 def to_not_beta(self, get):
     try:
         userInfo = json.loads(public.ReadFile('data/userInfo.json'))
         p_data = {}
         p_data['uid'] = userInfo['uid']
         p_data['access_key'] = userInfo['access_key']
         p_data['username'] = userInfo['username']
         result = public.HttpPost(
             public.GetConfigValue('home') + '/api/panel/to_not_beta',
             p_data, 5)
         try:
             return json.loads(result)
         except:
             return public.returnMsg(False, 'AJAX_CONN_ERR')
     except:
         return public.returnMsg(False, 'AJAX_USER_BINDING_ERR')
Esempio n. 11
0
 def DelCrontab(self,get):
     try:
         id = get['id']
         find = public.M('crontab').where("id=?",(id,)).field('name,echo').find()
         if not self.remove_for_crond(find['echo']): return public.returnMsg(False,'SYSSAFE_CANT_WRITE_FILE');
         cronPath = public.GetConfigValue('setup_path') + '/cron'
         sfile = cronPath + '/' + find['echo']
         if os.path.exists(sfile): os.remove(sfile)
         sfile = cronPath + '/' + find['echo'] + '.log'
         if os.path.exists(sfile): os.remove(sfile)
         
         public.M('crontab').where("id=?",(id,)).delete()
         public.WriteLog('TYPE_CRON', 'CRONTAB_DEL',(find['name'],))
         return public.returnMsg(True, 'DEL_SUCCESS')
     except:
         return public.returnMsg(False, 'DEL_ERROR')
Esempio n. 12
0
    def GetPHPConfig(self, get):
        import re, json
        filename = public.GetConfigValue(
            'setup_path') + '/php/' + get.version + '/etc/php.ini'
        if not os.path.exists(filename):
            return public.returnMsg(False, 'PHP_NOT_EXISTS')
        phpini = public.readFile(filename)
        data = {}
        rep = "disable_functions\s*=\s{0,1}(.*)\n"
        tmp = re.search(rep, phpini).groups()
        data['disable_functions'] = tmp[0]

        rep = "upload_max_filesize\s*=\s*([0-9]+)(M|m|K|k)"
        tmp = re.search(rep, phpini).groups()
        data['max'] = tmp[0]

        rep = u"\n;*\s*cgi\.fix_pathinfo\s*=\s*([0-9]+)\s*\n"
        tmp = re.search(rep, phpini).groups()
        if tmp[0] == '0':
            data['pathinfo'] = False
        else:
            data['pathinfo'] = True
        self.getCloudPHPExt(get)
        phplib = json.loads(public.readFile('data/phplib.conf'))
        libs = []
        tasks = public.M('tasks').where("status!=?",
                                        ('1', )).field('status,name').select()
        for lib in phplib:
            lib['task'] = '1'
            for task in tasks:
                tmp = public.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)

        data['libs'] = libs
        return data
Esempio n. 13
0
 def DelBackup(self,get):
     try:
         id = get.id
         where = "id=?"
         filename = public.M('backup').where(where,(id,)).getField('filename')
         if os.path.exists(filename): os.remove(filename)
         name=''
         if filename == 'qiniu':
             name = public.M('backup').where(where,(id,)).getField('name');
             public.ExecShell("python "+public.GetConfigValue('setup_path') + '/panel/script/backup_qiniu.py delete_file ' + name)
         
         public.M('backup').where(where,(id,)).delete()
         public.WriteLog("TYPE_DATABASE", 'DATABASE_BACKUP_DEL_SUCCESS',(name,filename))
         return public.returnMsg(True, 'DEL_SUCCESS');
     except Exception as ex:
         public.WriteLog("TYPE_DATABASE", 'DATABASE_BACKUP_DEL_ERR',(name,filename,str(ex)))
         return public.returnMsg(False,'DEL_ERROR')
Esempio n. 14
0
def database(pdata = None):
    comReturn = comm.local()
    if comReturn: return comReturn
    if request.method == method_get[0] and not pdata:
        pmd = get_phpmyadmin_dir();
        session['phpmyadminDir'] = False
        if pmd: 
            session['phpmyadminDir'] = 'http://' + public.GetHost() + ':'+ pmd[1] + '/' + pmd[0];
        data = {}
        data['isSetup'] = os.path.exists(public.GetConfigValue('setup_path') + '/mysql/bin');
        data['mysql_root'] = public.M('config').where('id=?',(1,)).getField('mysql_root');
        data['lan'] = public.GetLan('database')
        return render_template('database.html',data=data)
    import database
    databaseObject = database.database()
    defs = ('GetdataInfo','GetInfo','ReTable','OpTable','AlTable','GetSlowLogs','GetRunStatus','SetDbConf','GetDbStatus','BinLog','GetErrorLog','GetMySQLInfo','SetDataDir','SetMySQLPort','AddDatabase','DeleteDatabase','SetupPassword','ResDatabasePassword','ToBackup','DelBackup','InputSql','SyncToDatabases','SyncGetDatabases','GetDatabaseAccess','SetDatabaseAccess')
    return publicObject(databaseObject,defs,None,pdata);
Esempio n. 15
0
    def ResDatabasePassword(self,get):
        try:
            newpassword = get['password']
            username = get['name']
            id = get['id']
            if not newpassword: return public.returnMsg(False,'DB_PASSWD_EMPTY_ERR', (username,))
            name = public.M('databases').where('id=?',(id,)).getField('name')
            
            rep = "^[\w@\.\?\-\_\>\<\~\!\#\$\%\^\&\*\(\)]+$"
            if  not re.match(rep, newpassword): return public.returnMsg(False, 'DATABASE_NAME_ERR_T')
            #修改MYSQL
            mysql_obj = panelMysql.panelMysql()
            m_version = public.readFile(public.GetConfigValue('setup_path') + '/mysql/version.pl')
            if m_version.find('5.7') == 0  or m_version.find('8.0') == 0 :
                accept = self.map_to_list(panelMysql.panelMysql().query("select Host from mysql.user where User='******' AND Host!='localhost'"))
                mysql_obj.execute("update mysql.user set authentication_string='' where User='******'")
                result = mysql_obj.execute("ALTER USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username,newpassword))
                for my_host in accept:
                    mysql_obj.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % (username,my_host[0],newpassword))
            elif m_version.find('10.5.') != -1 or m_version.find('10.4.') != -1:
                accept = self.map_to_list(panelMysql.panelMysql().query("select Host from mysql.user where User='******' AND Host!='localhost'"))
                result = mysql_obj.execute("ALTER USER `%s`@`localhost` IDENTIFIED BY '%s'" % (username,newpassword))
                for my_host in accept:
                    mysql_obj.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % (username,my_host[0],newpassword))
            else:
                result = mysql_obj.execute("update mysql.user set Password=password('" + newpassword + "') where User='******'")
            
            isError=self.IsSqlError(result)
            if  isError != None: return isError

            mysql_obj.execute("flush privileges")
            #if result==False: return public.returnMsg(False,'DATABASE_PASS_ERR_NOT_EXISTS')
            #修改SQLITE
            if int(id) > 0:
                public.M('databases').where("id=?",(id,)).setField('password',newpassword)
            else:
                public.M('config').where("id=?",(id,)).setField('mysql_root',newpassword)
                session['config']['mysql_root'] = newpassword
            
            public.WriteLog("TYPE_DATABASE",'DATABASE_PASS_SUCCESS',(name,))
            return public.returnMsg(True,'DATABASE_PASS_SUCCESS',(name,))
        except Exception as ex:
            import traceback
            public.WriteLog("TYPE_DATABASE", 'DATABASE_PASS_ERROR',(username,traceback.format_exc(limit=True).replace('\n','<br>')))
            return public.returnMsg(False,'DATABASE_PASS_ERROR',(name,))    
Esempio n. 16
0
 def check_user_auth(self,get):
     m_key = 'check_user_auth'
     if m_key in session: return session[m_key]
     u_path = 'data/userInfo.json'
     try:
         userInfo = json.loads(public.ReadFile(u_path))
     except: 
         if os.path.exists(u_path): os.remove(u_path)
         return public.returnMsg(False,'AJAX_USER_BE_OVERDUE')
     pdata = {'access_key':userInfo['access_key'],'secret_key':userInfo['secret_key']}
     result = public.HttpPost(public.GetConfigValue('home') + '/api/panel/check_auth_key',pdata,3)
     if result == '0': 
         if os.path.exists(u_path): os.remove(u_path)
         return public.returnMsg(False,'AJAX_USER_BE_OVERDUE')
     if result == '1':
         session[m_key] = public.returnMsg(True,'AJAX_USER_IS_VALID!')
         return session[m_key]
     return public.returnMsg(True,result)
Esempio n. 17
0
    def SetupPassword(self,get):
        password = get['password'].strip()
        try:
            if not password: return public.returnMsg(False,'MYSQL_ROOT_PASSWD_EMTPY_ERR')
            rep = "^[\w@\.\?\-\_\>\<\~\!\#\$\%\^\&\*\(\)]+$"
            if not re.match(rep, password): return public.returnMsg(False, 'DATABASE_NAME_ERR_T')
            mysql_root = public.M('config').where("id=?",(1,)).getField('mysql_root')
            #修改MYSQL
            mysql_obj = panelMysql.panelMysql()
            result = mysql_obj.query("show databases")
            isError=self.IsSqlError(result)
            is_modify = True
            if  isError != None: 
                #尝试使用新密码
                public.M('config').where("id=?",(1,)).setField('mysql_root',password)
                result = mysql_obj.query("show databases")
                isError=self.IsSqlError(result)
                if  isError != None: 
                    public.ExecShell("cd /www/server/panel && "+public.get_python_bin()+" tools.py root \"" + password + "\"")
                    is_modify = False
            if is_modify:
                m_version = public.readFile(public.GetConfigValue('setup_path') + '/mysql/version.pl')
                
                if m_version.find('5.7') == 0  or m_version.find('8.0') == 0:
                    accept = self.map_to_list(mysql_obj.query("select Host from mysql.user where User='******'"))
                    for my_host in accept:
                        mysql_obj.execute("UPDATE mysql.user SET authentication_string='' WHERE User='******' and Host='{}'".format(my_host[0]))
                        mysql_obj.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % ('root',my_host[0],password))
                elif m_version.find('10.5.') != -1 or m_version.find('10.4.') != -1:
                    accept = self.map_to_list(mysql_obj.query("select Host from mysql.user where User='******'"))
                    for my_host in accept:
                        mysql_obj.execute("ALTER USER `%s`@`%s` IDENTIFIED BY '%s'" % ('root',my_host[0],password))
                else:
                    result = mysql_obj.execute("update mysql.user set Password=password('" + password + "') where User='******'")
                mysql_obj.execute("flush privileges")

            msg = public.getMsg('DATABASE_ROOT_SUCCESS')
            #修改SQLITE
            public.M('config').where("id=?",(1,)).setField('mysql_root',password)  
            public.WriteLog("TYPE_DATABASE", "DATABASE_ROOT_SUCCESS")
            session['config']['mysql_root']=password
            return public.returnMsg(True,msg)
        except Exception as ex:
            return public.returnMsg(False,'EDIT_ERROR' + str(ex))
Esempio n. 18
0
    def AddCrontab(self,get):
        if len(get['name'])<1:
             return public.returnMsg(False,'CRONTAB_TASKNAME_EMPTY')
        cuonConfig,get,name = self.GetCrondCycle(get)
        cronPath=public.GetConfigValue('setup_path')+'/cron'
        cronName=self.GetShell(get)
        if type(cronName) == dict: return cronName;
        cuonConfig += ' ' + cronPath+'/'+cronName+' >> '+ cronPath+'/'+cronName+'.log 2>&1'

        wRes = self.WriteShell(cuonConfig)
        if type(wRes) != bool: return wRes
        self.CrondReload()
        addData=public.M('crontab').add(
            'name,type,where1,where_hour,where_minute,echo,addtime,status,save,backupTo,sType,sName,sBody,urladdress',
            (get['name'],get['type'],get['where1'],get['hour'],get['minute'],cronName,time.strftime('%Y-%m-%d %X',time.localtime()),1,get['save'],get['backupTo'],get['sType'],get['sName'],get['sBody'],get['urladdress'])
            )
        if addData>0:
             return public.returnMsg(True,'ADD_SUCCESS')
        return public.returnMsg(False,'ADD_ERROR')
Esempio n. 19
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()):
                return 404
                # 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)
Esempio n. 20
0
    def SetupPassword(self,get):
        password = get['password'].strip()
        try:
            if not password: return public.returnMsg(False,'Root password cannot be empty')
            rep = "^[\w@\.\?\-\_\>\<\~\!\#\$\%\^\&\*\(\)]+$"
            if not re.match(rep, password): return public.returnMsg(False, 'DATABASE_NAME_ERR_T')
            mysql_root = public.M('config').where("id=?",(1,)).getField('mysql_root')
            #修改MYSQL
            mysql_obj = panelMysql.panelMysql()
            result = mysql_obj.query("show databases")
            isError=self.IsSqlError(result)
            is_modify = True
            if  isError != None: 
                #尝试使用新密码
                public.M('config').where("id=?",(1,)).setField('mysql_root',password)
                result = mysql_obj.query("show databases")
                isError=self.IsSqlError(result)
                if  isError != None: 
                    os.system("cd /www/server/panel && python tools.py root \"" + password + "\"")
                    is_modify = False
            if is_modify:
                m_version = public.readFile(public.GetConfigValue('setup_path') + '/mysql/version.pl')
                
                if m_version.find('5.7') == 0  or m_version.find('8.0') == 0:
                    panelMysql.panelMysql().execute("UPDATE mysql.user SET authentication_string='' WHERE user='******'")
                    panelMysql.panelMysql().execute("ALTER USER 'root'@'localhost' IDENTIFIED BY '%s'" % password)
                    panelMysql.panelMysql().execute("ALTER USER 'root'@'127.0.0.1' IDENTIFIED BY '%s'" % password)
                else:
                    result = mysql_obj.execute("update mysql.user set Password=password('" + password + "') where User='******'")
                mysql_obj.execute("flush privileges")

            msg = public.getMsg('DATABASE_ROOT_SUCCESS');
            #修改SQLITE
            public.M('config').where("id=?",(1,)).setField('mysql_root',password)  
            public.WriteLog("TYPE_DATABASE", "DATABASE_ROOT_SUCCESS")
            session['config']['mysql_root']=password
            return public.returnMsg(True,msg)
        except Exception as ex:
            return public.returnMsg(False,'EDIT_ERROR' + str(ex));
Esempio n. 21
0
    def set_crond(self):
        try:
            echo = public.md5(public.md5('renew_lets_ssl_bt'))
            cron_id = public.M('crontab').where('echo=?',(echo,)).getField('id')

            import crontab
            args_obj = public.dict_obj()
            if not cron_id:
                cronPath = public.GetConfigValue('setup_path') + '/cron/' + echo    
                shell = 'python %s/panel/class/panelLets.py renew_lets_ssl ' % (self.setupPath)
                public.writeFile(cronPath,shell)
                args_obj.id = public.M('crontab').add('name,type,where1,where_hour,where_minute,echo,addtime,status,save,backupTo,sType,sName,sBody,urladdress',("续签Let's Encrypt证书",'day','','0','10',echo,time.strftime('%Y-%m-%d %X',time.localtime()),0,'','localhost','toShell','',shell,''))
                crontab.crontab().set_cron_status(args_obj)
            else:
                cron_path = public.get_cron_path()
                if os.path.exists(cron_path):
                    cron_s = public.readFile(cron_path)
                    if cron_s.find(echo) == -1:
                        public.M('crontab').where('echo=?',(echo,)).setField('status',0)
                        args_obj.id = cron_id
                        crontab.crontab().set_cron_status(args_obj)
        except:pass
Esempio n. 22
0
    def init(self):
        ua = request.headers.get('User-Agent')
        if ua:
            ua = ua.lower()
            if ua.find('spider') != -1 or ua.find('bot') != -1:
                return redirect('https://www.google.com')
        g.version = '6.6.7'
        g.title = public.GetConfigValue('title')
        g.uri = request.path
        if not os.path.exists('data/debug.pl'):
            g.cdn_url = public.get_cdn_url()
            if not g.cdn_url:
                g.cdn_url = '/static'
            else:
                g.cdn_url = '//' + g.cdn_url + '/' + g.version
        else:
            g.cdn_url = '/static'

        session['version'] = g.version
        session['title'] = g.title
        g.is_aes = False
        return None
Esempio n. 23
0
    def GetPanelInfo(self, get=None):
        #取面板配置
        address = public.GetLocalIp()
        try:
            port = public.GetHost(True)
        except:
            port = '8888'
        domain = ''
        if os.path.exists('data/domain.conf'):
            domain = public.readFile('data/domain.conf')

        autoUpdate = ''
        if os.path.exists('data/autoUpdate.pl'): autoUpdate = 'checked'
        limitip = ''
        if os.path.exists('data/limitip.conf'):
            limitip = public.readFile('data/limitip.conf')
        admin_path = '/'
        if os.path.exists('data/admin_path.pl'):
            admin_path = public.readFile('data/admin_path.pl').strip()

        templates = []
        #for template in os.listdir('BTPanel/templates/'):
        #    if os.path.isdir('templates/' + template): templates.append(template);
        template = public.GetConfigValue('template')

        check502 = ''
        if os.path.exists('data/502Task.pl'): check502 = 'checked'
        return {
            'port': port,
            'address': address,
            'domain': domain,
            'auto': autoUpdate,
            '502': check502,
            'limitip': limitip,
            'templates': templates,
            'template': template,
            'admin_path': admin_path
        }
Esempio n. 24
0
 def BtcoRemove(self, get):
     if not public.GetConfigValue('btco'):
         return public.returnMsg(False, '未安装怎么移除?')
     initobj = open(
         '/www/server/panel/BTPanel/templates/default/layout.html', 'r')
     for initLine in initobj:
         for btcoin in ['<!--BTCO-->']:
             if btcoin.upper() in initLine.upper():
                 self.BtcoIns.append(btcoin)
     if len(self.BtcoIns) > 0:
         initCoutent = open(
             '/www/server/panel/BTPanel/templates/default/layout.html', 'r')
         BtcoAddOn = initCoutent.read().split("<!--BTCO-->")
         initCoutent.close()
         BtcoAddOnd = open(
             '/www/server/panel/BTPanel/templates/default/layout.html', 'w')
         BtcoAddOnd.write(BtcoAddOn[0] + BtcoAddOn[2])
         BtcoAddOnd.close()
         public.restart_panel()
         public.SetConfigValue('btco', False)
         return public.returnMsg(True, '移除成功!')
     public.SetConfigValue('btco', False)
     return public.returnMsg(True, '移除成功')
Esempio n. 25
0
 def GetLocalIp(self):
     # 取本地外网IP
     try:
         filename = '/www/server/panel/data/iplist.txt'
         ipaddress = public.readFile(filename)
         if not ipaddress:
             import urllib2
             url = 'http://pv.sohu.com/cityjson?ie=utf-8'
             opener = urllib2.urlopen(url)
             m_str = opener.read()
             ipaddress = re.search('\d+.\d+.\d+.\d+', m_str).group(0)
             public.WriteFile(filename, ipaddress)
         c_ip = public.check_ip(ipaddress)
         if not c_ip:
             a, e = public.ExecShell("curl ifconfig.me")
             return a
         return ipaddress
     except:
         try:
             url = public.GetConfigValue('home') + '/Api/getIpAddress'
             return public.HttpGet(url)
         except:
             return public.GetHost()
Esempio n. 26
0
    def init(self):
        ua = request.headers.get('User-Agent', '')
        if ua:
            ua = ua.lower()
            if ua.find('spider') != -1 or ua.find('bot') != -1:
                return redirect('https://www.google.com')
        g.version = '6.8.4'
        g.title = public.GetConfigValue('title')
        g.uri = request.path
        g.debug = os.path.exists('data/debug.pl')
        g.pyversion = sys.version_info[0]
        if not g.debug:
            g.cdn_url = public.get_cdn_url()
            if not g.cdn_url:
                g.cdn_url = '/static'
            else:
                g.cdn_url = '//' + g.cdn_url + '/' + g.version
        else:
            g.cdn_url = '/static'

        session['version'] = g.version
        session['title'] = g.title
        g.is_aes = False

        dirPath = '/www/server/phpmyadmin/pma'
        if os.path.exists(dirPath):
            public.ExecShell("rm -rf {}".format(dirPath))

        dirPath = '/www/server/adminer'
        if os.path.exists(dirPath):
            public.ExecShell("rm -rf {}".format(dirPath))

        dirPath = '/www/server/panel/adminer'
        if os.path.exists(dirPath):
            public.ExecShell("rm -rf {}".format(dirPath))

        return None
Esempio n. 27
0
    def setFpmConfig(self, get):
        version = get.version
        max_children = get.max_children
        start_servers = get.start_servers
        min_spare_servers = get.min_spare_servers
        max_spare_servers = get.max_spare_servers
        pm = get.pm

        file = public.GetConfigValue(
            'setup_path') + "/php/" + version + "/etc/php-fpm.conf"
        conf = public.readFile(file)

        rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*"
        conf = re.sub(rep, "\npm.max_children = " + max_children, conf)

        rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*"
        conf = re.sub(rep, "\npm.start_servers = " + start_servers, conf)

        rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*"
        conf = re.sub(rep, "\npm.min_spare_servers = " + min_spare_servers,
                      conf)

        rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*"
        conf = re.sub(rep,
                      "\npm.max_spare_servers = " + max_spare_servers + "\n",
                      conf)

        rep = "\s*pm\s*=\s*(\w+)\s*"
        conf = re.sub(rep, "\npm = " + pm + "\n", conf)

        public.writeFile(file, conf)
        public.phpReload(version)
        public.WriteLog("TYPE_PHP", 'PHP_CHILDREN',
                        (version, max_children, start_servers,
                         min_spare_servers, max_spare_servers))
        return public.returnMsg(True, 'SET_SUCCESS')
Esempio n. 28
0
 def StartTask(self, get):
     echo = public.M('crontab').where('id=?', (get.id, )).getField('echo')
     execstr = public.GetConfigValue('setup_path') + '/cron/' + echo
     os.system('chmod +x ' + execstr)
     os.system('nohup ' + execstr + ' >> ' + execstr + '.log 2>&1 &')
     return public.returnMsg(True, 'CRONTAB_TASK_EXEC')
Esempio n. 29
0
    def GetShell(self, param):
        #try:
        type = param['sType']
        if type == 'toFile':
            shell = param.sFile
        else:
            head = "#!/bin/bash\nPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin\nexport PATH\n"
            log = '-access_log'
            if public.get_webserver() == 'nginx':
                log = '.log'
            if type in [
                    'site', 'path'
            ] and param['sBody'] != 'undefined' and len(param['sBody']) > 1:
                exports = param['sBody'].replace("\r\n",
                                                 "\n").replace("\n", ",")
                head += "BT_EXCLUDE=\"" + exports.strip(
                ) + "\"\nexport BT_EXCLUDE\n"
            wheres = {
                'path':
                head + "python " + public.GetConfigValue('setup_path') +
                "/panel/script/backup.py path " + param['sName'] + " " +
                str(param['save']),
                'site':
                head + "python " + public.GetConfigValue('setup_path') +
                "/panel/script/backup.py site " + param['sName'] + " " +
                str(param['save']),
                'database':
                head + "python " + public.GetConfigValue('setup_path') +
                "/panel/script/backup.py database " + param['sName'] + " " +
                str(param['save']),
                'logs':
                head + "python " + public.GetConfigValue('setup_path') +
                "/panel/script/logsBackup " + param['sName'] + log + " " +
                str(param['save']),
                'rememory':
                head + "/bin/bash " + public.GetConfigValue('setup_path') +
                '/panel/script/rememory.sh'
            }
            if param['backupTo'] != 'localhost':
                cfile = public.GetConfigValue(
                    'setup_path') + "/panel/plugin/" + param[
                        'backupTo'] + "/" + param['backupTo'] + "_main.py"
                if not os.path.exists(cfile):
                    cfile = public.GetConfigValue(
                        'setup_path'
                    ) + "/panel/script/backup_" + param['backupTo'] + ".py"
                wheres = {
                    'path':
                    head + "python " + cfile + " path " + param['sName'] +
                    " " + str(param['save']),
                    'site':
                    head + "python " + cfile + " site " + param['sName'] +
                    " " + str(param['save']),
                    'database':
                    head + "python " + cfile + " database " + param['sName'] +
                    " " + str(param['save']),
                    'logs':
                    head + "python " + public.GetConfigValue('setup_path') +
                    "/panel/script/logsBackup " + param['sName'] + log + " " +
                    str(param['save']),
                    'rememory':
                    head + "/bin/bash " + public.GetConfigValue('setup_path') +
                    '/panel/script/rememory.sh'
                }

            try:
                shell = wheres[type]
            except:
                if type == 'toUrl':
                    shell = head + "curl -sS --connect-timeout 10 -m 3600 '" + param[
                        'urladdress'] + "'"
                else:
                    shell = head + param['sBody'].replace("\r\n", "\n")

                shell += '''
echo "----------------------------------------------------------------------------"
endDate=`date +"%Y-%m-%d %H:%M:%S"`
echo "★[$endDate] Successful"
echo "----------------------------------------------------------------------------"
'''
        cronPath = public.GetConfigValue('setup_path') + '/cron'
        if not os.path.exists(cronPath):
            public.ExecShell('mkdir -p ' + cronPath)
        if not 'echo' in param:
            cronName = public.md5(public.md5(str(time.time()) + '_bt'))
        else:
            cronName = param['echo']
        file = cronPath + '/' + cronName
        public.writeFile(file, self.CheckScript(shell))
        public.ExecShell('chmod 750 ' + file)
        return cronName
Esempio n. 30
0
 def GetTitle(self):
     return public.GetConfigValue('title')