Ejemplo n.º 1
0
    def SetSshPort(self, get):
        port = get.port
        if int(port) < 22 or int(port) > 65535:
            return public.returnMsg(False, 'FIREWALL_SSH_PORT_ERR')
        ports = ['21', '25', '80', '443', '8080', '888', '8888']
        if port in ports: return public.returnMsg(False, '请不要使用常用程序的默认端口!')
        file = '/etc/ssh/sshd_config'
        conf = public.readFile(file)

        rep = r"#*Port\s+([0-9]+)\s*\n"
        conf = re.sub(rep, "Port " + port + "\n", conf)
        public.writeFile(file, conf)

        if self.__isFirewalld:
            public.ExecShell(
                'firewall-cmd --permanent --zone=public --add-port=' + port +
                '/tcp')
            public.ExecShell('setenforce 0')
            public.ExecShell(
                'sed -i "s#SELINUX=enforcing#SELINUX=disabled#" /etc/selinux/config'
            )
            public.ExecShell("systemctl restart sshd.service")
        elif self.__isUfw:
            public.ExecShell('ufw allow ' + port + '/tcp')
            public.ExecShell("service ssh restart")
        else:
            public.ExecShell(
                'iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport '
                + port + ' -j ACCEPT')
            public.ExecShell("/etc/init.d/sshd restart")

        self.FirewallReload()
        public.M('firewall').where("ps=? or ps=? or port=?",
                                   ('SSH远程管理服务', 'SSH远程服务', port)).delete()
        public.M('firewall').add(
            'port,ps,addtime',
            (port, 'SSH远程服务', time.strftime('%Y-%m-%d %X', time.localtime())))
        public.WriteLog("TYPE_FIREWALL", "FIREWALL_SSH_PORT", (port, ))
        return public.returnMsg(True, 'EDIT_SUCCESS')
Ejemplo n.º 2
0
    def create_command(self, args):
        '''
            @name 创建常用命令
            @author hwliang<2020-08-08>
            @param  args<dict_obj>{
                title<string> 标题
                shell<string> 命令文本
            }
            @return dict
        '''
        args.title = args.title.strip()
        command = self.get_command_list(sys_cmd=True)

        if self.command_exists(command, args.title):
            return public.returnMsg(False, 'COMMAND_NAME_EXIST')

        cmd = {"title": args.title, "shell": args.shell.strip()}

        command.append(cmd)
        self.save_command(command)
        public.WriteLog(self._log_type, 'ADD_COMMAND_COMMAND', (args.title, ))
        return public.returnMsg(True, 'SET_SUCCESS')
Ejemplo n.º 3
0
 def create_host(self, args):
     '''
         @name 添加SSH信息
         @author hwliang<2020-08-07>
         @param args<dict_obj>{
             host: 主机地址,
             port: 端口
             ps: 备注
             sort: 排序(可选,默认0)
             username: 用户名
             password: 密码
             pkey: 密钥(如果不为空,将使用密钥连接)
         }
         @return dict
     '''
     args.host = args.host.strip()
     host_path = self._save_path + args.host
     info_file = host_path + '/info.json'
     if os.path.exists(info_file):
         args.new_host = args.host
         return self.modify_host(args)
         #return public.returnMsg(False,'指定SSH信息已经添加过了!')
     if not os.path.exists(host_path):
         os.makedirs(host_path, 384)
     if not 'sort' in args: args.sort = 0
     if not 'ps' in args: args.ps = args.host
     host_info = {}
     host_info['host'] = args.host
     host_info['port'] = int(args['port'])
     host_info['ps'] = args['ps']
     host_info['sort'] = int(args['sort'])
     host_info['username'] = args['username']
     host_info['password'] = args['password']
     host_info['pkey'] = args['pkey']
     result = self.set_attr(host_info)
     if not result['status']: return result
     self.save_ssh_info(args.host, host_info)
     public.WriteLog(self._log_type, 'ADD_SSH_INFO', (str(args.host), ))
     return public.returnMsg(True, 'SET_SUCCESS')
Ejemplo n.º 4
0
 def AddDropAddress(self,get):
     import time
     import re
     rep = "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/\d{1,2})?$"
     if not re.search(rep,get.port): return public.returnMsg(False,'FIREWALL_IP_FORMAT');
     if not public.check_ip(get.port.split('/')[0]): return public.returnMsg(False,'FIREWALL_IP_FORMAT');
     address = get.port
     if public.M('firewall').where("port=?",(address,)).count() > 0: return public.returnMsg(False,'FIREWALL_IP_EXISTS')
     if self.__isUfw:
         public.ExecShell('ufw deny from ' + address + ' to any');
     else:
         if self.__isFirewalld:
             #self.__Obj.AddDropAddress(address)
             public.ExecShell('firewall-cmd --permanent --add-rich-rule=\'rule family=ipv4 source address="'+ address +'" drop\'')
         else:
             public.ExecShell('iptables -I INPUT -s '+address+' -j DROP')
     
     public.WriteLog("TYPE_FIREWALL", 'FIREWALL_DROP_IP',(address,))
     addtime = time.strftime('%Y-%m-%d %X',time.localtime())
     public.M('firewall').add('port,ps,addtime',(address,get.ps,addtime))
     self.FirewallReload()
     return public.returnMsg(True,'ADD_SUCCESS')
