Beispiel #1
0
 def get_crond_find(self, get):
     id = int(get.id)
     data = public.M('crontab').where('id=?',
                                      (id, )).field(self.field).find()
     return data
Beispiel #2
0
    def UpdatePanel(self, get):
        try:
            if not public.IsRestart():
                return public.returnMsg(False, 'EXEC_ERR_TASK')
            import json
            if int(session['config']['status']) == 0:
                public.HttpGet(
                    public.GetConfigValue('home') +
                    '/Api/SetupCount?type=Linux')
                public.M('config').where("id=?",
                                         ('1', )).setField('status', 1)

            #取回远程版本信息
            if 'updateInfo' in session and hasattr(get, 'check') == False:
                updateInfo = session['updateInfo']
            else:
                logs = ''
                import psutil, system, sys
                mem = psutil.virtual_memory()
                import panelPlugin
                mplugin = panelPlugin.panelPlugin()

                mplugin.ROWS = 10000
                panelsys = system.system()
                data = {}
                data['sites'] = str(public.M('sites').count())
                data['ftps'] = str(public.M('ftps').count())
                data['databases'] = str(public.M('databases').count())
                data['system'] = panelsys.GetSystemVersion() + '|' + str(
                    mem.total / 1024 /
                    1024) + 'MB|' + str(public.getCpuType()) + '*' + str(
                        psutil.cpu_count()) + '|' + str(
                            public.get_webserver()) + '|' + session['version']
                data['system'] += '||' + self.GetInstalleds(
                    mplugin.getPluginList(None))
                data['logs'] = logs
                data['oem'] = ''
                data['intrusion'] = 0
                data['uid'] = self.get_uid()
                #msg = public.getMsg('PANEL_UPDATE_MSG');
                data['o'] = ''
                filename = '/www/server/panel/data/o.pl'
                if os.path.exists(filename):
                    data['o'] = str(public.readFile(filename))
                sUrl = public.GetConfigValue('home') + '/api/panel/updateLinux'
                updateInfo = json.loads(public.httpPost(sUrl, data))
                if not updateInfo:
                    return public.returnMsg(False, "CONNECT_ERR")
                #updateInfo['msg'] = msg;
                session['updateInfo'] = updateInfo

            #检查是否需要升级
            if updateInfo['is_beta'] == 1:
                if updateInfo['beta']['version'] == session['version']:
                    return public.returnMsg(False, updateInfo)
            else:
                if updateInfo['version'] == session['version']:
                    return public.returnMsg(False, updateInfo)

            #是否执行升级程序
            if (updateInfo['force'] == True or hasattr(get, 'toUpdate') == True
                    or os.path.exists('data/autoUpdate.pl') == True):
                if updateInfo['is_beta'] == 1:
                    updateInfo['version'] = updateInfo['beta']['version']
                setupPath = public.GetConfigValue('setup_path')
                uptype = 'update'
                httpUrl = public.get_url()
                if httpUrl:
                    updateInfo[
                        'downUrl'] = httpUrl + '/install/' + uptype + '/LinuxPanel-' + updateInfo[
                            'version'] + '.zip'
                public.downloadFile(updateInfo['downUrl'], 'panel.zip')
                if os.path.getsize('panel.zip') < 1048576:
                    return public.returnMsg(False, "PANEL_UPDATE_ERR_DOWN")
                public.ExecShell('unzip -o panel.zip -d ' + setupPath + '/')
                import compileall
                if os.path.exists('/www/server/panel/runserver.py'):
                    public.ExecShell('rm -f /www/server/panel/*.pyc')
                if os.path.exists('/www/server/panel/class/common.py'):
                    public.ExecShell('rm -f /www/server/panel/class/*.pyc')

                if os.path.exists('panel.zip'): os.remove("panel.zip")
                session['version'] = updateInfo['version']
                if 'getCloudPlugin' in session: del (session['getCloudPlugin'])
                if updateInfo['is_beta'] == 1: self.to_beta()
                return public.returnMsg(True, 'PANEL_UPDATE',
                                        (updateInfo['version'], ))

            #输出新版本信息
            data = {
                'status': True,
                'version': updateInfo['version'],
                'updateMsg': updateInfo['updateMsg']
            }

            public.ExecShell('rm -rf /www/server/phpinfo/*')
            return public.returnMsg(True, updateInfo)
        except Exception as ex:
            return public.returnMsg(False, "CONNECT_ERR")
Beispiel #3
0
    def GetConcifInfo(self, get=None):
        #取环境配置信息
        if not hasattr(web.ctx.session, 'config'):
            web.ctx.session.config = public.M('config').where(
                "id=?",
                ('1',
                 )).field('webserver,sites_path,backup_path,status,mysql_root'
                          ).find()
        if not hasattr(web.ctx.session.config, 'email'):
            web.ctx.session.config['email'] = public.M('users').where(
                "id=?", ('1', )).getField('email')
        data = {}
        data = web.ctx.session.config
        data['webserver'] = web.ctx.session.config['webserver']
        #PHP版本
        phpVersions = ('52', '53', '54', '55', '56', '70', '71', '72', '73',
                       '74')

        data['php'] = []

        for version in phpVersions:
            tmp = {}
            tmp['setup'] = os.path.exists(self.setupPath + '/php/' + version +
                                          '/bin/php')
            if tmp['setup']:
                phpConfig = self.GetPHPConfig(version)
                tmp['version'] = version
                tmp['max'] = phpConfig['max']
                tmp['maxTime'] = phpConfig['maxTime']
                tmp['pathinfo'] = phpConfig['pathinfo']
                tmp['status'] = os.path.exists('/tmp/php-cgi-' + version +
                                               '.sock')
                data['php'].append(tmp)

        tmp = {}
        data['webserver'] = ''
        serviceName = 'nginx'
        tmp['setup'] = False
        phpversion = "54"
        phpport = '888'
        pstatus = False
        pauth = False
        if os.path.exists(self.setupPath + '/nginx'):
            data['webserver'] = 'nginx'
            serviceName = 'nginx'
            tmp['setup'] = os.path.exists(self.setupPath + '/nginx/sbin/nginx')
            configFile = self.setupPath + '/nginx/conf/nginx.conf'
            try:
                if os.path.exists(configFile):
                    conf = public.readFile(configFile)
                    rep = "listen\s+([0-9]+)\s*;"
                    rtmp = re.search(rep, conf)
                    if rtmp:
                        phpport = rtmp.groups()[0]

                    if conf.find('AUTH_START') != -1: pauth = True
                    if conf.find(self.setupPath + '/stop') == -1:
                        pstatus = True
                    configFile = self.setupPath + '/nginx/conf/enable-php.conf'
                    conf = public.readFile(configFile)
                    rep = "php-cgi-([0-9]+)\.sock"
                    rtmp = re.search(rep, conf)
                    if rtmp:
                        phpversion = rtmp.groups()[0]
            except:
                pass

        elif os.path.exists(self.setupPath + '/apache'):
            data['webserver'] = 'apache'
            serviceName = 'httpd'
            tmp['setup'] = os.path.exists(self.setupPath + '/apache/bin/httpd')
            configFile = self.setupPath + '/apache/conf/extra/httpd-vhosts.conf'
            try:
                if os.path.exists(configFile):
                    conf = public.readFile(configFile)
                    rep = "php-cgi-([0-9]+)\.sock"
                    rtmp = re.search(rep, conf)
                    if rtmp:
                        phpversion = rtmp.groups()[0]
                    rep = "Listen\s+([0-9]+)\s*\n"
                    rtmp = re.search(rep, conf)
                    if rtmp:
                        phpport = rtmp.groups()[0]
                    if conf.find('AUTH_START') != -1: pauth = True
                    if conf.find(self.setupPath + '/stop') == -1:
                        pstatus = True
            except:
                pass

        tmp['type'] = data['webserver']
        tmp['version'] = public.readFile(self.setupPath + '/' +
                                         data['webserver'] + '/version.pl')
        tmp['status'] = False
        result = public.ExecShell('/etc/init.d/' + serviceName + ' status')
        if result[0].find('running') != -1: tmp['status'] = True
        data['web'] = tmp

        tmp = {}
        vfile = self.setupPath + '/phpmyadmin/version.pl'
        tmp['version'] = public.readFile(vfile)
        tmp['setup'] = os.path.exists(vfile)
        tmp['status'] = pstatus
        tmp['phpversion'] = phpversion
        tmp['port'] = phpport
        tmp['auth'] = pauth
        data['phpmyadmin'] = tmp

        tmp = {}
        tmp['setup'] = os.path.exists('/etc/init.d/tomcat')
        tmp['status'] = True
        if public.ExecShell('ps -aux|grep tomcat|grep -v grep')[0] == "":
            tmp['status'] = False
        tmp['version'] = public.readFile(self.setupPath + '/tomcat/version.pl')
        data['tomcat'] = tmp

        tmp = {}
        tmp['setup'] = os.path.exists(self.setupPath + '/mysql/bin/mysql')
        tmp['version'] = public.readFile(self.setupPath + '/mysql/version.pl')
        tmp['status'] = os.path.exists('/tmp/mysql.sock')
        data['mysql'] = tmp

        tmp = {}
        tmp['setup'] = os.path.exists(self.setupPath + '/redis/runtest')
        tmp['status'] = os.path.exists('/var/run/redis_6379.pid')
        data['redis'] = tmp

        tmp = {}
        tmp['setup'] = os.path.exists('/usr/local/memcached/bin/memcached')
        tmp['status'] = os.path.exists('/var/run/memcached.pid')
        data['memcached'] = tmp

        tmp = {}
        tmp['setup'] = os.path.exists(self.setupPath +
                                      '/pure-ftpd/bin/pure-pw')
        tmp['version'] = public.readFile(self.setupPath +
                                         '/pure-ftpd/version.pl')
        tmp['status'] = os.path.exists('/var/run/pure-ftpd.pid')
        data['pure-ftpd'] = tmp
        data['panel'] = self.GetPanelInfo()
        data['systemdate'] = public.ExecShell(
            'date +"%Y-%m-%d %H:%M:%S %Z %z"')[0].strip()

        return data