Ejemplo n.º 5
0
    def DelDropAddress(self, get):
        address = get.port
        id = get.id
        if self.__isUfw:
            public.ExecShell('ufw delete deny from ' + address + ' to any')
        else:
            if self.__isFirewalld:
                public.ExecShell(
                    'firewall-cmd --permanent --remove-rich-rule=\'rule family=ipv4 source address="'
                    + address + '" drop\'')
                ret = self.__Obj.DelDropAddress(address)
                if ret:
                    pass
            else:
                public.ExecShell('iptables -D INPUT -s ' + address +
                                 ' -j DROP')

        public.WriteLog("TYPE_FIREWALL", 'FIREWALL_ACCEPT_IP', (address, ))
        public.M('firewall').where("id=?", (id, )).delete()

        self.FirewallReload()
        return public.returnMsg(True, 'DEL_SUCCESS')
Ejemplo n.º 6
0
 def InstallSoft(self,get):
     import db,time
     path = public.GetConfigValue('setup_path') + '/php'
     if not os.path.exists(path): os.system("mkdir -p " + path);
     if session['server_os']['x'] != 'RHEL': get.type = '3'
     apacheVersion='false';
     if public.get_webserver() == 'apache':
         apacheVersion = public.readFile(public.GetConfigValue('setup_path')+'/apache/version.pl');
     public.writeFile('/var/bt_apacheVersion.pl',apacheVersion)
     public.writeFile('/var/bt_setupPath.conf',public.GetConfigValue('root_path'))
     isTask = '/tmp/panelTask.pl'
     execstr = "cd " + public.GetConfigValue('setup_path') + "/panel/install && /bin/bash install_soft.sh " + get.type + " install " + get.name + " "+ get.version;
     sql = db.Sql()
     if hasattr(get,'id'):
         id = get.id;
     else:
         id = None;
     sql.table('tasks').add('id,name,type,status,addtime,execstr',(None,'安装['+get.name+'-'+get.version+']','execshell','0',time.strftime('%Y-%m-%d %H:%M:%S'),execstr))
     public.writeFile(isTask,'True')
     public.WriteLog('TYPE_SETUP','PLUGIN_ADD',(get.name,get.version));
     time.sleep(0.1);
     return public.returnMsg(True,'PLUGIN_ADD');
Ejemplo n.º 7
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));
Ejemplo n.º 8
0
    def ToBackup(self, get):
        #try:
        result = panelMysql.panelMysql().execute("show databases")
        isError = self.IsSqlError(result)
        if isError: return isError
        id = get['id']
        name = public.M('databases').where("id=?", (id, )).getField('name')
        root = public.M('config').where('id=?', (1, )).getField('mysql_root')
        if not os.path.exists(session['config']['backup_path'] + '/database'):
            os.system('mkdir -p ' + session['config']['backup_path'] +
                      '/database')
        if not self.mypass(True, root):
            return public.returnMsg(
                False,
                'Database configuration file failed to get checked, please check if MySQL configuration file exists'
            )

        fileName = name + '_' + time.strftime('%Y%m%d_%H%M%S',
                                              time.localtime()) + '.sql.gz'
        backupName = session['config']['backup_path'] + '/database/' + fileName
        public.ExecShell(
            "/www/server/mysql/bin/mysqldump --default-character-set=" +
            public.get_database_character(name) + " --force --opt \"" + name +
            "\" | gzip > " + backupName)
        if not os.path.exists(backupName):
            return public.returnMsg(False, 'BACKUP_ERROR')

        if not self.mypass(True, root):
            return public.returnMsg(
                False,
                'Database configuration file failed to get checked, please check if MySQL configuration file exists'
            )

        sql = public.M('backup')
        addTime = time.strftime('%Y-%m-%d %X', time.localtime())
        sql.add('type,name,pid,filename,size,addtime',
                (1, fileName, id, backupName, 0, addTime))
        public.WriteLog("TYPE_DATABASE", "DATABASE_BACKUP_SUCCESS", (name, ))
        return public.returnMsg(True, 'BACKUP_SUCCESS')
Ejemplo n.º 9
0
 def CopyDir(self,get):
     if sys.version_info[0] == 2:
         get.sfile = get.sfile.encode('utf-8');
         get.dfile = get.dfile.encode('utf-8');
     if not os.path.exists(get.sfile):
         return public.returnMsg(False,'DIR_NOT_EXISTS');
     
     if os.path.exists(get.dfile):
         return public.returnMsg(False,'DIR_EXISTS');
     
     #if not self.CheckDir(get.dfile):
     #    return public.returnMsg(False,'FILE_DANGER');
     
     import shutil
     try:
         shutil.copytree(get.sfile, get.dfile)
         stat = os.stat(get.sfile)
         os.chown(get.dfile,stat.st_uid,stat.st_gid)
         public.WriteLog('TYPE_FILE','DIR_COPY_SUCCESS',(get.sfile,get.dfile))
         return public.returnMsg(True,'DIR_COPY_SUCCESS')
     except:
         return public.returnMsg(False,'DIR_COPY_ERR')
Ejemplo n.º 10
0
    def start_run(self, run_name):
        '''
            @name 启动指定启动项
            @author hwliang<2021-08-06>
            @param run_name string<启动项名称>
            @return bool
        '''
        run_info = self.get_run_info(run_name)
        if not run_info: return False

        log_file = '{}/{}.log'.format(self.__run_logs_path, run_name)
        pid_file = '{}/{}.pid'.format(self.__run_pids_path, run_name)
        public.ExecShell("nohup {} 2>&1 >> {} & $! > {}".format(
            run_info['run_script'], log_file, pid_file),
                         cwd=run_info['run_path'],
                         env=run_info['run_env'])[0]
        time.sleep(1)
        pid = self.get_script_pid(run_info)
        public.writeFile(pid_file, str(pid))
        public.WriteLog(self.__log_name,
                        '开机启动{}成功, PID: {}'.format(run_name, pid))
        return True
Ejemplo n.º 11
0
 def DelAcceptPort(self,get):
     port = get.port
     id = get.id
     types=get.type
     type_list = ['tcp', 'udp']
     if not types in type_list: return public.returnMsg(False, 'FIREWALL_PORT_EXISTS')
     try:
         if(port == public.GetHost(True)): return public.returnMsg(False,'FIREWALL_PORT_PANEL')
         if self.__isUfw:
             public.ExecShell('ufw delete allow ' + port + '/' + types+ '');
         else:
             if self.__isFirewalld:
                 public.ExecShell('firewall-cmd --permanent --zone=public --remove-port='+port+'/' + types + '')
             else:
                 public.ExecShell('iptables -D INPUT -p tcp -m state --state NEW -m ' + types +' --dport '+port+' -j ACCEPT')
         public.WriteLog("TYPE_FIREWALL", 'FIREWALL_DROP_PORT',(port,))
         public.M('firewall').where("id=?",(id,)).delete()
         
         self.FirewallReload()
         return public.returnMsg(True,'DEL_SUCCESS')
     except:
         return public.returnMsg(False,'DEL_ERROR')
Ejemplo n.º 12
0
    def remove_command(self, args):
        '''
            @name 删除指定命令
            @author hwliang<2020-08-08>
            @param  args<dict_obj>{
                title<string> 标题
            }
            @return dict
        '''
        args.title = args.title.strip()
        command = self.get_command_list(sys_cmd=True)
        if not self.command_exists(command, args.title):
            return public.returnMsg(False, 'COMMAND_NOTEXIST')
        for i in range(len(command)):
            if command[i]['title'] == args.title:
                del (command[i])
                break

        self.save_command(command)
        public.WriteLog(self._log_type, 'DEL_COMMAND_COMMAND',
                        (str(args.title), ))
        return public.returnMsg(True, 'SET_SUCCESS')
Ejemplo n.º 13
0
    def _unzip(self, sfile, dfile, password, log_file):
        if sys.version_info[0] == 2:
            sfile = sfile.encode('utf-8')
            dfile = dfile.encode('utf-8')
        if not os.path.exists(sfile):
            return public.returnMsg(False, 'FILE_NOT_EXISTS')

        #判断压缩包格式
        if sfile[-4:] == '.zip':
            os.system("unzip -P '" + password + "' -o '" + sfile + "' -d '" +
                      dfile + "' &> " + log_file)
        elif sfile[-7:] == '.tar.gz' or sfile[-4:] == '.tgz':
            os.system("tar zxvf '" + sfile + "' -C '" + dfile + "' &> " +
                      log_file)
        elif sfile[-4:] == '.rar':
            rar_file = '/www/server/rar/unrar'
            if not os.path.exists(rar_file): self.install_rar()
            os.system('echo "' + password + '"|' + rar_file + ' x -u -y "' +
                      sfile + '" "' + dfile + '" &> ' + log_file)
        elif sfile[-4:] == '.war':
            os.system("unzip -P '" + password + "' -o '" + sfile + "' -d '" +
                      dfile + "' &> " + log_file)
        else:
            os.system("gunzip -c " + sfile + " > " + sfile[:-3])

        #检查是否设置权限
        if self.check_dir(dfile):
            sites_path = public.M('config').where('id=?',
                                                  (1, )).getField('sites_path')
            if dfile.find('/www/wwwroot') != -1 or dfile.find(
                    sites_path) != -1:
                self.set_file_accept(dfile)
            else:
                import pwd
                user = pwd.getpwuid(os.stat(dfile).st_uid).pw_name
                os.system("chown %s:%s %s" % (user, user, dfile))

        public.WriteLog("TYPE_FILE", 'UNZIP_SUCCESS', (sfile, dfile))
        return public.returnMsg(True, 'UNZIP_SUCCESS')