Beispiel #4
0
    def AddSpecifiesIp(self, get):
        '''
        get 里面 有  protocol type port  address ps   五个参数
        protocol == ['tcp','udp']
        types==['reject','accept'] # 放行和禁止
        port = 端口
        address  地址
        :param get :
        :return:
        '''

        # | ports | protocol | address_ip | types |
        flag = False
        import re
        # 判断端口是否正确
        rep = "^\d{1,5}(:\d{1,5})?$"
        if not re.search(rep, get.port):
            return public.returnMsg(False, 'PORT_CHECK_RANGE')

        # 判断IP是否正确
        rep2 = "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/\d{1,2})?$"
        if not re.search(rep2, get.address):
            return public.returnMsg(False, 'FIREWALL_IP_FORMAT')
        import time
        ports = get.port
        ps = get.ps
        types = get.type
        protocol = get.protocol
        address_ip = get.address

        protocol_list = ['tcp', 'udp']
        type_list = ['reject', 'accept']
        # 判断type类型是否正确

        if types not in type_list:
            return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')
        # 判断protocol 类型是否正确

        if protocol not in protocol_list:
            return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')

        notudps = ['80', '443', '8888', '888', '39000:40000', '21', '22']
        if ports in notudps: flag = True

        # sql 查询
        #sql="select * from firewall where ports='%s' and address_ip='%s' and protocol='%s' and types='%s';" % (str(ports), str(address_ip), str(protocol), str(types))
        query_result = public.M('firewall').where(
            'ports=? and address_ip=? and protocol=? and types=?',
            (ports, address_ip, protocol, types)).count()
        # 这里大于0 表示存在
        if query_result > 0:
            return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')

        if self.__isUfw:
            if type == 'accept':
                public.ExecShell('ufw allow proto ' + protocol + ' from ' +
                                 address_ip + ' to any port ' + ports + '')

            else:
                public.ExecShell('ufw deny proto ' + protocol + ' from ' +
                                 address_ip + ' to any port ' + ports + '')

        else:
            if self.__isFirewalld:
                port = ports.replace(':', '-')
                self.__Obj.Add_Port_IP(port=ports,
                                       address=address_ip,
                                       pool=protocol,
                                       type=types)
            else:
                if type == 'accept':
                    public.ExecShell('iptables -I INPUT -s ' + address_ip +
                                     ' -p ' + protocol + ' --dport ' + ports +
                                     ' -j ACCEPT')
                else:
                    public.ExecShell('iptables -I INPUT -s ' + address_ip +
                                     ' -p ' + protocol + ' --dport ' + ports +
                                     ' -j DROP')

        public.WriteLog("TYPE_FIREWALL", 'FIREWALL_ACCEPT_PORT', (ports, ))
        addtime = time.strftime('%Y-%m-%d %X', time.localtime())
        result = public.M('firewall').add(
            'protocol,types,port,address_ip,ps,addtime',
            (protocol, types, ports, address_ip, ps, addtime))
        self.FirewallReload()
        return public.returnMsg(True, 'ADD_SUCCESS')
Beispiel #5
0
 def GetTaskCount(self, get):
     #取任务数量
     return public.M('tasks').where("status!=?", ('1', )).count()
 def GetSiteId(self, get):
     return public.M('sites').where('name=?',
                                    (get.webname, )).getField('id')
Beispiel #7
0
    def AddAcceptPort(self, get):
        flag = False
        import re
        rep = "^\d{1,5}(:\d{1,5})?$"
        if not re.search(rep, get.port):
            return public.returnMsg(False, 'PORT_CHECK_RANGE')
        import time
        port = get.port
        ps = get.ps
        types = get.type
        type_list = ['tcp', 'udp']
        if types not in type_list:
            return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')
        notudps = ['80', '443', '8888', '888', '39000:40000', '21', '22']
        if port in notudps: flag = True
        #return public.M('firewall').where("port=?", (port,)).count()
        if types == 'tcp':
            if flag:
                if public.M('firewall').where("port=?", (port, )).count() > 0:
                    return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')
            else:
                if public.M('firewall').where("port=? and type='tcp'",
                                              (port, )).count() > 0:
                    return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')
        elif types == 'udp':
            if flag:
                if public.M('firewall').where("port=?", (port, )).count() > 0:
                    return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')
            else:
                if public.M('firewall').where("port=? and type='udp'",
                                              (port, )).count() > 0:
                    return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')
        else:
            return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')

        if self.__isUfw:
            if port in notudps:
                public.ExecShell('ufw allow ' + port + '/tcp')
            else:
                public.ExecShell('ufw allow ' + port + '/' + type + '')
        else:
            if self.__isFirewalld:
                port = port.replace(':', '-')
                if port in notudps:
                    public.ExecShell(
                        'firewall-cmd --permanent --zone=public --add-port=' +
                        port + '/tcp')
                else:
                    public.ExecShell(
                        'firewall-cmd --permanent --zone=public --add-port=' +
                        port + '/' + types + '')
            else:
                if port in notudps:
                    public.ExecShell(
                        'iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport '
                        + port + ' -j ACCEPT')
                else:
                    public.ExecShell(
                        'iptables -I INPUT -p tcp -m state --state NEW -m ' +
                        types + ' --dport ' + port + ' -j ACCEPT')

        public.WriteLog("TYPE_FIREWALL", 'FIREWALL_ACCEPT_PORT', (port, ))
        addtime = time.strftime('%Y-%m-%d %X', time.localtime())
        result = public.M('firewall').add('port,ps,addtime,types',
                                          (port, ps, addtime, types))
        #return result
        self.FirewallReload()
        return public.returnMsg(True, 'ADD_SUCCESS')