Ejemplo n.º 14
0
    def MvFile(self, get):
        get.sfile = get.sfile.encode('utf-8')
        get.dfile = get.dfile.encode('utf-8')
        if not self.CheckFileName(get.dfile):
            return public.returnMsg(False, '文件名不能包含特殊字符!')
        if not os.path.exists(get.sfile):
            return public.returnMsg(False, 'FILE_NOT_EXISTS')

        # if os.path.exists(get.dfile):
        #    return public.returnMsg(False,'FILE_EXISTS')

        if not self.CheckDir(get.sfile):
            return public.returnMsg(False, 'FILE_DANGER')

        import shutil
        try:
            shutil.move(get.sfile, get.dfile)
            public.WriteLog('TYPE_FILE', 'MOVE_SUCCESS',
                            (get.sfile, get.dfile))
            return public.returnMsg(True, 'MOVE_SUCCESS')
        except:
            return public.returnMsg(False, 'MOVE_ERR')
Ejemplo n.º 15
0
    def CopyFile(self, get):
        get.sfile = get.sfile.encode('utf-8')
        get.dfile = get.dfile.encode('utf-8')
        if not os.path.exists(get.sfile):
            return public.returnMsg(False, 'FILE_NOT_EXISTS')

        # if os.path.exists(get.dfile):
        #    return public.returnMsg(False,'FILE_EXISTS')

        if os.path.isdir(get.sfile):
            return self.CopyDir(get)

        import shutil
        try:
            shutil.copyfile(get.sfile, get.dfile)
            public.WriteLog('TYPE_FILE', 'FILE_COPY_SUCCESS',
                            (get.sfile, get.dfile))
            stat = os.stat(get.sfile)
            os.chown(get.dfile, stat.st_uid, stat.st_gid)
            return public.returnMsg(True, 'FILE_COPY_SUCCESS')
        except:
            return public.returnMsg(False, 'FILE_COPY_ERR')
Ejemplo n.º 16
0
 def get_task_lists(self,get):
     sql = public.M(self.__table)
     if 'status' in get:
         if get.status == '-3':
             sql = sql.where('status=? OR status=?',(-1,0))
         else:
             sql = sql.where('status=?',(get.status,))
     data = sql.field('id,name,type,shell,other,status,exectime,endtime,addtime').order('id asc').limit('10').select();
     if type(data) == str: 
         public.WriteLog('任务队列',data)
         return []
     if not 'num' in get: get.num = 15
     num = int(get.num)
     for i in range(len(data)):
         data[i]['log'] = ''
         if data[i]['status'] == -1: 
             data[i]['log'] = self.get_task_log(data[i]['id'],data[i]['type'],num)
         elif data[i]['status'] == 1:
             data[i]['log'] = self.get_task_log(data[i]['id'],data[i]['type'],10)
         if data[i]['type'] == '3':
             data[i]['other'] = json.loads(data[i]['other'])
     return data
Ejemplo n.º 17
0
 def GetDiskInfo2(self):
     #取磁盘分区信息
     temp = public.ExecShell("df -hT -P|grep '/'|grep -v tmpfs")[0]
     tempInodes = public.ExecShell("df -i -P|grep '/'|grep -v tmpfs")[0]
     temp1 = temp.split('\n')
     tempInodes1 = tempInodes.split('\n')
     diskInfo = []
     n = 0
     cuts = [
         '/mnt/cdrom', '/boot', '/boot/efi', '/dev', '/dev/shm',
         '/run/lock', '/run', '/run/shm', '/run/user'
     ]
     for tmp in temp1:
         n += 1
         try:
             inodes = tempInodes1[n - 1].split()
             disk = re.findall(
                 r"^(.+)\s+([\w]+)\s+([\w\.]+)\s+([\w\.]+)\s+([\w\.]+)\s+([\d%]{2,4})\s+(/.{0,50})$",
                 tmp.strip())
             if disk: disk = disk[0]
             if len(disk) < 6: continue
             if disk[2].find('M') != -1: continue
             if disk[2].find('K') != -1: continue
             if len(disk[6].split('/')) > 10: continue
             if disk[6] in cuts: continue
             if disk[6].find('docker') != -1: continue
             if disk[1].strip() in ['tmpfs']: continue
             arr = {}
             arr['filesystem'] = disk[0].strip()
             arr['type'] = disk[1].strip()
             arr['path'] = disk[6]
             tmp1 = [disk[2], disk[3], disk[4], disk[5]]
             arr['size'] = tmp1
             arr['inodes'] = [inodes[1], inodes[2], inodes[3], inodes[4]]
             diskInfo.append(arr)
         except Exception as ex:
             public.WriteLog('Access to information', str(ex))
             continue
     return diskInfo
Ejemplo n.º 18
0
 def GetDiskInfo2(self):
     #取磁盘分区信息
     key = 'sys_disk'
     diskInfo = cache.get(key)
     if diskInfo: return diskInfo
     temp = public.ExecShell("df -hT -P|grep '/'|grep -v tmpfs|grep -v 'snap/core'|grep -v udev")[0]
     tempInodes = public.ExecShell("df -i -P|grep '/'|grep -v tmpfs|grep -v 'snap/core'|grep -v udev")[0]
     temp1 = temp.split('\n')
     tempInodes1 = tempInodes.split('\n')
     diskInfo = []
     n = 0
     cuts = ['/mnt/cdrom','/boot','/boot/efi','/dev','/dev/shm','/run/lock','/run','/run/shm','/run/user']
     for tmp in temp1:
         n += 1
         try:
             inodes = tempInodes1[n-1].split()
             disk = re.findall(r"^(.+)\s+([\w\.]+)\s+([\w\.]+)\s+([\w\.]+)\s+([\w\.]+)\s+([\d%]{2,4})\s+(/.{0,100})$",tmp.strip())
             if disk: disk = disk[0]
             if len(disk) < 6: continue
             if disk[2].find('M') != -1: continue
             if disk[2].find('K') != -1: continue
             if len(disk[6].split('/')) > 10: continue
             if disk[6] in cuts: continue
             if disk[6].find('docker') != -1: continue
             if disk[1].strip() in ['tmpfs']: continue
             arr = {}
             arr['filesystem'] = disk[0].strip()
             arr['type'] = disk[1].strip()
             arr['path'] = disk[6].replace('/usr/local/lighthouse/softwares/btpanel','/www')
             tmp1 = [disk[2],disk[3],disk[4],disk[5]]
             arr['size'] = tmp1
             arr['inodes'] = [inodes[1],inodes[2],inodes[3],inodes[4]]
             diskInfo.append(arr)
         except Exception as ex:
             public.WriteLog('GET_INFO',str(ex))
             continue
     cache.set(key,diskInfo,360)
     return diskInfo
Ejemplo n.º 19
0
 def SaveFileBody(self,get):
     get.path = get.path.encode('utf-8');
     if not os.path.exists(get.path):
         if get.path.find('.htaccess') == -1:
             return public.returnMsg(False,'FILE_NOT_EXISTS')
     
     try:
         isConf = -1
         if os.path.exists('/etc/init.d/nginx') or os.path.exists('/etc/init.d/httpd'):
             isConf = get.path.find('nginx');
             if isConf == -1: isConf = get.path.find('apache');
             if isConf == -1: isConf = get.path.find('rewrite');
             if isConf != -1:
                 os.system('\\cp -a '+get.path+' /tmp/backup.conf');
         
         data = get.data[0];
         
         if get.path.find('/www/server/cron') != -1:
                 try:
                     import crontab
                     data = crontab.crontab().CheckScript(data);
                 except:
                     pass
         
         if get.encoding == 'ascii':get.encoding = 'utf-8';
         public.writeFile(get.path,data.encode(get.encoding));
         
         if isConf != -1:
             isError = public.checkWebConfig();
             if isError != True:
                 os.system('\\cp -a /tmp/backup.conf '+get.path);
                 return public.returnMsg(False,'ERROR:<br><font style="color:red;">'+isError.replace("\n",'<br>')+'</font>');
             public.serviceReload();
             
         public.WriteLog('TYPE_FILE','FILE_SAVE_SUCCESS',(get.path,));
         return public.returnMsg(True,'FILE_SAVE_SUCCESS');
     except:
         return public.returnMsg(False,'FILE_SAVE_ERR');