Beispiel #8
0
    def crate_let_by_file(self,data):
        result = {}
        result['status'] = False
        result['clecks'] = []
        try:
            log_level = "INFO"
            if data['account_key']: log_level = 'ERROR'
            if not data['email']: data['email'] = public.M('users').getField('email')
            client = sewer.Client(domain_name = data['first_domain'],dns_class = None,account_key = data['account_key'],domain_alt_names = data['domains'],contact_email = str(data['email']),LOG_LEVEL = log_level,ACME_AUTH_STATUS_WAIT_PERIOD = 15,ACME_AUTH_STATUS_MAX_CHECKS = 5,ACME_REQUEST_TIMEOUT = 20,ACME_DIRECTORY_URL = self.let_url)
            
            client.acme_register()
            authorizations, finalize_url = client.apply_for_cert_issuance()
            responders = []
            sucess_domains = []
            for url in authorizations:
                identifier_auth = self.get_identifier_authorization(client,url)
             
                authorization_url = identifier_auth["url"]
                http_name = identifier_auth["domain"]
                http_token = identifier_auth["http_token"]
                http_challenge_url = identifier_auth["http_challenge_url"]

                acme_keyauthorization, domain_http_value = client.get_keyauthorization(http_token)   
                acme_dir = '%s/.well-known/acme-challenge' % (data['site_dir']);
                if not os.path.exists(acme_dir): os.makedirs(acme_dir)
               
                #写入token
                wellknown_path = acme_dir + '/' + http_token               
                public.writeFile(wellknown_path,acme_keyauthorization)
                wellknown_url = "http://{0}/.well-known/acme-challenge/{1}".format(http_name, http_token)
                
                result['clecks'].append({'wellknown_url':wellknown_url,'http_token':http_token});
                is_check = False
                n = 0
                while n < 5:
                    print("wait_check_authorization_status")
                    try:                       
                        retkey = public.httpGet(wellknown_url,20)
                        if retkey == acme_keyauthorization:
                            is_check = True
                            break;
                    except :
                        pass
                    n += 1;
                    time.sleep(1)
                if is_check: 
                    sucess_domains.append(http_name) 
                    responders.append({"authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization,"http_challenge_url": http_challenge_url})

            if len(sucess_domains) > 0: 
                #验证
                for i in responders:
                    auth_status_response = client.check_authorization_status(i["authorization_url"])          
                    if auth_status_response.json()["status"] == "pending":
                        client.respond_to_challenge(i["acme_keyauthorization"], i["http_challenge_url"])

                for i in responders:
                    client.check_authorization_status(i["authorization_url"], ["valid"])

                certificate_url = client.send_csr(finalize_url)
                certificate = client.download_certificate(certificate_url)
               
                if certificate:
                    certificate = self.split_ca_data(certificate)
                    result['cert'] = certificate['cert']
                    result['ca_data'] = certificate['ca_data']
                    result['key'] = client.certificate_key
                    result['account_key'] = client.account_key
                    result['status'] = True
                else:
                    result['msg'] = '证书获取失败,请稍后重试.'
            else:
                result['msg'] = "签发失败,我们无法验证您的域名:<p>1、检查域名是否绑定到对应站点</p><p>2、检查域名是否正确解析到本服务器,或解析还未完全生效</p><p>3、如果您的站点设置了反向代理,或使用了CDN,请先将其关闭</p><p>4、如果您的站点设置了301重定向,请先将其关闭</p><p>5、如果以上检查都确认没有问题,请尝试更换DNS服务商</p>'"
        except Exception as e:
            result['msg'] =  self.get_error(str(e))
        return result
Beispiel #9
0
 def setPs(self, get):
     id = get.id
     get.ps = public.xssencode(get.ps)
     if public.M(get.table).where("id=?", (id, )).setField('ps', get.ps):
         return public.returnMsg(True, 'EDIT_SUCCESS')
     return public.returnMsg(False, 'EDIT_ERROR')
Beispiel #10
0
    def crate_let_by_oper(self,data):
        result = {}
        result['status'] = False
        try:
            if not data['email']: data['email'] = public.M('users').getField('email')
            
            
            #手动解析记录值
            if not 'renew' in data:
                BTPanel.dns_client = sewer.Client(domain_name = data['first_domain'],dns_class = None,account_key = data['account_key'],domain_alt_names = data['domains'],contact_email = str(data['email']) ,ACME_AUTH_STATUS_WAIT_PERIOD = 15,ACME_AUTH_STATUS_MAX_CHECKS = 5,ACME_REQUEST_TIMEOUT = 20,ACME_DIRECTORY_URL = self.let_url)
                domain_dns_value = "placeholder"
                dns_names_to_delete = []

                BTPanel.dns_client.acme_register()
                authorizations, finalize_url = BTPanel.dns_client.apply_for_cert_issuance()
                responders = []
                for url in authorizations:
                    identifier_auth = BTPanel.dns_client.get_identifier_authorization(url)
                    authorization_url = identifier_auth["url"]
                    dns_name = identifier_auth["domain"]
                    dns_token = identifier_auth["dns_token"]
                    dns_challenge_url = identifier_auth["dns_challenge_url"]

                    acme_keyauthorization, domain_dns_value = BTPanel.dns_client.get_keyauthorization(dns_token)
                 
                    acme_name = self.get_acme_name(dns_name)
                    dns_names_to_delete.append({"dns_name": public.de_punycode(dns_name),"acme_name":acme_name, "domain_dns_value": domain_dns_value})
                    responders.append(
                        {
                            "authorization_url": authorization_url,
                            "acme_keyauthorization": acme_keyauthorization,
                            "dns_challenge_url": dns_challenge_url,
                        }
                    )
            
                dns = {}
                dns['dns_names'] = dns_names_to_delete
                dns['responders'] = responders
                dns['finalize_url'] = finalize_url
                return dns
            else:

                responders = data['dns']['responders']
                dns_names_to_delete = data['dns']['dns_names']
                finalize_url = data['dns']['finalize_url']
                for i in responders:  
                    auth_status_response = BTPanel.dns_client.check_authorization_status(i["authorization_url"])
                    if auth_status_response.json()["status"] == "pending":
                        BTPanel.dns_client.respond_to_challenge(i["acme_keyauthorization"], i["dns_challenge_url"])

                for i in responders:
                    BTPanel.dns_client.check_authorization_status(i["authorization_url"], ["valid"])

                certificate_url = BTPanel.dns_client.send_csr(finalize_url)
                certificate = BTPanel.dns_client.download_certificate(certificate_url)

                if certificate:
                    certificate = self.split_ca_data(certificate)
                    result['cert'] = certificate['cert']
                    result['ca_data'] = certificate['ca_data']
                    result['key'] = BTPanel.dns_client.certificate_key
                    result['account_key'] = BTPanel.dns_client.account_key
                    result['status'] = True
                    BTPanel.dns_client = None
                else:
                    result['msg'] = '证书获取失败,请稍后重试.'

        except Exception as e:
            print(public.get_error_info())
            result['msg'] =  self.get_error(str(e)) 
        return result
Beispiel #11
0
    def crate_let_by_dns(self,data):
        dns_class = self.get_dns_class(data)
        if not dns_class: 
            return public.returnMsg(False, 'DNS连接失败,请检查密钥是否正确.')
     
        result = {}
        result['status'] = False
        try:
            log_level = "INFO"
            if data['account_key']: log_level = 'ERROR'
            if not data['email']: data['email'] = public.M('users').getField('email')
            client = sewer.Client(domain_name = data['first_domain'],domain_alt_names = data['domains'],account_key = data['account_key'],contact_email = str(data['email']),LOG_LEVEL = log_level,ACME_AUTH_STATUS_WAIT_PERIOD = 15,ACME_AUTH_STATUS_MAX_CHECKS = 5,ACME_REQUEST_TIMEOUT = 20, dns_class = dns_class,ACME_DIRECTORY_URL = self.let_url)
            domain_dns_value = "placeholder"
            dns_names_to_delete = []
            try:
                client.acme_register()
                authorizations, finalize_url = client.apply_for_cert_issuance()
                
                responders = []
                for url in authorizations:
                    identifier_auth = client.get_identifier_authorization(url)
                    authorization_url = identifier_auth["url"]
                    dns_name = identifier_auth["domain"]
                    dns_token = identifier_auth["dns_token"]
                    dns_challenge_url = identifier_auth["dns_challenge_url"]

                    acme_keyauthorization, domain_dns_value = client.get_keyauthorization(dns_token)
                    dns_class.create_dns_record(public.de_punycode(dns_name), domain_dns_value)
                    self.check_dns(self.get_acme_name(dns_name),domain_dns_value)
                    dns_names_to_delete.append({"dns_name": public.de_punycode(dns_name), "domain_dns_value": domain_dns_value})
                    responders.append({"authorization_url": authorization_url, "acme_keyauthorization": acme_keyauthorization,"dns_challenge_url": dns_challenge_url} )
                n = 0
                while n<2:
                    print("第",n+1,"次验证")
                    try:
                        for i in responders:     
                            auth_status_response = client.check_authorization_status(i["authorization_url"])
                            r_data = auth_status_response.json()
                            if r_data["status"] == "pending":
                                client.respond_to_challenge(i["acme_keyauthorization"], i["dns_challenge_url"])

                        for i in responders: client.check_authorization_status(i["authorization_url"], ["valid"])
                        break
                    except:
                        n+=1

                certificate_url = client.send_csr(finalize_url)
                certificate = client.download_certificate(certificate_url)
                if certificate:
                    certificate = self.split_ca_data(certificate)
                    result['cert'] = certificate['cert']
                    result['ca_data'] = certificate['ca_data']
                    result['key'] = client.certificate_key
                    result['account_key'] = client.account_key
                    result['status'] = True

            except Exception as e:
                print(public.get_error_info())
                raise e
            finally:   
                try:
                    for i in dns_names_to_delete: dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"])
                except :
                    pass

        except Exception as err:  
            print(public.get_error_info())
            result['msg'] =  self.get_error(str(err)) 
        return result
Beispiel #12
0
    def setPHPMyAdmin(self, get):
        import re
        #try:
        if public.get_webserver() == 'nginx':
            filename = web.ctx.session.setupPath + '/nginx/conf/nginx.conf'
        else:
            filename = web.ctx.session.setupPath + '/apache/conf/extra/httpd-vhosts.conf'

        conf = public.readFile(filename)
        if hasattr(get, 'port'):
            mainPort = public.readFile('data/port.pl').strip()
            if mainPort == get.port:
                return public.returnMsg(False, 'SOFT_PHPVERSION_ERR_PORT_RE')
            if public.get_webserver() == 'nginx':
                rep = "listen\s+([0-9]+)\s*;"
                oldPort = re.search(rep, conf).groups()[0]
                conf = re.sub(rep, 'listen ' + get.port + ';\n', conf)
            else:
                rep = "Listen\s+([0-9]+)\s*\n"
                oldPort = re.search(rep, conf).groups()[0]
                conf = re.sub(rep, "Listen " + get.port + "\n", conf, 1)
                rep = "VirtualHost\s+\*:[0-9]+"
                conf = re.sub(rep, "VirtualHost *:" + get.port, conf, 1)

            if oldPort == get.port:
                return public.returnMsg(False, 'SOFT_PHPVERSION_ERR_PORT')

            public.writeFile(filename, conf)
            import firewalls
            get.ps = public.getMsg('SOFT_PHPVERSION_PS')
            fw = firewalls.firewalls()
            fw.AddAcceptPort(get)
            public.serviceReload()
            public.WriteLog('TYPE_SOFT', 'SOFT_PHPMYADMIN_PORT', (get.port, ))
            get.id = public.M('firewall').where('port=?',
                                                (oldPort, )).getField('id')
            get.port = oldPort
            fw.DelAcceptPort(get)
            return public.returnMsg(True, 'SET_PORT_SUCCESS')

        if hasattr(get, 'phpversion'):
            if public.get_webserver() == 'nginx':
                filename = web.ctx.session.setupPath + '/nginx/conf/enable-php.conf'
                conf = public.readFile(filename)
                rep = "php-cgi.*\.sock"
                conf = re.sub(rep, 'php-cgi-' + get.phpversion + '.sock', conf)
            else:
                rep = "php-cgi.*\.sock"
                conf = re.sub(rep, 'php-cgi-' + get.phpversion + '.sock', conf)

            public.writeFile(filename, conf)
            public.serviceReload()
            public.WriteLog('TYPE_SOFT', 'SOFT_PHPMYADMIN_PHP',
                            (get.phpversion, ))
            return public.returnMsg(True, 'SOFT_PHPVERSION_SET')

        if hasattr(get, 'password'):
            import panelSite
            if (get.password == 'close'):
                return panelSite.panelSite().CloseHasPwd(get)
            else:
                return panelSite.panelSite().SetHasPwd(get)

        if hasattr(get, 'status'):
            if conf.find(web.ctx.session.setupPath + '/stop') != -1:
                conf = conf.replace(web.ctx.session.setupPath + '/stop',
                                    web.ctx.session.setupPath + '/phpmyadmin')
                msg = public.getMsg('START')
            else:
                conf = conf.replace(web.ctx.session.setupPath + '/phpmyadmin',
                                    web.ctx.session.setupPath + '/stop')
                msg = public.getMsg('STOP')

            public.writeFile(filename, conf)
            public.serviceReload()
            public.WriteLog('TYPE_SOFT', 'SOFT_PHPMYADMIN_STATUS', (msg, ))
            return public.returnMsg(True, 'SOFT_PHPMYADMIN_STATUS', (msg, ))
Beispiel #13
0
    def UpdatePanel(self, get):
        #return public.returnMsg(False,'演示服务器,禁止此操作!');
        try:
            if not public.IsRestart():
                return public.returnMsg(False, 'EXEC_ERR_TASK')
            import web, json
            if int(web.ctx.session.config['status']) == 0:
                public.httpGet(web.ctx.session.home +
                               '/Api/SetupCount?type=Linux')
                public.M('config').where("id=?",
                                         ('1', )).setField('status', 1)

            #取回远程版本信息
            if hasattr(web.ctx.session, 'updateInfo') == True and hasattr(
                    get, 'check') == False:
                updateInfo = web.ctx.session.updateInfo
            else:
                login_temp = 'data/login.temp'
                if os.path.exists(login_temp):
                    logs = public.readFile(login_temp)
                    os.remove(login_temp)
                else:
                    logs = ''
                import psutil, panelPlugin, system
                mem = psutil.virtual_memory()
                mplugin = panelPlugin.panelPlugin()
                mplugin.ROWS = 10000
                panelsys = system.system()
                data = {}
                data['sites'] = str(public.M('sites').count())
                data['ftps'] = str(public.M('ftps').count())
                data['databases'] = str(public.M('databases').count())
                data['system'] = panelsys.GetSystemVersion() + '|' + str(
                    mem.total / 1024 /
                    1024) + 'MB|' + public.getCpuType() + '*' + str(
                        psutil.cpu_count()) + '|' + public.get_webserver(
                        ) + '|' + web.ctx.session.version
                data['system'] += '||' + self.GetInstalleds(
                    mplugin.getPluginList(None))
                data['logs'] = logs
                data['oem'] = ''
                msg = public.getMsg('PANEL_UPDATE_MSG')
                sUrl = web.ctx.session.home + '/Api/updateLinux'
                betaIs = 'data/beta.pl'
                betaStr = public.readFile(betaIs)
                if betaStr:
                    if betaStr.strip() != 'False':
                        sUrl = web.ctx.session.home + '/Api/updateLinuxBeta'
                        msg = public.getMsg('PANEL_UPDATE_MSG_TEST')

                betaIs = 'plugin/beta/config.conf'
                betaStr = public.readFile(betaIs)
                if betaStr:
                    if betaStr.strip() != 'False':
                        sUrl = web.ctx.session.home + '/Api/updateLinuxBeta'
                        msg = public.getMsg('PANEL_UPDATE_MSG_TEST')

                updateInfo = json.loads(public.httpPost(sUrl, data))
                if not updateInfo:
                    return public.returnMsg(False, "CONNECT_ERR")
                updateInfo['msg'] = msg
                web.ctx.session.updateInfo = updateInfo

            #检查是否需要升级
            if updateInfo['version'] == web.ctx.session.version:
                try:
                    return public.returnMsg(False, updateInfo['msg'])
                except:
                    return public.returnMsg(False, 'PANEL_UPDATE_ERR_NEW')

            #是否执行升级程序
            if (updateInfo['force'] == True or hasattr(get, 'toUpdate') == True
                    or os.path.exists('data/autoUpdate.pl') == True):
                setupPath = web.ctx.session.setupPath
                uptype = 'update'
                betaIs = 'plugin/beta/config.conf'
                betaStr = public.readFile(betaIs)
                if betaStr:
                    if betaStr.strip() != 'False': uptype = 'updateTest'
                betaIs = 'data/beta.pl'
                betaStr = public.readFile(betaIs)
                if betaStr:
                    if betaStr.strip() != 'False': uptype = 'updateTest'
                httpUrl = public.get_url()
                if httpUrl:
                    updateInfo[
                        'downUrl'] = httpUrl + '/install/' + uptype + '/LinuxPanel-' + updateInfo[
                            'version'] + '.zip'

                public.downloadFile(updateInfo['downUrl'], 'panel.zip')
                if os.path.getsize('panel.zip') < 1048576:
                    return public.returnMsg(False, "PANEL_UPDATE_ERR_DOWN")
                public.ExecShell('unzip -o panel.zip -d ' + setupPath + '/')
                import compileall
                if os.path.exists(setupPath + '/panel/main.py'):
                    public.ExecShell('rm -f ' + setupPath + '/panel/*.pyc')
                if os.path.exists(setupPath + '/panel/class/common.py'):
                    public.ExecShell('rm -f ' + setupPath +
                                     '/panel/class/*.pyc')

                compileall.compile_dir(setupPath + '/panel')
                compileall.compile_dir(setupPath + '/panel/class')
                public.ExecShell('rm -f panel.zip')
                web.ctx.session.version = updateInfo['version']
                return public.returnMsg(True, 'PANEL_UPDATE',
                                        (updateInfo['version'], ))

            #输出新版本信息
            data = {
                'status': True,
                'version': updateInfo['version'],
                'updateMsg': updateInfo['updateMsg']
            }

            public.ExecShell('rm -rf /www/server/phpinfo/*')
            return data
        except Exception, ex:
            return public.returnMsg(False, "CONNECT_ERR")
Beispiel #14
0
 def StartTask(self, get):
     echo = public.M('crontab').where('id=?', (get.id, )).getField('echo')
     execstr = public.GetConfigValue('setup_path') + '/cron/' + echo
     public.ExecShell('chmod +x ' + execstr)
     public.ExecShell('nohup ' + execstr + ' >> ' + execstr + '.log 2>&1 &')
     return public.returnMsg(True, 'CRONTAB_TASK_EXEC')
Beispiel #15
0
def control_init():
    time.sleep(1)
    sql = db.Sql().dbfile('system')
    if not sql.table('sqlite_master').where('type=? AND name=?',
                                            ('table', 'load_average')).count():
        csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`pro` REAL,
`one` REAL,
`five` REAL,
`fifteen` REAL,
`addtime` INTEGER
)'''
        sql.execute(csql, ())
    if not public.M('sqlite_master').where(
            'type=? AND name=? AND sql LIKE ?',
        ('table', 'sites', '%type_id%')).count():
        public.M('sites').execute(
            "alter TABLE sites add edate integer DEFAULT '0000-00-00'", ())
        public.M('sites').execute(
            "alter TABLE sites add type_id integer DEFAULT 0", ())

    sql = db.Sql()
    if not sql.table('sqlite_master').where('type=? AND name=?',
                                            ('table', 'site_types')).count():
        csql = '''CREATE TABLE IF NOT EXISTS `site_types` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` REAL,
`ps` REAL
)'''

        sql.execute(csql, ())

    if not sql.table('sqlite_master').where(
            'type=? AND name=?', ('table', 'download_token')).count():
        csql = '''CREATE TABLE IF NOT EXISTS `download_token` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`token` REAL,
`filename` REAL,
`total` INTEGER DEFAULT 0,
`expire` INTEGER,
`password` REAL,
`ps` REAL,
`addtime` INTEGER
)'''
        sql.execute(csql, ())

    if not sql.table('sqlite_master').where('type=? AND name=?',
                                            ('table', 'messages')).count():
        csql = '''CREATE TABLE IF NOT EXISTS `messages` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`level` TEXT,
`msg` TEXT,
`state` INTEGER DEFAULT 0,
`expire` INTEGER,
`addtime` INTEGER
)'''
        sql.execute(csql, ())

    if not public.M('sqlite_master').where(
            'type=? AND name=? AND sql LIKE ?',
        ('table', 'logs', '%username%')).count():
        public.M('logs').execute(
            "alter TABLE logs add uid integer DEFAULT '1'", ())
        public.M('logs').execute(
            "alter TABLE logs add username TEXT DEFAULT 'system'", ())

    if not public.M('sqlite_master').where(
            'type=? AND name=? AND sql LIKE ?',
        ('table', 'crontab', '%status%')).count():
        public.M('crontab').execute(
            "ALTER TABLE 'crontab' ADD 'status' INTEGER DEFAULT 1", ())
        public.M('crontab').execute(
            "ALTER TABLE 'crontab' ADD 'save' INTEGER DEFAULT 3", ())
        public.M('crontab').execute(
            "ALTER TABLE 'crontab' ADD 'backupTo' TEXT DEFAULT off", ())
        public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'sName' TEXT",
                                    ())
        public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'sBody' TEXT",
                                    ())
        public.M('crontab').execute("ALTER TABLE 'crontab' ADD 'sType' TEXT",
                                    ())
        public.M('crontab').execute(
            "ALTER TABLE 'crontab' ADD 'urladdress' TEXT", ())

    public.M('users').where(
        'email=? or email=?',
        ('*****@*****.**', '*****@*****.**')).setField(
            'email', '*****@*****.**')

    if not public.M('sqlite_master').where(
            'type=? AND name=? AND sql LIKE ?',
        ('table', 'users', '%salt%')).count():
        public.M('users').execute("ALTER TABLE 'users' ADD 'salt' TEXT", ())

    public.chdck_salt()

    filename = '/www/server/nginx/off'
    if os.path.exists(filename): os.remove(filename)
    c = public.to_string([
        99, 104, 97, 116, 116, 114, 32, 45, 105, 32, 47, 119, 119, 119, 47,
        115, 101, 114, 118, 101, 114, 47, 112, 97, 110, 101, 108, 47, 99, 108,
        97, 115, 115, 47, 42
    ])
    try:
        init_file = '/etc/init.d/bt'
        src_file = '/www/server/panel/init.sh'
        md51 = public.md5(init_file)
        md52 = public.md5(src_file)
        if md51 != md52:
            import shutil
            shutil.copyfile(src_file, init_file)
            if os.path.getsize(init_file) < 10:
                public.ExecShell("chattr -i " + init_file)
                public.ExecShell("\cp -arf %s %s" % (src_file, init_file))
                public.ExecShell("chmod +x %s" % init_file)
    except:
        pass
    public.writeFile('/var/bt_setupPath.conf', '/www')
    public.ExecShell(c)
    p_file = 'class/plugin2.so'
    if os.path.exists(p_file): public.ExecShell("rm -f class/*.so")
    # public.ExecShell("chmod -R  600 /www/server/panel/data;chmod -R  600 /www/server/panel/config;chmod -R  700 /www/server/cron;chmod -R  600 /www/server/cron/*.log;chown -R root:root /www/server/panel/data;chown -R root:root /www/server/panel/config;chown -R www:www /www/server/phpmyadmin;chmod -R 700 /www/server/phpmyadmin")
    if os.path.exists("/www/server/mysql"):
        public.ExecShell("chown mysql:mysql /etc/my.cnf;chmod 600 /etc/my.cnf")
    stop_path = '/www/server/stop'
    if not os.path.exists(stop_path):
        os.makedirs(stop_path)
    public.ExecShell(
        "chown -R root:root {path};chmod -R 755 {path}".format(path=stop_path))
    public.ExecShell('chmod 755 /www;chmod 755 /www/server')
    #disable_putenv('putenv')
    clean_session()
    #set_crond()
    clean_max_log('/www/server/panel/plugin/rsync/lsyncd.log')
    clean_max_log('/var/log/rsyncd.log', 1024 * 1024 * 10)
    clean_max_log('/root/.pm2/pm2.log', 1024 * 1024 * 20)
    remove_tty1()
    clean_hook_log()
    run_new()
    clean_max_log('/www/server/cron', 1024 * 1024 * 5, 20)
    #check_firewall()
    check_dnsapi()
    clean_php_log()
    #update_py37()
    files_set_mode()
Beispiel #16
0
 def get_domain_run_path(self, domain):
     pid = public.M('domain').where('name=?', (domain, )).getField('pid')
     if not pid: return False
     return self.get_site_run_path(pid)
Beispiel #17
0
    def SetupPackage(self, get):
        name = get.dname
        site_name = get.site_name
        php_version = get.php_version
        #取基础信息
        find = public.M('sites').where(
            'name=?', (site_name, )).field('id,path,name').find()
        path = find['path']
        if path.replace('//', '/') == '/':
            return public.returnMsg(False, 'Dangerous website root directory!')

        #获取包信息
        pinfo = self.GetPackageInfo(name)
        id = pinfo['id']
        if not pinfo:
            return public.returnMsg(False,
                                    'The specified package does not exist.!')

        #检查本地包
        self.WriteLogs(
            json.dumps({
                'name': 'Verifying package...',
                'total': 0,
                'used': 0,
                'pre': 0,
                'speed': 0
            }))
        pack_path = self.__panelPath + '/package'
        if not os.path.exists(pack_path): os.makedirs(pack_path, 384)
        packageZip = pack_path + '/' + name + '.zip'
        isDownload = False
        if os.path.exists(packageZip):
            md5str = self.GetFileMd5(packageZip)
            if md5str != pinfo['versions'][0]['md5']: isDownload = True
        else:
            isDownload = True

        #下载文件
        if isDownload:
            self.WriteLogs(
                json.dumps({
                    'name': 'Downloading file ...',
                    'total': 0,
                    'used': 0,
                    'pre': 0,
                    'speed': 0
                }))
            if pinfo['versions'][0]['download']:
                self.DownloadFile(
                    'http://www.bt.cn/api/Pluginother/get_file?fname=' +
                    pinfo['versions'][0]['download'], packageZip)

        if not os.path.exists(packageZip):
            return public.returnMsg(False,
                                    'File download failed!' + packageZip)

        pinfo = self.set_temp_file(packageZip, path)
        if not pinfo:
            return public.returnMsg(
                False,
                'Cannot find [aaPanel Auto Deployment Configuration File] in the installation package'
            )

        #设置权限
        self.WriteLogs(
            json.dumps({
                'name': 'Setting permissions',
                'total': 0,
                'used': 0,
                'pre': 0,
                'speed': 0
            }))
        os.system('chmod -R 755 ' + path)
        os.system('chown -R www.www ' + path)
        if pinfo['chmod'] != "":
            for chm in pinfo['chmod']:
                os.system('chmod -R ' + str(chm['mode']) + ' ' +
                          (path + '/' + chm['path']).replace('//', '/'))

        #安装PHP扩展
        self.WriteLogs(
            json.dumps({
                'name': 'Install the necessary PHP extensions',
                'total': 0,
                'used': 0,
                'pre': 0,
                'speed': 0
            }))
        import files
        mfile = files.files()
        pinfo['php_ext'] = pinfo['php_ext'].strip().split(',')
        for ext in pinfo['php_ext']:
            if ext == 'pathinfo':
                import config
                con = config.config()
                get.version = php_version
                get.type = 'on'
                con.setPathInfo(get)
            else:
                get.name = ext
                get.version = php_version
                get.type = '1'
                mfile.InstallSoft(get)

        #解禁PHP函数
        if 'enable_functions' in pinfo:
            try:
                php_f = public.GetConfigValue(
                    'setup_path') + '/php/' + php_version + '/etc/php.ini'
                php_c = public.readFile(php_f)
                rep = "disable_functions\s*=\s{0,1}(.*)\n"
                tmp = re.search(rep, php_c).groups()
                disable_functions = tmp[0].split(',')
                for fun in pinfo['enable_functions']:
                    fun = fun.strip()
                    if fun in disable_functions: disable_functions.remove(fun)
                disable_functions = ','.join(disable_functions)
                php_c = re.sub(
                    rep, 'disable_functions = ' + disable_functions + "\n",
                    php_c)
                public.writeFile(php_f, php_c)
                public.phpReload(php_version)
            except:
                pass

        #执行额外shell进行依赖安装
        self.WriteLogs(
            json.dumps({
                'name': 'Execute extra SHELL',
                'total': 0,
                'used': 0,
                'pre': 0,
                'speed': 0
            }))
        if os.path.exists(path + '/install.sh'):
            os.system('cd ' + path + ' && bash ' + 'install.sh ' +
                      find['name'])
            os.system('rm -f ' + path + '/install.sh')

        #是否执行Composer
        if os.path.exists(path + '/composer.json'):
            self.WriteLogs(
                json.dumps({
                    'name': 'Execute Composer',
                    'total': 0,
                    'used': 0,
                    'pre': 0,
                    'speed': 0
                }))
            if not os.path.exists(path + '/composer.lock'):
                execPHP = '/www/server/php/' + php_version + '/bin/php'
                if execPHP:
                    if public.get_url().find('125.88'):
                        os.system(
                            'cd ' + path + ' && ' + execPHP +
                            ' /usr/bin/composer config repo.packagist composer https://packagist.phpcomposer.com'
                        )
                    import panelSite
                    phpini = '/www/server/php/' + php_version + '/etc/php.ini'
                    phpiniConf = public.readFile(phpini)
                    phpiniConf = phpiniConf.replace(
                        'proc_open,proc_get_status,', '')
                    public.writeFile(phpini, phpiniConf)
                    os.system(
                        'nohup cd ' + path + ' && ' + execPHP +
                        ' /usr/bin/composer install -vvv > /tmp/composer.log 2>&1 &'
                    )

        #写伪静态
        self.WriteLogs(
            json.dumps({
                'name': 'Set URL rewrite',
                'total': 0,
                'used': 0,
                'pre': 0,
                'speed': 0
            }))
        swfile = path + '/nginx.rewrite'
        if os.path.exists(swfile):
            rewriteConf = public.readFile(swfile)
            dwfile = self.__panelPath + '/vhost/rewrite/' + site_name + '.conf'
            public.writeFile(dwfile, rewriteConf)

        #删除伪静态文件
        public.ExecShell("rm -f " + path + '/*.rewrite')

        #删除多余文件
        rm_file = path + '/index.html'
        if os.path.exists(rm_file):
            rm_file_body = public.readFile(rm_file)
            if rm_file_body.find('panel-heading') != -1: os.remove(rm_file)

        #设置运行目录
        self.WriteLogs(
            json.dumps({
                'name': 'Set the run directory',
                'total': 0,
                'used': 0,
                'pre': 0,
                'speed': 0
            }))
        if pinfo['run_path'] != '/':
            import panelSite
            siteObj = panelSite.panelSite()
            mobj = obj()
            mobj.id = find['id']
            mobj.runPath = pinfo['run_path']
            siteObj.SetSiteRunPath(mobj)

        #导入数据
        self.WriteLogs(
            json.dumps({
                'name': 'Import database',
                'total': 0,
                'used': 0,
                'pre': 0,
                'speed': 0
            }))
        if os.path.exists(path + '/import.sql'):
            databaseInfo = public.M('databases').where(
                'pid=?', (find['id'], )).field('username,password').find()
            if databaseInfo:
                os.system('/www/server/mysql/bin/mysql -u' +
                          databaseInfo['username'] + ' -p' +
                          databaseInfo['password'] + ' ' +
                          databaseInfo['username'] + ' < ' + path +
                          '/import.sql')
                os.system('rm -f ' + path + '/import.sql')
                siteConfigFile = (path + '/' + pinfo['db_config']).replace(
                    '//', '/')
                if os.path.exists(siteConfigFile):
                    siteConfig = public.readFile(siteConfigFile)
                    siteConfig = siteConfig.replace('BT_DB_USERNAME',
                                                    databaseInfo['username'])
                    siteConfig = siteConfig.replace('BT_DB_PASSWORD',
                                                    databaseInfo['password'])
                    siteConfig = siteConfig.replace('BT_DB_NAME',
                                                    databaseInfo['username'])
                    public.writeFile(siteConfigFile, siteConfig)

        #清理文件和目录
        self.WriteLogs(
            json.dumps({
                'name': '清理多余的文件',
                'total': 0,
                'used': 0,
                'pre': 0,
                'speed': 0
            }))
        for f_path in pinfo['remove_file']:
            filename = (path + '/' + f_path).replace('//', '/')
            if os.path.exists(filename):
                if not os.path.isdir(filename):
                    if f_path.find('.user.ini') != -1:
                        public.ExecShell("chattr -i " + filename)
                    os.remove(filename)
                else:
                    public.ExecShell("rm -rf " + filename)

        public.serviceReload()
        if id: self.depTotal(id)
        self.WriteLogs(
            json.dumps({
                'name': 'Ready to deploy',
                'total': 0,
                'used': 0,
                'pre': 0,
                'speed': 0
            }))
        return public.returnMsg(True, pinfo)
Beispiel #18
0
    def GetDVSSL(self, get):
        get.id = public.M('domain').where('name=?',
                                          (get.domain, )).getField('pid')
        if hasattr(get, 'siteName'):
            get.path = public.M('sites').where('id=?',
                                               (get.id, )).getField('path')
        else:
            get.siteName = public.M('sites').where('id=?',
                                                   (get.id, )).getField('name')

        #当申请二级域名为www时,检测主域名是否绑定到同一网站
        if get.domain[:4] == 'www.':
            if not public.M('domain').where('name=? AND pid=?',
                                            (get.domain[4:], get.id)).count():
                return public.returnMsg(
                    False,
                    "Apply for [%s] certificate to verify [%s] Please bind [%s] and resolve to the site!"
                    % (get.domain, get.domain[4:], get.domain[4:]))

        #检测是否开启强制HTTPS
        if not self.CheckForceHTTPS(get.siteName):
            return public.returnMsg(False, 'SSL_ORDER_HTTPS_ERR')

        #获取真实网站运行目录
        runPath = self.GetRunPath(get)
        if runPath != False and runPath != '/': get.path += runPath

        #提前模拟测试验证文件值是否正确
        authfile = get.path + '/.well-known/pki-validation/fileauth.txt'
        if not self.CheckDomain(get):
            if not os.path.exists(authfile):
                return public.returnMsg(False, 'CANT_CREATE', (authfile, ))
            else:
                msg = '''{err_msg}<br><a class="btlink" href="{c_url}" target="_blank">{c_url}</a> <br><br>
                <p></b>{err_msg1}</b></p>
                {err_msg2}<br>
                {err_msg3}<br>
                {err_msg4}'''.format(c_url=self._check_url,
                                     err_msg=public.getMsg('SSL_ERR_MSG'),
                                     err_msg1=public.getMsg('SSL_ERR_MSG1'),
                                     err_msg2=public.getMsg('SSL_ERR_MSG2'),
                                     err_msg3=public.getMsg('SSL_ERR_MSG3'),
                                     err_msg4=public.getMsg('SSL_ERR_MSG4'))
                return public.returnMsg(False, msg)

        action = 'GetDVSSL'
        if hasattr(get, 'partnerOrderId'):
            self.__PDATA['data']['partnerOrderId'] = get.partnerOrderId
            action = 'ReDVSSL'

        self.__PDATA['data']['domain'] = get.domain
        self.__PDATA['data'] = self.De_Code(self.__PDATA['data'])
        result = public.httpPost(self.__APIURL + '/' + action, self.__PDATA)
        try:
            result = json.loads(result)
        except:
            return result
        result['data'] = self.En_Code(result['data'])

        try:
            if 'authValue' in result['data'].keys():
                public.writeFile(authfile, result['data']['authValue'])
        except:
            try:
                public.writeFile(authfile, result['data']['authValue'])
            except:
                return result

        return result
Beispiel #19
0
 def CheckDbExists(self, port, type=None):
     data = public.M('firewall').field('id,port,ps,addtime,types').select()
     return data
     for dt in data:
         if dt['port'] == port and dt['type'] == type: return dt
     return False
Beispiel #20
0
 def get_login_log(self,get):
     return public.M('logs').where('type=?',(u'用户登录',)).field('log,addtime').select();
Beispiel #21
0
    def GetList(self, get=None):
        try:
            data = {}
            # 获取开放的端口
            data['ports'] = self.__Obj.GetAcceptPortList()
            #当前时间
            #'2018-10-11 14:36:40'
            addtime = time.strftime('%Y-%m-%d %X', time.localtime())
            #
            for i in range(len(data['ports'])):
                #
                tmp = self.CheckDbExists(data['ports'][i]['port'],
                                         data['ports'][i]['protocol'])
                # | id | port  | ps  | addtime   | ports | protocol | address_ip | types |
                if not tmp:
                    public.M('firewall').add(
                        'port,ps,addtime',
                        (data['ports'][i]['port'], '', addtime))

            data['iplist'] = self.__Obj.GetDropAddressList()

            for i in range(len(data['iplist'])):
                try:
                    tmp = self.CheckDbExists(data['iplist'][i]['address'])
                    if not tmp:
                        public.M('firewall').add(
                            'port,ps,addtime',
                            (data['iplist'][i]['address'], '', addtime))
                except:
                    return public.get_error_info()

            # 添加到firewalls 数据表中
            data['reject'] = self.__Obj.GetrejectLIST()

            for i in range(len(data['reject'])):
                try:
                    tmp = self.CheckDbExists2(data['reject'][i]['protocol'],
                                              data['reject'][i]['type'],
                                              data['reject'][i]['port'],
                                              data['reject'][i]['address'])
                    if not tmp:
                        public.M('firewall').add(
                            'protocol,types,ports,address_ip,addtime',
                            (data['reject'][i]['protocol'],
                             data['reject'][i]['type'],
                             data['reject'][i]['port'],
                             data['reject'][i]['address'], addtime))
                except:
                    return public.get_error_info()
            # 添加允许信息到firewalls 表中
            data['accept'] = self.__Obj.Getacceptlist()
            #return data
            for i in range(len(data['accept'])):
                try:
                    tmp = self.CheckDbExists2(data['accept'][i]['protocol'],
                                              data['accept'][i]['type'],
                                              data['accept'][i]['port'],
                                              data['accept'][i]['address'])
                    if not tmp:
                        public.M('firewall').add(
                            'protocol,types,ports,address_ip,addtime',
                            (data['accept'][i]['protocol'],
                             data['accept'][i]['type'],
                             data['accept'][i]['port'],
                             data['accept'][i]['address'], addtime))
                except:
                    return public.get_error_info()
            return data
        except Exception as ex:
            return public.get_error_info()
Beispiel #22
0
 def CheckDbExists(self,port):
     data = public.M('firewall').field('id,port,ps,addtime').select();
     for dt in data:
         if dt['port'] == port: return dt;
     return False;
Beispiel #23
0
    def setPHPMyAdmin(self, get):
        import re
        #try:
        filename = self.__get_webserver_conffile()
        conf = public.readFile(filename)
        if not conf: return public.returnMsg(False, 'ERROR')
        if hasattr(get, 'port'):
            mainPort = public.readFile('data/port.pl').strip()
            rulePort = [
                '80', '443', '21', '20', '8080', '8081', '8089', '11211',
                '6379'
            ]
            if get.port in rulePort:
                return public.returnMsg(False, 'AJAX_PHPMYADMIN_PORT_ERR')
            if public.get_webserver() == 'nginx':
                rep = "listen\s+([0-9]+)\s*;"
                oldPort = re.search(rep, conf).groups()[0]
                conf = re.sub(rep, 'listen ' + get.port + ';\n', conf)
            else:
                rep = "Listen\s+([0-9]+)\s*\n"
                oldPort = re.search(rep, conf).groups()[0]
                conf = re.sub(rep, "Listen " + get.port + "\n", conf, 1)
                rep = "VirtualHost\s+\*:[0-9]+"
                conf = re.sub(rep, "VirtualHost *:" + get.port, conf, 1)

            if oldPort == get.port:
                return public.returnMsg(False, 'SOFT_PHPVERSION_ERR_PORT')

            public.writeFile(filename, conf)
            import firewalls
            get.ps = public.getMsg('SOFT_PHPVERSION_PS')
            fw = firewalls.firewalls()
            fw.AddAcceptPort(get)
            public.serviceReload()
            public.WriteLog('TYPE_SOFT', 'SOFT_PHPMYADMIN_PORT', (get.port, ))
            get.id = public.M('firewall').where('port=?',
                                                (oldPort, )).getField('id')
            get.port = oldPort
            fw.DelAcceptPort(get)
            return public.returnMsg(True, 'SET_PORT_SUCCESS')

        if hasattr(get, 'phpversion'):
            if public.get_webserver() == 'nginx':
                filename = public.GetConfigValue(
                    'setup_path') + '/nginx/conf/enable-php.conf'
                conf = public.readFile(filename)
                rep = "php-cgi.*\.sock"
                conf = re.sub(rep, 'php-cgi-' + get.phpversion + '.sock', conf,
                              1)
            else:
                rep = "php-cgi.*\.sock"
                conf = re.sub(rep, 'php-cgi-' + get.phpversion + '.sock', conf,
                              1)

            public.writeFile(filename, conf)
            public.serviceReload()
            public.WriteLog('TYPE_SOFT', 'SOFT_PHPMYADMIN_PHP',
                            (get.phpversion, ))
            return public.returnMsg(True, 'SOFT_PHPVERSION_SET')

        if hasattr(get, 'password'):
            import panelSite
            if (get.password == 'close'):
                return panelSite.panelSite().CloseHasPwd(get)
            else:
                return panelSite.panelSite().SetHasPwd(get)

        if hasattr(get, 'status'):
            if conf.find(public.GetConfigValue('setup_path') + '/stop') != -1:
                conf = conf.replace(
                    public.GetConfigValue('setup_path') + '/stop',
                    public.GetConfigValue('setup_path') + '/phpmyadmin')
                msg = public.getMsg('START')
            else:
                conf = conf.replace(
                    public.GetConfigValue('setup_path') + '/phpmyadmin',
                    public.GetConfigValue('setup_path') + '/stop')
                msg = public.getMsg('STOP')

            public.writeFile(filename, conf)
            public.serviceReload()
            public.WriteLog('TYPE_SOFT', 'SOFT_PHPMYADMIN_STATUS', (msg, ))
            return public.returnMsg(True, 'SOFT_PHPMYADMIN_STATUS', (msg, ))
Beispiel #24
0
 def ClickPanelInfo(self, get):
     click = public.M('panel').where('id=?', (get.id, )).getField('click')
     public.M('panel').where('id=?',
                             (get.id, )).setField('click', click + 1)
     return True
Beispiel #25
0
 def get_load_average(self, get):
     data = public.M('load_average').dbfile('system').where(
         "addtime>=? AND addtime<=?", (get.start, get.end)).field(
             'id,pro,one,five,fifteen,addtime').order('id asc').select()
     return self.ToAddtime(data)
Beispiel #26
0
    def setPanel(self, get):
        if not public.IsRestart():
            return public.returnMsg(False, 'EXEC_ERR_TASK')
        isReWeb = False
        sess_out_path = 'data/session_timeout.pl'
        if 'session_timeout' in get:
            session_timeout = int(get.session_timeout)
            s_time_tmp = public.readFile(sess_out_path)
            if not s_time_tmp: s_time_tmp = '0'
            if int(s_time_tmp) != session_timeout:
                if session_timeout < 300:
                    return public.returnMsg(False, '超时时间不能小于300秒')
                public.writeFile(sess_out_path, str(session_timeout))
                isReWeb = True

        workers_p = 'data/workers.pl'
        if 'workers' in get:
            workers = int(get.workers)
            if int(public.readFile(workers_p)) != workers:
                if workers < 1 or workers > 1024:
                    return public.returnMsg(False, '面板线程数范围应该在1-1024之间')
                public.writeFile(workers_p, str(workers))
                isReWeb = True

        if get.domain:
            reg = "^([\w\-\*]{1,100}\.){1,4}(\w{1,10}|\w{1,10}\.\w{1,10})$"
            if not re.match(reg, get.domain):
                return public.returnMsg(False, 'SITE_ADD_ERR_DOMAIN')

        oldPort = public.GetHost(True)
        newPort = get.port
        if oldPort != get.port:
            get.port = str(int(get.port))
            if self.IsOpen(get.port):
                return public.returnMsg(False, 'PORT_CHECK_EXISTS',
                                        (get.port, ))
            if int(get.port) >= 65535 or int(get.port) < 100:
                return public.returnMsg(False, 'PORT_CHECK_RANGE')
            public.writeFile('data/port.pl', get.port)
            import firewalls
            get.ps = public.getMsg('PORT_CHECK_PS')
            fw = firewalls.firewalls()
            fw.AddAcceptPort(get)
            get.port = oldPort
            get.id = public.M('firewall').where("port=?",
                                                (oldPort, )).getField('id')
            fw.DelAcceptPort(get)
            isReWeb = True

        if get.webname != session['title']:
            session['title'] = get.webname
            public.SetConfigValue('title', get.webname)

        limitip = public.readFile('data/limitip.conf')
        if get.limitip != limitip:
            public.writeFile('data/limitip.conf', get.limitip)

        public.writeFile('data/domain.conf', get.domain.strip())
        public.writeFile('data/iplist.txt', get.address)

        public.M('config').where("id=?", ('1', )).save(
            'backup_path,sites_path', (get.backup_path, get.sites_path))
        session['config']['backup_path'] = os.path.join('/', get.backup_path)
        session['config']['sites_path'] = os.path.join('/', get.sites_path)
        mhost = public.GetHost()
        if get.domain.strip(): mhost = get.domain
        data = {
            'uri': request.path,
            'host': mhost + ':' + newPort,
            'status': True,
            'isReWeb': isReWeb,
            'msg': public.getMsg('PANEL_SAVE')
        }
        public.WriteLog('TYPE_PANEL', 'PANEL_SET_SUCCESS',
                        (newPort, get.domain, get.backup_path, get.sites_path,
                         get.address, get.limitip))
        if isReWeb: public.restart_panel()
        return data
Beispiel #27
0
 def delClose(self, get):
     public.M('logs').where('id>?', (0, )).delete()
     public.WriteLog('TYPE_CONFIG', 'LOG_CLOSE')
     return public.returnMsg(True, 'LOG_CLOSE')
Beispiel #28
0
 def get_config(self, get):
     if 'config' in session: return session['config']
     data = public.M('config').where("id=?", ('1', )).field(
         'webserver,sites_path,backup_path,status,mysql_root').find()
     return data
Beispiel #29
0
 def reload_session(self):
     userInfo = public.M('users').where(
         "id=?", (1, )).field('username,password').find()
     token = public.Md5(userInfo['username'] + '/' + userInfo['password'])
     public.writeFile('/www/server/panel/data/login_token.pl', token)
     session['login_token'] = token
Beispiel #30
0
    def GetCrontab(self, get):
        self.checkBackup()
        self.__clean_log()
        cront = public.M('crontab').order("id desc").field(self.field).select()
        if type(cront) == str:
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'status' INTEGER DEFAULT 1", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'save' INTEGER DEFAULT 3", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'backupTo' TEXT DEFAULT off", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'sName' TEXT", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'sBody' TEXT", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'sType' TEXT", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'urladdress' TEXT", ())
            cront = public.M('crontab').order("id desc").field(
                self.field).select()

        data = []
        for i in range(len(cront)):
            tmp = cront[i]
            if cront[i]['type'] == "day":
                tmp['type'] = public.getMsg('CRONTAB_TODAY')
                tmp['cycle'] = public.getMsg('CRONTAB_TODAY_CYCLE', (str(
                    cront[i]['where_hour']), str(cront[i]['where_minute'])))
            elif cront[i]['type'] == "day-n":
                tmp['type'] = public.getMsg('CRONTAB_N_TODAY',
                                            (str(cront[i]['where1']), ))
                tmp['cycle'] = public.getMsg(
                    'CRONTAB_N_TODAY_CYCLE',
                    (str(cront[i]['where1']), str(cront[i]['where_hour']),
                     str(cront[i]['where_minute'])))
            elif cront[i]['type'] == "hour":
                tmp['type'] = public.getMsg('CRONTAB_HOUR')
                tmp['cycle'] = public.getMsg('CRONTAB_HOUR_CYCLE',
                                             (str(cront[i]['where_minute']), ))
            elif cront[i]['type'] == "hour-n":
                tmp['type'] = public.getMsg('CRONTAB_N_HOUR',
                                            (str(cront[i]['where1']), ))
                tmp['cycle'] = public.getMsg(
                    'CRONTAB_N_HOUR_CYCLE',
                    (str(cront[i]['where1']), str(cront[i]['where_minute'])))
            elif cront[i]['type'] == "minute-n":
                tmp['type'] = public.getMsg('CRONTAB_N_MINUTE',
                                            (str(cront[i]['where1']), ))
                tmp['cycle'] = public.getMsg('CRONTAB_N_MINUTE_CYCLE',
                                             (str(cront[i]['where1']), ))
            elif cront[i]['type'] == "week":
                tmp['type'] = public.getMsg('CRONTAB_WEEK')
                if not cront[i]['where1']: cront[i]['where1'] = '0'
                tmp['cycle'] = public.getMsg(
                    'CRONTAB_WEEK_CYCLE', (self.toWeek(int(
                        cront[i]['where1'])), str(cront[i]['where_hour']),
                                           str(cront[i]['where_minute'])))
            elif cront[i]['type'] == "month":
                tmp['type'] = public.getMsg('CRONTAB_MONTH')
                tmp['cycle'] = public.getMsg(
                    'CRONTAB_MONTH_CYCLE',
                    (str(cront[i]['where1']), str(cront[i]['where_hour']),
                     str(cront[i]['where_minute'])))
            data.append(tmp)
        return data