Ejemplo n.º 20
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 = web.ctx.session.setupPath + '/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 = web.ctx.session.setupPath + '/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]) < 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')
Ejemplo n.º 21
0
 def set_cli_php_version(self,get):
     php_bin = '/usr/bin/php'
     php_bin_src = "/www/server/php/%s/bin/php" % get.php_version
     php_ize = '/usr/bin/phpize'
     php_ize_src = "/www/server/php/%s/bin/phpize" % get.php_version
     php_fpm = '/usr/bin/php-fpm'
     php_fpm_src = "/www/server/php/%s/sbin/php-fpm" % get.php_version
     php_pecl = '/usr/bin/pecl'
     php_pecl_src = "/www/server/php/%s/bin/pecl" % get.php_version
     php_pear = '/usr/bin/pear'
     php_pear_src = "/www/server/php/%s/bin/pear" % get.php_version
     if not os.path.exists(php_bin_src): return public.returnMsg(False,'指定PHP版本未安装!')
     is_chattr = public.ExecShell('lsattr /usr|grep /usr/bin')[0].find('-i-')
     if is_chattr != -1: public.ExecShell('chattr -i /usr/bin')
     public.ExecShell("rm -f " + php_bin + ' '+ php_ize + ' ' + php_fpm + ' ' + php_pecl + ' ' + php_pear)
     public.ExecShell("ln -sf %s %s" % (php_bin_src,php_bin))
     public.ExecShell("ln -sf %s %s" % (php_ize_src,php_ize))
     public.ExecShell("ln -sf %s %s" % (php_fpm_src,php_fpm))
     public.ExecShell("ln -sf %s %s" % (php_pecl_src,php_pecl))
     public.ExecShell("ln -sf %s %s" % (php_pear_src,php_pear))
     if is_chattr != -1:  public.ExecShell('chattr +i /usr/bin')
     public.WriteLog('面板设置','设置PHP-CLI版本为: %s' % get.php_version)
     return public.returnMsg(True,'设置成功!')
Ejemplo n.º 22
0
    def UnZip(self, get):
        get.sfile = get.sfile.encode('utf-8')
        get.dfile = get.dfile.encode('utf-8')
        if not os.path.exists(get.sfile):
            return public.returnMsg(False, 'FILE_NOT_EXISTS')
        if not hasattr(get, 'password'): get.password = ''

        #try:
        if not hasattr(get, 'coding'): get.coding = 'UTF-8'
        tmps = '/tmp/panelExec.log'
        if get.sfile[-4:] == '.zip':
            os.system("export LANG=\"zh_CN." + get.coding +
                      "\" && unzip -P '" + get.password + "' -o '" +
                      get.sfile + "' -d '" + get.dfile + "' > " + tmps +
                      " 2>&1")
        elif get.sfile[-7:] == '.tar.gz' or get.sfile[-4:] == '.tgz':
            os.system("tar zxf '" + get.sfile + "' -C '" + get.dfile + "' > " +
                      tmps + " 2>&1")
        else:
            os.system("gunzip -c " + get.sfile + " > " + get.sfile[:-3])
        if self.CheckDir(get.dfile): self.SetFileAccept(get.dfile)
        public.WriteLog("TYPE_FILE", 'UNZIP_SUCCESS', (get.sfile, get.dfile))
        return public.returnMsg(True, 'UNZIP_SUCCESS')
Ejemplo n.º 23
0
 def Close_Recycle_bin(self, get):
     rPath = '/www/Recycle_bin/'
     os.system('chattr -R -i ' + rPath)
     import database, shutil
     rlist = os.listdir(rPath)
     i = 0
     l = len(rlist)
     for name in rlist:
         i += 1
         path = rPath + name
         public.writeSpeed(name, i, l)
         if name.find('BTDB_') != -1:
             database.database().DeleteTo(path)
             continue
         if os.path.isdir(path):
             #os.system('rm -rf ' + path);
             shutil.rmtree(path)
         else:
             #os.system('rm -f ' + path);
             os.remove(path)
     public.writeSpeed(None, 0, 0)
     public.WriteLog('TYPE_FILE', 'FILE_CLOSE_RECYCLE_BIN')
     return public.returnMsg(True, 'FILE_CLOSE_RECYCLE_BIN')
Ejemplo n.º 24
0
 def add_node(self, get):
     upName = get.upname
     node = {}
     node['server'] = get.server
     node['port'] = int(get.port)
     node['state'] = int(get.state)
     node['weight'] = int(get.weight)
     node['max_fails'] = int(get.max_fails)
     node['fail_timeout'] = int(get.fail_timeout)
     node['addtime'] = int(get.addtime)
     data = self.__read_config()
     for i in xrange(len(data)):
         if data[i]['name'] != upName: continue
         for n in data[i]['nodes']:
             if n['server'] == node['server'] and n['port'] == node['port']:
                 return public.returnMsg(False, '指定节点已存在!')
         data[i]['nodes'].append(node)
     self.__write_config(data)
     self.__write_to_conf(upName)
     public.WriteLog(
         '负载均衡', '添加节点[' + node['server'] + ':' + str(node['port']) +
         ']到负载均衡[' + upName + ']')
     return public.returnMsg(True, '节点添加成功!')
Ejemplo n.º 25
0
 def set_cli_php_version(self,get):
     php_bin = '/usr/bin/php'
     php_bin_src = "/www/server/php/%s/bin/php" % get.php_version
     php_ize = '/usr/bin/phpize'
     php_ize_src = "/www/server/php/%s/bin/phpize" % get.php_version
     php_fpm = '/usr/bin/php-fpm'
     php_fpm_src = "/www/server/php/%s/sbin/php-fpm" % get.php_version
     php_pecl = '/usr/bin/pecl'
     php_pecl_src = "/www/server/php/%s/bin/pecl" % get.php_version
     php_pear = '/usr/bin/pear'
     php_pear_src = "/www/server/php/%s/bin/pear" % get.php_version
     if not os.path.exists(php_bin_src): return public.returnMsg(False,'SPECIFIED_PHP_NOT_INSTALL')
     is_chattr = public.ExecShell('lsattr /usr|grep /usr/bin')[0].find('-i-')
     if is_chattr != -1: public.ExecShell('chattr -i /usr/bin')
     public.ExecShell("rm -f " + php_bin + ' '+ php_ize + ' ' + php_fpm + ' ' + php_pecl + ' ' + php_pear)
     public.ExecShell("ln -sf %s %s" % (php_bin_src,php_bin))
     public.ExecShell("ln -sf %s %s" % (php_ize_src,php_ize))
     public.ExecShell("ln -sf %s %s" % (php_fpm_src,php_fpm))
     public.ExecShell("ln -sf %s %s" % (php_pecl_src,php_pecl))
     public.ExecShell("ln -sf %s %s" % (php_pear_src,php_pear))
     if is_chattr != -1:  public.ExecShell('chattr +i /usr/bin')
     public.WriteLog('P_CONF','SET_PHP_CLI %s' % get.php_version)
     return public.returnMsg(True,'SET_SUCCESS')
Ejemplo n.º 26
0
    def backup_site(self, id, log_file):
        find = public.M('sites').where("id=?",
                                       (id, )).field('name,path,id').find()
        fileName = find['name']+'_' + \
            time.strftime('%Y%m%d_%H%M%S', time.localtime())+'.zip'
        backupPath = public.M('config').where(
            'id=?', (1, )).getField('backup_path') + '/site'

        zipName = backupPath + '/' + fileName
        if not (os.path.exists(backupPath)):
            os.makedirs(backupPath)

        execStr = "cd '" + find['path'] + "' && zip '" + \
            zipName + "' -x .user.ini -r ./ &> " + log_file
        public.ExecShell(execStr)

        sql = public.M('backup').add(
            'type,name,pid,filename,size,addtime',
            (0, fileName, find['id'], zipName, 0, public.getDate()))
        public.WriteLog('TYPE_SITE',
                        'SITE_BACKUP_SUCCESS', (find['name'], ),
                        not_web=self.not_web)
        return public.returnMsg(True, 'BACKUP_SUCCESS')
Ejemplo n.º 27
0
 def DeleteTo(self, filename):
     import json
     data = json.loads(public.readFile(filename))
     if public.M('databases').where("name=?", (data['name'], )).count():
         os.remove(filename)
         return public.returnMsg(True, 'DEL_SUCCESS')
     result = panelMysql.panelMysql().execute("drop database `" +
                                              data['name'] + "`")
     isError = self.IsSqlError(result)
     if isError != None: return isError
     panelMysql.panelMysql().execute("drop user '" + data['username'] +
                                     "'@'localhost'")
     users = panelMysql.panelMysql().query(
         "select Host from mysql.user where User='******'username'] +
         "' AND Host!='localhost'")
     for us in users:
         panelMysql.panelMysql().execute("drop user '" + data['username'] +
                                         "'@'" + us[0] + "'")
     panelMysql.panelMysql().execute("flush privileges")
     os.remove(filename)
     public.WriteLog("TYPE_DATABASE", 'DATABASE_DEL_SUCCESS',
                     (data['name'], ))
     return public.returnMsg(True, 'DEL_SUCCESS')
Ejemplo n.º 28
0
 def remove_safe_path(OO0OOOOOO0OOOO0O0, OO00OOOO0OOO0OO0O):  #line:101
     OO0O0O0O0OO0OO00O = OO0OOOOOO0OOOO0O0.__OO00OO00O0O00OO0O()  #line:102
     OO0000O0OO0O000OO = False  #line:103
     for OOO0O0O0OO000OOO0 in OO0O0O0O0OO0OO00O[
             OO00OOOO0OOO0OO0O.s_key]['paths']:  #line:104
         if OO00OOOO0OOO0OO0O.path == OOO0O0O0OO000OOO0['path']:  #line:105
             OO0000O0OO0O000OO = True  #line:106
             OO0O0O0O0OO0OO00O[OO00OOOO0OOO0OO0O.s_key]['paths'].remove(
                 OOO0O0O0OO000OOO0)  #line:107
             if os.path.exists(OO00OOOO0OOO0OO0O.path):
                 OO0OOOOOO0OOOO0O0.__OOOOOOOO0OOOO0000([OOO0O0O0OO000OOO0],
                                                       False)  #line:108
             break
             #line:109
     if not OO0000O0OO0O000OO:
         return public.returnMsg(False, '指定保护对象不存在!')  #line:110
     OO0OOOOOO0OOOO0O0.__OO00OOO0OO0O0O000(OO0O0O0O0OO0OO00O)  #line:111
     O000O00000OOOO00O = u'从[%s]删除保护对象[%s]' % (
         OO0O0O0O0OO0OO00O[OO00OOOO0OOO0OO0O.s_key]['name'],
         OO00OOOO0OOO0OO0O.path)  #line:112
     public.WriteLog(OO0OOOOOO0OOOO0O0.__O0O0O0O00O0O0OO00,
                     O000O00000OOOO00O)  #line:113
     return public.returnMsg(True, O000O00000OOOO00O)  #line:114
Ejemplo n.º 29
0
 def DelAcceptPort(self,get):
     port = get.port
     id = get.id
     try:
         if(port == public.GetHost(True) or port == public.readFile('data/port.pl').strip()): return public.returnMsg(False,'FIREWALL_PORT_PANEL')
         if self.__isUfw:
             public.ExecShell('ufw delete allow ' + port + '/tcp');
             public.ExecShell('ufw delete allow ' + port + '/udp');
         else:
             if self.__isFirewalld:
                 #self.__Obj.DelAcceptPort(port)
                 public.ExecShell('firewall-cmd --permanent --zone=public --remove-port='+port+'/tcp')
                 public.ExecShell('firewall-cmd --permanent --zone=public --remove-port='+port+'/udp')
             else:
                 public.ExecShell('iptables -D INPUT -p tcp -m state --state NEW -m tcp --dport '+port+' -j ACCEPT')
                 public.ExecShell('iptables -D INPUT -p tcp -m state --state NEW -m udp --dport '+port+' -j ACCEPT')
         public.WriteLog("TYPE_FIREWALL", 'FIREWALL_DROP_PORT',(port,))
         public.M('firewall').where("id=?",(id,)).delete()
         
         self.FirewallReload()
         return public.returnMsg(True,'DEL_SUCCESS')
     except:
         return public.returnMsg(False,'DEL_ERROR')
Ejemplo n.º 30
0
 def set_safe_status(O00O0OOO000O000OO, O0O00O0O000OOOOOO):  #line:44
     OOOOO0OOOO000O0OO = O00O0OOO000O000OO.__OO00OO00O0O00OO0O()  #line:45
     OOOOO0OOOO000O0OO[
         O0O00O0O000OOOOOO.s_key]['open'] = not OOOOO0OOOO000O0OO[
             O0O00O0O000OOOOOO.s_key]['open']  #line:46
     O00O0OOO000O000OO.__OO00OOO0OO0O0O000(OOOOO0OOOO000O0OO)  #line:47
     if type(OOOOO0OOOO000O0OO[O0O00O0O000OOOOOO.s_key]) != bool:  #line:48
         if 'paths' in OOOOO0OOOO000O0OO[
                 O0O00O0O000OOOOOO.s_key] and OOOOO0OOOO000O0OO['open']:
             O00O0OOO000O000OO.__OOOOOOOO0OOOO0000(
                 OOOOO0OOOO000O0OO[O0O00O0O000OOOOOO.s_key]['paths'],
                 OOOOO0OOOO000O0OO[
                     O0O00O0O000OOOOOO.s_key]['open'])  #line:49
     if O0O00O0O000OOOOOO.s_key in ['ssh', 'process'
                                    ] and OOOOO0OOOO000O0OO['open']:
         public.ExecShell("/etc/init.d/bt_syssafe restart")  #line:50
     OO0OO00O000OOO00O = u'已将[%s]状态设置为[%s]' % (
         OOOOO0OOOO000O0OO[O0O00O0O000OOOOOO.s_key]['name'],
         O00O0OOO000O000OO.__O0OOO0O00OOOO000O[OOOOO0OOOO000O0OO[
             O0O00O0O000OOOOOO.s_key]['open']])  #line:51
     public.WriteLog(O00O0OOO000O000OO.__O0O0O0O00O0O0OO00,
                     OO0OO00O000OOO00O)  #line:52
     return public.returnMsg(True, OO0OO00O000OOO00O)  #line:53