Пример #1
0
 def SetDataDir(self,get):
     if get.datadir[-1] == '/': get.datadir = get.datadir[0:-1];
     if os.path.exists(get.datadir): os.system('mkdir -p ' + get.datadir);
     mysqlInfo = self.GetMySQLInfo(get);
     if mysqlInfo['datadir'] == get.datadir: return public.returnMsg(False,'DATABASE_MOVE_RE');
     
     os.system('/etc/init.d/mysqld stop');
     os.system('\cp -a -r ' + mysqlInfo['datadir'] + '/* ' + get.datadir + '/');
     os.system('chown -R mysql.mysql ' + get.datadir);
     os.system('chmod -R 755 ' + get.datadir);
     os.system('rm -f ' + get.datadir + '/*.pid');
     os.system('rm -f ' + get.datadir + '/*.err');
     
     public.CheckMyCnf();
     myfile = '/etc/my.cnf';
     mycnf = public.readFile(myfile);
     public.writeFile('/etc/my_backup.cnf',mycnf);
     mycnf = mycnf.replace(mysqlInfo['datadir'],get.datadir);
     public.writeFile(myfile,mycnf);
     os.system('/etc/init.d/mysqld start');
     result = public.ExecShell('/etc/init.d/mysqld status');
     if result[0].find('SUCCESS') != -1:
         public.writeFile('data/datadir.pl',get.datadir);
         return public.returnMsg(True,'DATABASE_MOVE_SUCCESS');
     else:
         os.system('pkill -9 mysqld');
         public.writeFile(myfile,public.readFile('/etc/my_backup.cnf'));
         os.system('/etc/init.d/mysqld start');
         return public.returnMsg(False,'DATABASE_MOVE_ERR');
Пример #2
0
 def limitAddress(self,type):
     import time
     logFile = 'data/'+web.ctx.ip+'.login';
     timeFile = 'data/'+web.ctx.ip+'_time.login';
     limit = 6;
     outtime = 600;
     try:
         #初始化
         if not os.path.exists(timeFile): public.writeFile(timeFile,str(time.time()));
         if not os.path.exists(logFile): public.writeFile(logFile,'0');
         
         #判断是否解除登陆限制
         time1 = float(public.readFile(timeFile));
         if (time.time() - time1) > outtime: 
             public.writeFile(logFile,'0');
             public.writeFile(timeFile,str(time.time()));
         
         #计数
         num1 = int(public.readFile(logFile));
         if type == '+':
             num1 += 1;
             public.writeFile(logFile,str(num1));
             self.errorNum();
             web.ctx.session.code = True;
             return limit - num1;
         
         #清空
         if type == '-':
             public.ExecShell('rm -f data/*.login');
             web.ctx.session.code = False;
             return 1;
         return limit - num1;
     except:
         return limit;
Пример #3
0
 def GetSystemVersion(self):
     version = public.readFile('/etc/redhat-release')
     if not version:
         version = public.readFile('/etc/issue').replace('\\n \\l','').strip();
     else:
         version = version.replace('release ','').strip();
     return version
Пример #4
0
 def GetPHPConfig(self,version):
     import re
     setupPath = web.ctx.session.setupPath;
     file = setupPath + "/php/"+version+"/etc/php.ini"
     phpini = public.readFile(file)
     file = setupPath + "/php/"+version+"/etc/php-fpm.conf"
     phpfpm = public.readFile(file)
     data = {}
     try:
         rep = "upload_max_filesize\s*=\s*([0-9]+)M"
         tmp = re.search(rep,phpini).groups()
         data['max'] = tmp[0]
     except:
         data['max'] = '50'
     try:
         rep = "request_terminate_timeout\s*=\s*([0-9]+)\n"
         tmp = re.search(rep,phpfpm).groups()
         data['maxTime'] = tmp[0]
     except:
         data['maxTime'] = 0
     
     try:
         rep = ur"\n;*\s*cgi\.fix_pathinfo\s*=\s*([0-9]+)\s*\n"
         tmp = re.search(rep,phpini).groups()
         
         if tmp[0] == '1':
             data['pathinfo'] = True
         else:
             data['pathinfo'] = False
     except:
         data['pathinfo'] = False
     
     return data
Пример #5
0
 def get_phpmyadmin_dir(self):
     path = web.ctx.session.setupPath + '/phpmyadmin'
     if not os.path.exists(path): return None
     
     phpport = '888';
     try:
         import re;
         if web.ctx.session.webserver == 'nginx':
             filename = web.ctx.session.setupPath + '/nginx/conf/nginx.conf';
             conf = public.readFile(filename);
             rep = "listen\s+([0-9]+)\s*;";
             rtmp = re.search(rep,conf);
             if rtmp:
                 phpport = rtmp.groups()[0];
         else:
             filename = web.ctx.session.setupPath + '/apache/conf/extra/httpd-vhosts.conf';
             conf = public.readFile(filename);
             rep = "Listen\s+([0-9]+)\s*\n";
             rtmp = re.search(rep,conf);
             if rtmp:
                 phpport = rtmp.groups()[0];
     except:
         pass
         
     for filename in os.listdir(path):
         print filename
         filepath = path + '/' + filename
         if os.path.isdir(filepath):
             if filename[0:10] == 'phpmyadmin':
                 return str(filename),phpport
     
     return None
Пример #6
0
 def setPHPMaxSize(self,get):
     version = get.version
     max = get.max
     
     if int(max) < 2: return public.returnMsg(False,'PHP_UPLOAD_MAX_ERR')
     
     #设置PHP
     path = web.ctx.session.setupPath+'/php/'+version+'/etc/php.ini'
     conf = public.readFile(path)
     rep = u"\nupload_max_filesize\s*=\s*[0-9]+M"
     conf = re.sub(rep,u'\nupload_max_filesize = '+max+'M',conf)
     rep = u"\npost_max_size\s*=\s*[0-9]+M"
     conf = re.sub(rep,u'\npost_max_size = '+max+'M',conf)
     public.writeFile(path,conf)
     
     if public.get_webserver() == 'nginx':
         #设置Nginx
         path = web.ctx.session.setupPath+'/nginx/conf/nginx.conf'
         conf = public.readFile(path)
         rep = "client_max_body_size\s+([0-9]+)m"
         tmp = re.search(rep,conf).groups()
         if int(tmp[0]) < int(max):
             conf = re.sub(rep,'client_max_body_size '+max+'m',conf)
             public.writeFile(path,conf)
         
     public.serviceReload()
     public.phpReload(version);
     public.WriteLog("TYPE_PHP", "PHP_UPLOAD_MAX",(version,max))
     return public.returnMsg(True,'SET_SUCCESS')
Пример #7
0
 def setPathInfo(self,get):
     #设置PATH_INFO
     version = get.version
     type = get.type
     if public.get_webserver() == 'nginx':
         path = web.ctx.session.setupPath+'/nginx/conf/enable-php-'+version+'.conf';
         conf = public.readFile(path);
         rep = "\s+#*include\s+pathinfo.conf;";
         if type == 'on':
             conf = re.sub(rep,'\n\t\t\tinclude pathinfo.conf;',conf)
         else:
             conf = re.sub(rep,'\n\t\t\t#include pathinfo.conf;',conf)
         public.writeFile(path,conf)
         public.serviceReload();
     
     path = web.ctx.session.setupPath+'/php/'+version+'/etc/php.ini';
     conf = public.readFile(path);
     rep = "\n*\s*cgi\.fix_pathinfo\s*=\s*([0-9]+)\s*\n";
     status = '0'
     if type == 'on':status = '1'
     conf = re.sub(rep,"\ncgi.fix_pathinfo = "+status+"\n",conf)
     public.writeFile(path,conf)
     public.WriteLog("TYPE_PHP", "PHP_PATHINFO_SUCCESS",(version,type));
     public.phpReload(version);
     return public.returnMsg(True,'SET_SUCCESS');
Пример #8
0
 def GetSoftList(self,get):
     #取软件列表
     import json,os,web
     tmp = public.readFile('data/softList.conf');
     data = json.loads(tmp)
     tasks = public.M('tasks').where("status!=?",('1',)).field('status,name').select()
     for i in range(len(data)):
         data[i]['check'] = web.ctx.session.rootPath+'/'+data[i]['check'];
         for n in range(len(data[i]['versions'])):
             #处理任务标记
             isTask = '1';
             for task in tasks:
                 tmp = public.getStrBetween('[',']',task['name'])
                 if not tmp:continue;
                 tmp1 = tmp.split('-');
                 if data[i]['name'] == 'PHP': 
                     if tmp1[0].lower() == data[i]['name'].lower() and tmp1[1] == data[i]['versions'][n]['version']: isTask = task['status'];
                 else:
                     if tmp1[0].lower() == data[i]['name'].lower(): isTask = task['status'];
             
             #检查安装状态
             if data[i]['name'] == 'PHP': 
                 data[i]['versions'][n]['task'] = isTask
                 checkFile = data[i]['check'].replace('VERSION',data[i]['versions'][n]['version'].replace('.',''));
             else:
                 data[i]['task'] = isTask
                 version = public.readFile(web.ctx.session.rootPath+'/server/'+data[i]['name'].lower()+'/version.pl');
                 if not version:continue;
                 if version.find(data[i]['versions'][n]['version']) == -1:continue;
                 checkFile = data[i]['check'];
             data[i]['versions'][n]['status'] = os.path.exists(checkFile);
     return data
Пример #9
0
 def __Conn(self):
     try:
         import public
         try:
             import MySQLdb
         except Exception,ex:
             self.__DB_ERR = ex
             return False;
         try:
             myconf = public.readFile('/etc/my.cnf');
             rep = "port\s*=\s*([0-9]+)"
             self.__DB_PORT = int(re.search(rep,myconf).groups()[0]);
         except:
             self.__DB_PORT = 3306;
         self.__DB_PASS = public.M('config').where('id=?',(1,)).getField('mysql_root');
         try:
             if os.path.exists(self.__DB_HOST_CONF): self.__DB_HOST = public.readFile(self.__DB_HOST_CONF);
             self.__DB_CONN = MySQLdb.connect(host = self.__DB_HOST,user = self.__DB_USER,passwd = self.__DB_PASS,port = self.__DB_PORT,charset="utf8",connect_timeout=1)
         except MySQLdb.Error,e:
             if e[0] != 2003: 
                 self.__DB_ERR = e
                 return False
             if self.__DB_HOST == 'localhost':
                 self.__DB_HOST = '127.0.0.1';
             else:
                 self.__DB_HOST = 'localhost';
             public.writeFile(self.__DB_HOST_CONF,self.__DB_HOST);
             self.__DB_CONN = MySQLdb.connect(host = self.__DB_HOST,user = self.__DB_USER,passwd = self.__DB_PASS,port = self.__DB_PORT,charset="utf8",connect_timeout=1)
Пример #10
0
    def errorNum(self,s = True):
        numFile = '/tmp/panelNum.pl';
        timeFile = '/tmp/panelNime.pl';
        if os.path.exists(timeFile):
            stime = float(public.readFile(timeFile));
            etime = time.time() - stime;
            if etime < 1800: return False;
            os.remove(timeFile);
            os.remove(numFile);
        
        if not os.path.exists(numFile): 
            public.writeFile(numFile,'0');
            public.ExecShell('chmod 600 ' + numFile);
            
        num = int(public.readFile(numFile));

        if s:
            num +=1;
            public.writeFile(numFile,str(num));
        
        if num > 3:
            web.ctx.session.code = True;
        
        if num > 12:
            public.writeFile(timeFile,str(time.time()));
            public.ExecShell('chmod 600 ' + timeFile);
            return False;
        return True;
Пример #11
0
 def checkWebType(self):
     if os.path.exists(self.setupPath + '/nginx'):
         web.ctx.session.webserver = 'nginx'
     else:
         web.ctx.session.webserver = 'apache'
     if os.path.exists(self.setupPath+'/'+web.ctx.session.webserver+'/version.pl'):
         web.ctx.session.webversion = public.readFile(self.setupPath+'/'+web.ctx.session.webserver+'/version.pl').strip()
     filename = self.setupPath+'/data/phpmyadminDirName.pl'
     if os.path.exists(filename):
         web.ctx.session.phpmyadminDir = public.readFile(filename).strip()
Пример #12
0
 def close_ssh_limit(self,get):
     #清除白名单
     allowConf = public.readFile(self.__ALLOW);
     allowConf = re.sub("\n\s*sshd:\w{1,3}\.\w{1,3}\.\w{1,3}\.\w{1,3}:allow",'',allowConf);
     public.writeFile(self.__ALLOW,allowConf);
     
     #关闭限制
     denyConf = public.readFile(self.__DENY);
     denyConf = re.sub("sshd:ALL\s*","",denyConf);
     public.writeFile(self.__DENY,denyConf);
     return public.returnMsg(True,'清除成功!');
Пример #13
0
 def GetOS(self):
     if not hasattr(web.ctx.session,'server_os'):
         tmp = {}
         if os.path.exists('/etc/redhat-release'):
             tmp['x'] = 'RHEL';
             tmp['osname'] = public.readFile('/etc/redhat-release').split()[0];
         elif os.path.exists('/etc/issue'): 
             tmp['x'] = 'Debian';
             tmp['osname'] = public.readFile('/etc/issue').split()[0];
         web.ctx.session.server_os = tmp
         
Пример #14
0
 def install(self,get):
     pluginInfo = self.GetFind(get.name);
     if not pluginInfo:
         import json
         pluginInfo = json.loads(public.readFile(self.__install_path + '/' + get.name + '/info.json'));
     
     if pluginInfo['tip'] == 'lib':
         if not os.path.exists(self.__install_path + '/' + pluginInfo['name']): os.system('mkdir -p ' + self.__install_path + '/' + pluginInfo['name']);
         if not hasattr(web.ctx.session,'downloadUrl'): web.ctx.session.downloadUrl = 'http://download.bt.cn';
         downloadUrl = web.ctx.session.downloadUrl + '/install/lib/plugin/' + pluginInfo['name'] + '/install.sh';
         toFile = self.__install_path + '/' + pluginInfo['name'] + '/install.sh';
         public.downloadFile(downloadUrl,toFile);
         os.system('/bin/bash ' + toFile + ' install');
         if self.checksSetup(pluginInfo['name'],pluginInfo['checks'],pluginInfo['versions'])[0]['status'] or os.path.exists(self.__install_path + '/' + get.name):
             public.WriteLog('TYPE_SETUP','PLUGIN_INSTALL_LIB',(pluginInfo['title'],));
             os.system('rm -f ' + toFile);
             return public.returnMsg(True,'PLUGIN_INSTALL_SUCCESS');
         return public.returnMsg(False,'PLUGIN_INSTALL_ERR');
     else:
         import db,time
         path = web.ctx.session.setupPath + '/php'
         if not os.path.exists(path): os.system("mkdir -p " + path);
         issue = public.readFile('/etc/issue')
         if web.ctx.session.server_os['x'] != 'RHEL': get.type = '3'
         
         apacheVersion='false';
         if public.get_webserver() == 'apache':
             apacheVersion = public.readFile(web.ctx.session.setupPath+'/apache/version.pl');
         public.writeFile('/var/bt_apacheVersion.pl',apacheVersion)
         public.writeFile('/var/bt_setupPath.conf',web.ctx.session.rootPath)
         isTask = '/tmp/panelTask.pl'
         
         mtype = 'install';
         mmsg = '安装';
         if hasattr(get, 'upgrade'):
             if get.upgrade:
                 mtype = 'update';
                 mmsg = 'upgrade';
         execstr = "cd " + web.ctx.session.setupPath + "/panel/install && /bin/bash install_soft.sh " + get.type + " "+mtype+" " + 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, mmsg + '['+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));
         return public.returnMsg(True,'PLUGIN_INSTALL');
Пример #15
0
 def DelCrontab(self,get):
     try:
         id = get['id']
         find = public.M('crontab').where("id=?",(id,)).field('name,echo').find()
         x = web.ctx.session.server_os['x'];
         if x == 'RHEL':
             file='/var/spool/cron/root'
         else:
             file='/var/spool/cron/crontabs/root'
         conf=public.readFile(file)
         rep = ".+" + str(find['echo']) + ".+\n"
         conf = re.sub(rep, "", conf)
         cronPath = web.ctx.session.setupPath + '/cron'
         public.writeFile(file,conf)
         
         sfile = cronPath + '/' + find['echo']
         if os.path.exists(sfile): os.remove(sfile)
         sfile = cronPath + '/' + find['echo'] + '.log'
         if os.path.exists(sfile): os.remove(sfile)
         
         self.CrondReload()
         public.M('crontab').where("id=?",(id,)).delete()
         public.WriteLog('TYPE_CRON', 'CRONTAB_DEL',(find['name'],))
         return public.returnMsg(True, 'DEL_SUCCESS')
     except:
         return public.returnMsg(False, 'DEL_ERROR')
Пример #16
0
 def BinLog(self,get):
     myfile = '/etc/my.cnf';
     mycnf = public.readFile(myfile);
     if mycnf.find('#log-bin=mysql-bin') != -1:
         if hasattr(get,'status'): return public.returnMsg(False,'0');
         mycnf = mycnf.replace('#log-bin=mysql-bin','log-bin=mysql-bin')
         mycnf = mycnf.replace('#binlog_format=mixed','binlog_format=mixed')
         os.system('sync')
         os.system('/etc/init.d/mysqld restart');
     else:
         path = self.GetMySQLInfo(get)['datadir'];
         if hasattr(get,'status'): 
             dsize = 0;
             for n in os.listdir(path):
                 if len(n) < 9: continue;
                 if n[0:9] == 'mysql-bin':
                     dsize += os.path.getsize(path + '/' + n);
             return public.returnMsg(True,dsize);
         
         mycnf = mycnf.replace('log-bin=mysql-bin','#log-bin=mysql-bin')
         mycnf = mycnf.replace('binlog_format=mixed','#binlog_format=mixed')
         os.system('sync')
         os.system('/etc/init.d/mysqld restart');
         os.system('rm -f ' + path + '/mysql-bin.*')
     
     public.writeFile(myfile,mycnf);
     return public.returnMsg(True,'SUCCESS');
Пример #17
0
 def SetSshPort(self,get):
     #return public.returnMsg(False,'演示服务器,禁止此操作!');
     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 = "#*Port\s+([0-9]+)\s*\n"
     conf = re.sub(rep, "Port "+port+"\n", conf)
     public.writeFile(file,conf)
     
     if self.__isFirewalld:
         self.__Obj.AddAcceptPort(port);
         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=?",('SSH远程管理服务',)).setField('port',port)
     public.WriteLog("TYPE_FIREWALL", "FIREWALL_SSH_PORT",(port,))
     return public.returnMsg(True,'EDIT_SUCCESS') 
Пример #18
0
 def add_ssh_limit(self,get):
     ip = get.ip;
     denyConf = public.readFile(self.__DENY);
     if denyConf.find('sshd:ALL') == -1:
         while denyConf[-1:] == "\n" or denyConf[-1:] == " ": denyConf = denyConf[:-1];
         denyConf += "\nsshd:ALL\n";
         public.writeFile(self.__DENY,denyConf);
     if ip in self.get_ssh_limit(): return public.returnMsg(True,'指定IP白名单已存在!');
     
     allowConf = public.readFile(self.__ALLOW).strip();
     while allowConf[-1:] == "\n" or allowConf[-1:] == " ": allowConf = allowConf[:-1];
     allowConf += "\nsshd:" + ip+":allow\n";
     public.writeFile(self.__ALLOW,allowConf);
     
     if ip in self.get_ssh_limit(): return public.returnMsg(True,'添加成功!');
     return public.returnMsg(False,'添加失败!');
Пример #19
0
 def AddPackage(self,get):
     jsonFile = self.__setupPath + '/list.json';
     if not os.path.exists(jsonFile): return public.returnMsg(False,'配置文件不存在!');
     
     data = {}
     data = json.loads(public.readFile(jsonFile));
     for d in data:
         if d['name'] == get.dname: return public.returnMsg(False,'您要添加的程序标识已存在!');
         if d['title'] == get.title: return public.returnMsg(False,'您要添加的程序名称已存在!');
     
     if hasattr(get,'rewrite'): get.rewrite = True;
     
     pinfo = {}
     pinfo['name'] = get.dname;
     pinfo['title'] = get.title;
     pinfo['version'] = get.version;
     pinfo['md5'] = get.md5;
     pinfo['rewrite'] = get.rewrite;
     pinfo['php'] = get.php;
     pinfo['ps'] = get.ps;
     pinfo['shell'] = get.shell;
     pinfo['download'] = get.download;
     data.append(pinfo);
     public.writeFile(jsonFile,json.dumps(data));
     return public.returnMsg(True,'添加成功!');
Пример #20
0
 def GetLibInfo(self,name):
     import json
     tmp = public.readFile('data/libList.conf');
     data = json.loads(tmp)
     for lib in data:
         if name == lib['opt']: return lib;
     return False;
Пример #21
0
 def checkRule(self):
     ruleFile = 'data/rule.json';
     if not os.path.exists(ruleFile): return False;
     toPath = web.ctx.path.replace('/','');
     ruleList = public.readFile(ruleFile).split('|');
     if toPath in ruleList: return True;
     return False;
Пример #22
0
 def GetConfig(self,get):
     try:
         cfile = self.__setupPath + '/config.conf'
         if not os.path.exists(cfile): cfile = 'data/beta.pl'
         return public.readFile(cfile).strip();
     except:
         return 'False';
Пример #23
0
 def GetWarning(self,get):
     warningFile = 'data/warning.json'
     if not os.path.exists(warningFile): return public.returnMsg(False,'警告列表不存在!');
     import json,time;
     wlist = json.loads(public.readFile(warningFile));
     wlist['time'] = int(time.time());
     return wlist;
Пример #24
0
 def ResDatabasePassword(self,get):
     try:
         newpassword = get['password']
         username = get['username']
         id = get['id']
         name = public.M('databases').where('id=?',(id,)).getField('name');
         rep = "^[\w#@%\.]+$"
         if len(re.search(rep, newpassword).groups()) > 0: return public.returnMsg(False, 'DATABASE_NAME_ERR_T')
         
         #修改MYSQL
         if '5.7' in public.readFile(web.ctx.session.setupPath + '/mysql/version.pl'):
             result = panelMysql.panelMysql().execute("update mysql.user set authentication_string=password('" + newpassword + "') where User='******'")
         else:
             result = panelMysql.panelMysql().execute("update mysql.user set Password=password('" + newpassword + "') where User='******'")
         
         isError=self.IsSqlError(result)
         if  isError != None: return isError
         panelMysql.panelMysql().execute("flush privileges")
         #if result==False: return public.returnMsg(False,'DATABASE_PASS_ERR_NOT_EXISTS')
         #修改SQLITE
         if int(id) > 0:
             public.M('databases').where("id=?",(id,)).setField('password',newpassword)
         else:
             public.M('config').where("id=?",(id,)).setField('mysql_root',newpassword)
             web.ctx.session.config['mysql_root'] = newpassword
         
         public.WriteLog("TYPE_DATABASE",'DATABASE_PASS_SUCCESS',(name,))
         return public.returnMsg(True,'DATABASE_PASS_SUCCESS',(name,))
     except Exception,ex:
         public.WriteLog("TYPE_DATABASE", 'DATABASE_PASS_ERROR',(name,str(ex)))
         return public.returnMsg(False,'DATABASE_PASS_ERROR',(name,))
Пример #25
0
 def GetPHPConf(self,get):
     gets = [
             {'name':'short_open_tag','type':1,'ps':public.getMsg('PHP_CONF_1')},
             {'name':'asp_tags','type':1,'ps':public.getMsg('PHP_CONF_2')},
             {'name':'max_execution_time','type':2,'ps':public.getMsg('PHP_CONF_4')},
             {'name':'max_input_time','type':2,'ps':public.getMsg('PHP_CONF_5')},
             {'name':'memory_limit','type':2,'ps':public.getMsg('PHP_CONF_6')},
             {'name':'post_max_size','type':2,'ps':public.getMsg('PHP_CONF_7')},
             {'name':'file_uploads','type':1,'ps':public.getMsg('PHP_CONF_8')},
             {'name':'upload_max_filesize','type':2,'ps':public.getMsg('PHP_CONF_9')},
             {'name':'max_file_uploads','type':2,'ps':public.getMsg('PHP_CONF_10')},
             {'name':'default_socket_timeout','type':2,'ps':public.getMsg('PHP_CONF_11')},
             {'name':'error_reporting','type':3,'ps':public.getMsg('PHP_CONF_12')},
             {'name':'display_errors','type':1,'ps':public.getMsg('PHP_CONF_13')},
             {'name':'cgi.fix_pathinfo','type':0,'ps':public.getMsg('PHP_CONF_14')},
             {'name':'date.timezone','type':3,'ps':public.getMsg('PHP_CONF_15')}
             ]
     phpini = public.readFile('/www/server/php/' + get.version + '/etc/php.ini');
     
     result = []
     for g in gets:
         rep = g['name'] + '\s*=\s*([0-9A-Za-z_& ~]+)(\s*;?|\r?\n)';
         tmp = re.search(rep,phpini)
         if not tmp: continue;
         g['value'] = tmp.groups()[0];
         result.append(g);
     
     return result;
Пример #26
0
 def GetType(self,get = None):
     try:
         if not os.path.exists(self.__type): return False;
         data = json.loads(public.readFile(self.__type));
         return data
     except:
         return False;
Пример #27
0
 def getFpmConfig(self,get):
     version = get.version;
     file = web.ctx.session.setupPath+"/php/"+version+"/etc/php-fpm.conf";
     conf = public.readFile(file);
     data = {}
     rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*";
     tmp = re.search(rep, conf).groups();
     data['max_children'] = tmp[0];
     
     rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*";
     tmp = re.search(rep, conf).groups();
     data['start_servers'] = tmp[0];
     
     rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*";
     tmp = re.search(rep, conf).groups();
     data['min_spare_servers'] = tmp[0];
     
     rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*";
     tmp = re.search(rep, conf).groups();
     data['max_spare_servers'] = tmp[0];
     
     rep = "\s*pm\s*=\s*(\w+)\s*";
     tmp = re.search(rep, conf).groups();
     data['pm'] = tmp[0];
     
     return data
Пример #28
0
 def GetFileBody(self,get) :
     get.path = get.path.encode('utf-8');
     if not os.path.exists(get.path):
         if get.path.find('rewrite') == -1:
             return public.returnMsg(False,'FILE_NOT_EXISTS')
         public.writeFile(get.path,'');
     try:
         if os.path.getsize(get.path) > 2097152: return public.returnMsg(False,'不能在线编辑大于2MB的文件!');
         srcBody = public.readFile(get.path)
         
         data = {}
         if srcBody:
             import chardet
             char=chardet.detect(srcBody)
             data['encoding'] = char['encoding']
             if char['encoding'] == 'GB2312': data['encoding'] = 'GBK';
             if char['encoding'] == 'ascii': data['encoding'] = 'utf-8'
             data['data'] = srcBody.decode(data['encoding']).encode('utf-8')
         else:
             data['data'] = srcBody
             data['encoding'] = 'utf-8'
         
         data['status'] = True
         return data
     except Exception,ex:
         return public.returnMsg(False,'FILE_GET_ERR' + str(ex))
Пример #29
0
 def GetTaskSpeed(self,get):
     tempFile = '/tmp/panelExec.log'
     freshFile = '/tmp/panelFresh'
     import db
     find = db.Sql().table('tasks').where('status=? OR status=?',('-1','0')).field('id,type,name,execstr').find()
     if not len(find): return public.returnMsg(False,'当前没有任务队列在执行-2!')
     isTask = '/tmp/panelTask.pl'
     public.writeFile(isTask,'True');
     echoMsg = {}
     echoMsg['name'] = find['name']
     echoMsg['execstr'] = find['execstr']
     if find['type'] == 'download':
         import json
         try:
             tmp = public.readFile(tempFile)
             if len(tmp) < 10:
                 return public.returnMsg(False,'当前没有任务队列在执行-3!')
             echoMsg['msg'] = json.loads(tmp)
             echoMsg['isDownload'] = True
         except:
             db.Sql().table('tasks').where("id=?",(find['id'],)).save('status',('0',))
             return public.returnMsg(False,'当前没有任务队列在执行-4!')
     else:
         echoMsg['msg'] = self.GetLastLine(tempFile,20)
         echoMsg['isDownload'] = False
     
     echoMsg['task'] = public.M('tasks').where("status!=?",('1',)).field('id,status,name,type').order("id asc").select()
     return echoMsg
Пример #30
0
 def setFpmConfig(self,get):
     version = get.version
     max_children = get.max_children
     start_servers = get.start_servers
     min_spare_servers = get.min_spare_servers
     max_spare_servers = get.max_spare_servers
     pm = get.pm
     
     file = web.ctx.session.setupPath+"/php/"+version+"/etc/php-fpm.conf";
     conf = public.readFile(file);
     
     rep = "\s*pm.max_children\s*=\s*([0-9]+)\s*";
     conf = re.sub(rep, "\npm.max_children = "+max_children, conf);
     
     rep = "\s*pm.start_servers\s*=\s*([0-9]+)\s*";
     conf = re.sub(rep, "\npm.start_servers = "+start_servers, conf);
     
     rep = "\s*pm.min_spare_servers\s*=\s*([0-9]+)\s*";
     conf = re.sub(rep, "\npm.min_spare_servers = "+min_spare_servers, conf);
     
     rep = "\s*pm.max_spare_servers \s*=\s*([0-9]+)\s*";
     conf = re.sub(rep, "\npm.max_spare_servers = "+max_spare_servers+"\n", conf);
     
     rep = "\s*pm\s*=\s*(\w+)\s*";
     conf = re.sub(rep, "\npm = "+pm+"\n", conf);
     
     public.writeFile(file,conf)
     public.phpReload(version);
     public.WriteLog("TYPE_PHP",'PHP_CHILDREN', (version,max_children,start_servers,min_spare_servers,max_spare_servers));
     return public.returnMsg(True, 'SET_SUCCESS');
Пример #31
0
def bt_cli(u_input=0):
    raw_tip = "==============================================="
    if not u_input:
        print("===============宝塔面板命令行==================")
        print("(1) 重启面板服务           (8) 改面板端口")
        print("(2) 停止面板服务           (9) 清除面板缓存")
        print("(3) 启动面板服务           (10) 清除登录限制")
        print("(4) 重载面板服务           (11) 取消入口限制")
        print("(5) 修改面板密码           (12) 取消域名绑定限制")
        print("(6) 修改面板用户名         (13) 取消IP访问限制")
        print("(7) 强制修改MySQL密码      (14) 查看面板默认信息")
        print("(22) 显示面板错误日志      (15) 清理系统垃圾")
        print("(23) 关闭BasicAuth认证     (16) 修复面板(检查错误并更新面板文件到最新版)")
        print("(0) 取消                   ")
        print(raw_tip)
        try:
            u_input = input("请输入命令编号:")
            if sys.version_info[0] == 3: u_input = int(u_input)
        except:
            u_input = 0

    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 22, 23]
    if not u_input in nums:
        print(raw_tip)
        print("已取消!")
        exit()

    print(raw_tip)
    print("正在执行(%s)..." % u_input)
    print(raw_tip)

    if u_input == 1:
        os.system("/etc/init.d/bt restart")
    elif u_input == 2:
        os.system("/etc/init.d/bt stop")
    elif u_input == 3:
        os.system("/etc/init.d/bt start")
    elif u_input == 4:
        os.system("/etc/init.d/bt reload")
    elif u_input == 5:
        if sys.version_info[0] == 2:
            input_pwd = raw_input("请输入新的面板密码:")
        else:
            input_pwd = input("请输入新的面板密码:")
        set_panel_pwd(input_pwd.strip(), True)
    elif u_input == 6:
        if sys.version_info[0] == 2:
            input_user = raw_input("请输入新的面板用户名(>5位):")
        else:
            input_user = input("请输入新的面板用户名(>5位):")
        set_panel_username(input_user.strip())
    elif u_input == 7:
        if sys.version_info[0] == 2:
            input_mysql = raw_input("请输入新的MySQL密码:")
        else:
            input_mysql = input("请输入新的MySQL密码:")
        if not input_mysql:
            print("|-错误,不能设置空密码")
            return

        if len(input_mysql) < 8:
            print("|-错误,长度不能少于8位")
            return

        import re
        rep = "^[\w@\._]+$"
        if not re.match(rep, input_mysql):
            print("|-错误,密码中不能包含特殊符号")
            return

        print(input_mysql)
        set_mysql_root(input_mysql.strip())
    elif u_input == 8:
        input_port = input("请输入新的面板端口:")
        if sys.version_info[0] == 3: input_port = int(input_port)
        if not input_port:
            print("|-错误,未输入任何有效端口")
            return
        if input_port in [80, 443, 21, 20, 22]:
            print("|-错误,请不要使用常用端口作为面板端口")
            return
        old_port = int(public.readFile('data/port.pl'))
        if old_port == input_port:
            print("|-错误,与面板当前端口一致,无需修改")
            return

        is_exists = public.ExecShell("lsof -i:%s|grep LISTEN|grep -v grep" %
                                     input_port)
        if len(is_exists[0]) > 5:
            print("|-错误,指定端口已被其它应用占用")
            return

        public.writeFile('data/port.pl', str(input_port))
        if os.path.exists("/usr/bin/firewall-cmd"):
            os.system(
                "firewall-cmd --permanent --zone=public --add-port=%s/tcp" %
                input_port)
            os.system("firewall-cmd --reload")
        elif os.path.exists("/etc/sysconfig/iptables"):
            os.system(
                "iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport %s -j ACCEPT"
                % input_port)
            os.system("service iptables save")
        else:
            os.system("ufw allow %s" % input_port)
            os.system("ufw reload")
        os.system("/etc/init.d/bt reload")
        print("|-已将面板端口修改为:%s" % input_port)
        print(
            "|-若您的服务器提供商是[阿里云][腾讯云][华为云]或其它开启了[安全组]的服务器,请在安全组放行[%s]端口才能访问面板" %
            input_port)
    elif u_input == 9:
        sess_file = '/dev/shm/session.db'
        if os.path.exists(sess_file): os.remove(sess_file)
        os.system("/etc/init.d/bt reload")
    elif u_input == 10:
        os.system("/etc/init.d/bt reload")
    elif u_input == 11:
        auth_file = 'data/admin_path.pl'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("/etc/init.d/bt reload")
        print("|-已取消入口限制")
    elif u_input == 12:
        auth_file = 'data/domain.conf'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("/etc/init.d/bt reload")
        print("|-已取消域名访问限制")
    elif u_input == 13:
        auth_file = 'data/limitip.conf'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("/etc/init.d/bt reload")
        print("|-已取消IP访问限制")
    elif u_input == 14:
        os.system("/etc/init.d/bt default")
    elif u_input == 15:
        ClearSystem()
    elif u_input == 16:
        os.system("curl http://download.bt.cn/install/update6.sh|bash")
    elif u_input == 22:
        os.system('tail -100 /www/server/panel/logs/error.log')
    elif u_input == 23:
        filename = '/www/server/panel/config/basic_auth.json'
        if os.path.exists(filename): os.remove(filename)
        os.system('bt reload')
        print("|-已关闭BasicAuth认证")
Пример #32
0
    def setPHPMyAdmin(self, get):
        import re
        #try:
        if public.get_webserver() == 'nginx':
            filename = public.GetConfigValue(
                'setup_path') + '/nginx/conf/nginx.conf'
        else:
            filename = public.GetConfigValue(
                'setup_path') + '/apache/conf/extra/httpd-vhosts.conf'

        conf = public.readFile(filename)
        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, ))
Пример #33
0
 def GetKey(self, get):
     file = '/root/.ssh/id_rsa'
     if not os.path.exists(file): return public.returnMsg(True, '')
     ret = public.readFile(file)
     return public.returnMsg(True, ret)
Пример #34
0
 def __check_panel_domain(self):
     domain = public.readFile("/www/server/panel/data/domain.conf")
     if not domain:
         return False
     return domain
Пример #35
0
 def GetExecShellMsg(self, get):
     fileName = '/tmp/panelShell.pl'
     if not os.path.exists(fileName): return 'FILE_SHELL_EMPTY'
     return public.readFile('/tmp/panelShell.pl')
Пример #36
0
def PackagePanel():
    print('========================================================')
    print('|-' + public.GetMsg("CLEARING_LOG") + '...'),
    public.M('logs').where('id!=?', (0, )).delete()
    print('\t\t\033[1;32m[done]\033[0m')
    print('|-' + public.GetMsg("CLEARING_TASK_HISTORY") + '...'),
    public.M('tasks').where('id!=?', (0, )).delete()
    print('\t\t\033[1;32m[done]\033[0m')
    print('|-' + public.GetMsg("CLEARING_NET_MO") + '...'),
    public.M('network').dbfile('system').where('id!=?', (0, )).delete()
    print('\t\033[1;32m[done]\033[0m')
    print('|-' + public.GetMsg("CLEARING_CPU_MO") + '...'),
    public.M('cpuio').dbfile('system').where('id!=?', (0, )).delete()
    print('\t\033[1;32m[done]\033[0m')
    print('|-' + public.GetMsg("CLEARING_DISK_MO") + '...'),
    public.M('diskio').dbfile('system').where('id!=?', (0, )).delete()
    print('\t\033[1;32m[done]\033[0m')
    print('|-' + public.GetMsg("CLEARING_IP") + '...'),
    os.system('rm -f /www/server/panel/data/iplist.txt')
    os.system('rm -f /www/server/panel/data/address.pl')
    os.system('rm -f /www/server/panel/data/*.login')
    os.system('rm -f /www/server/panel/data/domain.conf')
    os.system('rm -f /www/server/panel/data/user*')
    os.system('rm -f /www/server/panel/data/admin_path.pl')
    os.system('rm -f /root/.ssh/*')

    print('\t\033[1;32m[done]\033[0m')
    print('|-' + public.GetMsg("CLEARING_SYS_HISTORY") + '...'),
    command = '''cat /dev/null > /var/log/boot.log
cat /dev/null > /var/log/btmp
cat /dev/null > /var/log/cron
cat /dev/null > /var/log/dmesg
cat /dev/null > /var/log/firewalld
cat /dev/null > /var/log/grubby
cat /dev/null > /var/log/lastlog
cat /dev/null > /var/log/mail.info
cat /dev/null > /var/log/maillog
cat /dev/null > /var/log/messages
cat /dev/null > /var/log/secure
cat /dev/null > /var/log/spooler
cat /dev/null > /var/log/syslog
cat /dev/null > /var/log/tallylog
cat /dev/null > /var/log/wpa_supplicant.log
cat /dev/null > /var/log/wtmp
cat /dev/null > /var/log/yum.log
history -c
'''
    os.system(command)
    print('\t\033[1;32m[done]\033[0m')

    print("|-Please select user initialization method:")
    print("=" * 50)
    print(" (1) Display the initialization page when accessing the panel page")
    print(
        " (2) A new account password is automatically generated randomly when first started"
    )
    print("=" * 50)
    p_input = input("Please select the initialization method (default: 1):")
    print(p_input)
    if p_input in [2, '2']:
        public.writeFile('/www/server/panel/aliyun.pl', "True")
        s_file = '/www/server/panel/install.pl'
        if os.path.exists(s_file): os.remove(s_file)
        public.M('config').where("id=?", ('1', )).setField('status', 1)
    else:
        public.writeFile('/www/server/panel/install.pl', "True")
        public.M('config').where("id=?", ('1', )).setField('status', 0)
    port = public.readFile('data/port.pl').strip()
    print('========================================================')
    print(
        '\033[1;32m|-The panel packaging is successful, please do not log in to the panel to do any other operations!\033[0m'
    )
    if not p_input in [2, '2']:
        print('\033[1;41m|-Panel initialization address:http://{SERVERIP}:' +
              port + '/install\033[0m')
    else:
        print(
            '\033[1;41m|-Get the initial account password command:bt default \033[0m'
        )
Пример #37
0
    def set_sshd_config(self, rep=False):
        '''
            @name 设置本地SSH配置文件,以支持pubkey认证
            @author hwliang<2020-08-13>
            @param rep<bool> 是否恢复ssh配置文件
            @return bool
        '''
        self.is_running(rep)
        return False
        if rep and not self._rep_ssh_config:
            return False

        try:
            sshd_config_file = '/etc/ssh/sshd_config'
            if not os.path.exists(sshd_config_file):
                return False

            sshd_config = public.readFile(sshd_config_file)

            if not sshd_config:
                return False

            if rep:
                if self._sshd_config_backup:
                    public.writeFile(sshd_config_file,
                                     self._sshd_config_backup)
                    self.restart_ssh()
                return True

            pin = r'^\s*PubkeyAuthentication\s+(yes|no)'
            pubkey_status = re.findall(pin, sshd_config, re.I)
            if pubkey_status:
                if pubkey_status[0] == 'yes':
                    pubkey_status = True
                else:
                    pubkey_status = False

            pin = r'^\s*RSAAuthentication\s+(yes|no)'
            rsa_status = re.findall(pin, sshd_config, re.I)
            if rsa_status:
                if rsa_status[0] == 'yes':
                    rsa_status = True
                else:
                    rsa_status = False

            self._sshd_config_backup = sshd_config
            is_write = False
            if not pubkey_status:
                sshd_config = re.sub(r'\n#?PubkeyAuthentication\s\w+',
                                     '\nPubkeyAuthentication yes', sshd_config)
                is_write = True
            if not rsa_status:
                sshd_config = re.sub(r'\n#?RSAAuthentication\s\w+',
                                     '\nRSAAuthentication yes', sshd_config)
                is_write = True

            if is_write:
                public.writeFile(sshd_config_file, sshd_config)
                self._rep_ssh_config = True
                self.restart_ssh()
            else:
                self._sshd_config_backup = None

            return True
        except:
            return False
Пример #38
0
    def get_task_log(self, id, task_type, num=5):
        log_file = self.__task_path + str(id) + '.log'
        if not os.path.exists(log_file):
            data = ''
            if (task_type == '1'):
                data = {
                    'name': '下载文件',
                    'total': 0,
                    'used': 0,
                    'pre': 0,
                    'speed': 0,
                    'time': 0
                }
            return data

        if (task_type == '1'):
            total = 0
            if not os.path.exists(self.down_log_total_file):
                f = open(log_file, 'r')
                head = f.read(4096)
                content_length = re.findall(r"Length:\s+(\d+)", head)
                if content_length:
                    total = int(content_length[0])
                    public.writeFile(self.down_log_total_file,
                                     content_length[0])
            else:
                total = public.readFile(self.down_log_total_file)
                if not total:
                    total = 0
                total = int(total)

            filename = public.M(self.__table).where('id=?',
                                                    (id, )).getField('shell')

            speed_tmp = public.ExecShell("tail -n 2 {}".format(log_file))[0]
            speed_total = re.findall(
                r"([\d\.]+[BbKkMmGg]).+\s+(\d+)%\s+([\d\.]+[KMBGkmbg])\s+(\w+[sS])",
                speed_tmp)
            if not speed_total:
                data = {
                    'name': '下载文件{}'.format(filename),
                    'total': 0,
                    'used': 0,
                    'pre': 0,
                    'speed': 0,
                    'time': 0
                }
            else:
                speed_total = speed_total[0]
                used = speed_total[0]
                if speed_total[0].lower().find('k') != -1:
                    used = public.to_size(
                        float(speed_total[0].lower().replace('k', '')) * 1024)
                    u_time = speed_total[3].replace('h', '小时').replace(
                        'm', '分').replace('s', '秒')
                data = {
                    'name': '下载文件{}'.format(filename),
                    'total': total,
                    'used': used,
                    'pre': speed_total[1],
                    'speed': speed_total[2],
                    'time': u_time
                }
        else:
            data = public.ExecShell("tail -n {} {}".format(num, log_file))[0]
            if type(data) == list:
                return ''
            data = data.replace('\x08', '').replace('\n', '<br>')
        return data
Пример #39
0
    def apple_lest_cert(self, get):

        data = {}
        data['siteName'] = get.siteName
        data['domains'] = json.loads(get.domains)
        data['email'] = get.email
        data['dnssleep'] = get.dnssleep

        if len(data['domains']) <= 0:
            return public.returnMsg(False, '申请域名列表不能为空.')

        data['first_domain'] = data['domains'][0]

        path = self.setupPath + '/panel/vhost/cert/' + data['siteName']
        if not os.path.exists(path): os.makedirs(path)

        # 检查是否自定义证书
        partnerOrderId = path + '/partnerOrderId'
        if os.path.exists(partnerOrderId): os.remove(partnerOrderId)
        #清理续签key
        re_key = path + '/account_key.key'
        if os.path.exists(re_key): os.remove(re_key)

        re_password = path + '/password'
        if os.path.exists(re_password): os.remove(re_password)

        data['account_key'] = None
        if hasattr(get, 'dnsapi'):
            if not 'app_root' in get: get.app_root = '0'
            data['app_root'] = get.app_root
            domain_list = data['domains']
            if data['app_root'] == '1':
                domain_list = []
                data['first_domain'] = self.get_root_domain(
                    data['first_domain'])
                for domain in data['domains']:
                    rootDoamin = self.get_root_domain(domain)
                    if not rootDoamin in domain_list:
                        domain_list.append(rootDoamin)
                    if not "*." + rootDoamin in domain_list:
                        domain_list.append("*." + rootDoamin)
                data['domains'] = domain_list
            if get.dnsapi == 'dns':
                domain_path = path + '/domain_txt_dns_value.json'
                if hasattr(get, 'renew'):  #验证
                    data['renew'] = True
                    dns = json.loads(public.readFile(domain_path))
                    data['dns'] = dns
                    certificate = self.crate_let_by_oper(data)
                else:
                    #手动解析提前返回
                    result = self.crate_let_by_oper(data)
                    if 'status' in result and not result['status']:
                        return result
                    result['status'] = True
                    public.writeFile(domain_path, json.dumps(result))
                    result['msg'] = '获取成功,请手动解析域名'
                    result['code'] = 2
                    return result
            elif get.dnsapi == 'dns_bt':
                data['dnsapi'] = get.dnsapi
                certificate = self.crate_let_by_dns(data)
            else:
                data['dnsapi'] = get.dnsapi
                data['dns_param'] = get.dns_param.split('|')
                certificate = self.crate_let_by_dns(data)
        else:
            #文件验证
            data['site_dir'] = get.site_dir
            certificate = self.crate_let_by_file(data)

        if not certificate['status']:
            return public.returnMsg(False, certificate['msg'])

        #保存续签
        cpath = self.setupPath + '/panel/vhost/cert/crontab.json'
        config = {}
        if os.path.exists(cpath):
            config = json.loads(public.readFile(cpath))
        config[data['siteName']] = data
        public.writeFile(cpath, json.dumps(config))
        public.set_mode(cpath, 600)

        #存储证书
        public.writeFile(path + "/privkey.pem", certificate['key'])
        public.writeFile(path + "/fullchain.pem",
                         certificate['cert'] + certificate['ca_data'])
        public.writeFile(path + "/account_key.key",
                         certificate['account_key'])  #续签KEY

        #转为IIS证书
        p12 = self.dump_pkcs12(certificate['key'],
                               certificate['cert'] + certificate['ca_data'],
                               certificate['ca_data'], data['first_domain'])
        pfx_buffer = p12.export()
        public.writeFile(path + "/fullchain.pfx", pfx_buffer, 'wb+')
        public.writeFile(path + "/README", "let")

        #计划任务续签
        self.set_crond()
        return public.returnMsg(True, '申请成功.')
Пример #40
0
    def backup_path_to(self, spath, dfile, exclude=[], siteName=None):
        if not os.path.exists(spath):
            self.echo_error(
                'The specified directory {} does not exist!'.format(spath))
            return False

        if spath[-1] == '/':
            spath = spath[:-1]

        dirname = os.path.basename(spath)
        dpath = os.path.dirname(dfile)
        if not os.path.exists(dpath):
            os.makedirs(dpath, 384)

        p_size = public.get_path_size(spath)
        self.get_exclude(exclude)
        exclude_config = self._exclude
        if not self._exclude:
            exclude_config = "Not set"

        if siteName:
            self.echo_info('Backup site: {}'.format(siteName))
            self.echo_info('Website root directory: {}'.format(spath))
        else:
            self.echo_info('Backup directory: {}'.format(spath))

        self.echo_info("Directory size: {}".format(public.to_size(p_size)))
        self.echo_info('Exclusion setting: {}'.format(exclude_config))
        disk_path, disk_free, disk_inode = self.get_disk_free(dfile)
        self.echo_info(
            "Partition {} available disk space is: {}, available Inode is: {}".
            format(disk_path, public.to_size(disk_free), disk_inode))
        if disk_path:
            if disk_free < p_size:
                self.echo_error(
                    "The available disk space of the target partition is less than {}, and the backup cannot be completed. Please increase the disk capacity or change the default backup directory on the settings page!"
                    .format(public.to_size(p_size)))
                return False

            if disk_inode < self._inode_min:
                self.echo_error(
                    "The available Inode of the target partition is less than {}, and the backup cannot be completed. Please increase the disk capacity or change the default backup directory on the settings page!"
                    .format(self._inode_min))
                return False

        stime = time.time()
        self.echo_info("Start compressing files: {}".format(
            public.format_date(times=stime)))
        if os.path.exists(dfile):
            os.remove(dfile)
        public.ExecShell("cd " + os.path.dirname(spath) + " && tar zcvf '" +
                         dfile + "' " + self._exclude + " '" + dirname +
                         "' 2>{err_log} 1> /dev/null".format(
                             err_log=self._err_log))
        tar_size = os.path.getsize(dfile)
        if tar_size < 1:
            self.echo_error("Data compression failed")
            self.echo_info(public.readFile(self._err_log))
            return False
        self.echo_info(
            "File compression completed, took {:.2f} seconds, compressed package size: {}"
            .format(time.time() - stime, public.to_size(tar_size)))
        if siteName:
            self.echo_info("Site backed up to: {}".format(dfile))
        else:
            self.echo_info("Directory has been backed up to: {}".format(dfile))
        if os.path.exists(self._err_log):
            os.remove(self._err_log)
        return dfile
Пример #41
0
def bt_cli(u_input=0):
    raw_tip = "==============================================="
    if not u_input:
        print("===============" + public.GetMsg("PANEL_SHELL") +
              "==================")
        print("(1) %s                           (8) %s" %
              (public.GetMsg("RESTART_PANEL"),
               public.GetMsg("CHANGE_PANEL_PORT")))
        print(
            "(2) %s                              (9) %s" %
            (public.GetMsg("STOP_PANEL"), public.GetMsg("CLEAR_PANEL_CACHE")))
        print(
            "(3) %s                             (10) %s" %
            (public.GetMsg("START_PANEL"), public.GetMsg("CLEAR_PANEL_LIMIT")))
        print("(4) %s                            (11) %s" %
              (public.GetMsg("RELOAD_PANEL"), public.GetMsg("CANCEL_ENTRY")))
        print("(5) %s                   (12) %s" %
              (public.GetMsg("CHANGE_PANEL_PASS"),
               public.GetMsg("CANCEL_DOMAIN_BIND")))
        print("(6) %s                   (13) %s" %
              (public.GetMsg("CHANGE_PANEL_USER"),
               public.GetMsg("CANCEL_IP_LIMIT")))
        print("(7) %s     (14) %s" % (public.GetMsg("CHANGE_MYSQL_PASS_FORCE"),
                                      public.GetMsg("GET_PANEL_DEFAULT_MSG")))
        print("(22) %s                (15) %s" %
              ("Display panel error log", public.GetMsg("CLEAR_SYS_RUBBISH")))
        print("(23) %s      (16) %s" % (
            "Turn off BasicAuth authentication",
            "Repair panel (check for errors and update panel files to the latest version)"
        ))
        print(
            "(24) Turn off Google Authenticator          (17) Set log cutting on/off compression"
        )
        print(
            "(25) Set whether to back up the panel automatically  (18) Set whether to save a historical copy of the file"
        )
        print("(0) Cancel")
        print(raw_tip)
        try:
            u_input = input(public.GetMsg("INPUT_CMD_NUM"))
            if sys.version_info[0] == 3: u_input = int(u_input)
        except:
            u_input = 0

    nums = [
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 22, 23,
        24, 25
    ]
    if not u_input in nums:
        print(raw_tip)
        print(public.GetMsg("CANCELLED"))
        exit()

    print(raw_tip)
    print(public.GetMsg("EXECUTING", (u_input, )))
    print(raw_tip)

    if u_input == 1:
        os.system("/etc/init.d/bt restart")
    elif u_input == 2:
        os.system("/etc/init.d/bt stop")
    elif u_input == 3:
        os.system("/etc/init.d/bt start")
    elif u_input == 4:
        os.system("/etc/init.d/bt reload")
    elif u_input == 5:
        if sys.version_info[0] == 2:
            input_pwd = raw_input(public.GetMsg("INPUT_NEW_PASS"))
        else:
            input_pwd = input(public.GetMsg("INPUT_NEW_PASS"))
        set_panel_pwd(input_pwd.strip(), True)
    elif u_input == 6:
        if sys.version_info[0] == 2:
            input_user = raw_input(public.GetMsg("INPUT_NEW_USER"))
        else:
            input_user = input(public.GetMsg("INPUT_NEW_USER"))
        set_panel_username(input_user.strip())
    elif u_input == 7:
        if sys.version_info[0] == 2:
            input_mysql = raw_input(public.GetMsg("INPUT_NEW_MYSQL_PASS"))
        else:
            input_mysql = input(public.GetMsg("INPUT_NEW_MYSQL_PASS"))
        if not input_mysql:
            print(public.GetMsg("PASS_NOT_EMPTY"))
            return

        if len(input_mysql) < 8:
            print(public.GetMsg("PASS_LEN_ERR"))
            return

        import re
        rep = "^[\w@\._]+$"
        if not re.match(rep, input_mysql):
            print(public.GetMsg("PASS_SPECIAL_CHARACTRES_ERR"))
            return

        print(input_mysql)
        set_mysql_root(input_mysql.strip())
    elif u_input == 8:
        input_port = input(public.GetMsg("INPUT_NEW_PANEL_PORT"))
        if sys.version_info[0] == 3: input_port = int(input_port)
        if not input_port:
            print(public.GetMsg("INPUT_PANEL_PORT_ERR"))
            return
        if input_port in [80, 443, 21, 20, 22]:
            print(public.GetMsg("CANT_USE_USUALLY_PORT_ERR"))
            return
        old_port = int(public.readFile('data/port.pl'))
        if old_port == input_port:
            print(public.GetMsg("NEW_PORT_SAMEAS_OLD"))
            return

        is_exists = public.ExecShell("lsof -i:%s|grep LISTEN|grep -v grep" %
                                     input_port)
        if len(is_exists[0]) > 5:
            print(public.GetMsg("PORT_ALREADY_IN_USE"))
            return

        public.writeFile('data/port.pl', str(input_port))
        if os.path.exists("/usr/bin/firewall-cmd"):
            os.system(
                "firewall-cmd --permanent --zone=public --add-port=%s/tcp" %
                input_port)
            os.system("firewall-cmd --reload")
        elif os.path.exists("/etc/sysconfig/iptables"):
            os.system(
                "iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport %s -j ACCEPT"
                % input_port)
            os.system("service iptables save")
        else:
            os.system("ufw allow %s" % input_port)
            os.system("ufw reload")
        os.system("/etc/init.d/bt reload")
        print(public.GetMsg("CHANGE_PORT_SUCCESS", (input_port, )))
        print(public.GetMsg("CLOUD_RELEASE_PORT", (input_port, )))
    elif u_input == 9:
        sess_file = '/dev/shm/session.db'
        if os.path.exists(sess_file): os.remove(sess_file)
        os.system("/etc/init.d/bt reload")
    elif u_input == 10:
        os.system("/etc/init.d/bt reload")
    elif u_input == 11:
        auth_file = 'data/admin_path.pl'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("/etc/init.d/bt reload")
        print(public.GetMsg("CHANGE_LIMITED_CANCEL"))
    elif u_input == 12:
        auth_file = 'data/domain.conf'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("/etc/init.d/bt reload")
        print(public.GetMsg("CHANGE_DOMAIN_CANCEL"))
    elif u_input == 13:
        auth_file = 'data/limitip.conf'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("/etc/init.d/bt reload")
        print(public.GetMsg("CHANGE_IP_CANCEL"))
    elif u_input == 14:
        os.system("/etc/init.d/bt default")
    elif u_input == 15:
        ClearSystem()
    elif u_input == 16:
        os.system("/www/server/panel/pyenv/bin/pip install cachelib")
        os.system("curl http://download.bt.cn/install/update6_en.sh|bash")
    elif u_input == 17:
        l_path = '/www/server/panel/data/log_not_gzip.pl'
        if os.path.exists(l_path):
            print(
                "|-Detected that gzip compression is turned off and is being turned on..."
            )
            os.remove(l_path)
            print("|-Gzip compression is turned on")
        else:
            print("|-Detected that gzip compression is turned on, closing ...")
            public.writeFile(l_path, 'True')
            print("|-Gzip compression turned off")
    elif u_input == 18:
        l_path = '/www/server/panel/data/not_auto_backup.pl'
        if os.path.exists(l_path):
            print(
                "|-Detected that the panel auto backup function is turned off and is being turned on..."
            )
            os.remove(l_path)
            print("|-Panel auto backup function is turned on")
        else:
            print(
                "|-Detected that the panel automatic backup function is turned on and is closing..."
            )
            public.writeFile(l_path, 'True')
            print("|-Panel auto-backup function turned off")
    elif u_input == 22:
        os.system('tail -100 /www/server/panel/logs/error.log')
    elif u_input == 23:
        filename = '/www/server/panel/config/basic_auth.json'
        if os.path.exists(filename): os.remove(filename)
        os.system('bt reload')
        print("|-BasicAuth authentication has been turned off")
    elif u_input == 24:
        filename = '/www/server/panel/data/two_step_auth.txt'
        if os.path.exists(filename): os.remove(filename)
        print("|-Google authentication turned off")
    elif u_input == 25:
        l_path = '/www/server/panel/data/not_file_history.pl'
        if os.path.exists(l_path):
            print(
                "|-Detected that the file copy function is turned off and is being turned on..."
            )
            os.remove(l_path)
            print("|-Document copy function turned on")
        else:
            print(
                "|-Detected that the file copy function is turned on and is closing..."
            )
            public.writeFile(l_path, 'True')
            print("|-File copy function turned off")
Пример #42
0
 def get_ssh_limit(self, get=None):
     allowConf = public.readFile(self.__ALLOW)
     return re.findall("sshd:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):allow",
                       allowConf)
Пример #43
0
 def get_panel_limit(self, get=None):
     conf = public.readFile(self.__LIMIT_CONF)
     if not conf: conf = ''
     limitIp = conf.split(',')
     if '' in limitIp: limitIp.remove('')
     return limitIp
Пример #44
0
import os, time, sys
sys.path.append('/www/server/panel/class')
import public
bt_port = public.readFile('data/port.pl')
if bt_port: bt_port.strip()
bind = []
if os.path.exists('data/ipv6.pl'):
    bind.append('[0:0:0:0:0:0:0:0]:%s' % bt_port)
else:
    bind.append('0.0.0.0:%s' % bt_port)
workers = 1
threads = 4
backlog = 512
reload = False
daemon = True
timeout = 7200
keepalive = 60
preload_app = True
worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker'
chdir = '/www/server/panel'
capture_output = True
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'
loglevel = 'info'
errorlog = chdir + '/logs/error.log'
accesslog = chdir + '/logs/access.log'
pidfile = chdir + '/logs/panel.pid'
if os.path.exists(chdir + '/data/ssl.pl'):
    certfile = 'ssl/certificate.pem'
    keyfile = 'ssl/privateKey.pem'
Пример #45
0
 def checkLimitIp(self):
     if os.path.exists('data/limitip.conf'):
         iplist = public.readFile('data/limitip.conf')
         if iplist:
             iplist = iplist.strip();
             if not web.ctx.ip in iplist.split(','): raise web.seeother('/login')
Пример #46
0
    def SetupPassword(self, get):
        password = get['password'].strip()
        try:
            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
            result = panelMysql.panelMysql().query("show databases")
            isError = self.IsSqlError(result)
            if isError != None:
                #尝试使用新密码
                public.M('config').where("id=?", (1, )).setField(
                    'mysql_root', password)
                result = panelMysql.panelMysql().query("show databases")
                isError = self.IsSqlError(result)
                if isError != None:
                    root_mysql = '''#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
pwd=$1
/etc/init.d/mysqld stop
mysqld_safe --skip-grant-tables&
echo '正在修改密码...';
echo 'The set password...';
sleep 6
mysql -uroot -e "insert into mysql.user(Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,Create_tmp_table_priv,Lock_tables_priv,Execute_priv,Repl_slave_priv,Repl_client_priv,Create_view_priv,Show_view_priv,Create_routine_priv,Alter_routine_priv,Create_user_priv,Event_priv,Trigger_priv,Create_tablespace_priv,User,Password,host)values('Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','root',password('${pwd}'),'127.0.0.1')"
mysql -uroot -e "insert into mysql.user(Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,Create_tmp_table_priv,Lock_tables_priv,Execute_priv,Repl_slave_priv,Repl_client_priv,Create_view_priv,Show_view_priv,Create_routine_priv,Alter_routine_priv,Create_user_priv,Event_priv,Trigger_priv,Create_tablespace_priv,User,Password,host)values('Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','root',password('${pwd}'),'localhost')"
mysql -uroot -e "UPDATE mysql.user SET password=PASSWORD('${pwd}') WHERE user='******'";
mysql -uroot -e "UPDATE mysql.user SET authentication_string=PASSWORD('${pwd}') WHERE user='******'";
mysql -uroot -e "FLUSH PRIVILEGES";
pkill -9 mysqld_safe
pkill -9 mysqld
sleep 2
/etc/init.d/mysqld start

echo '==========================================='
echo "root密码成功修改为: ${pwd}"
echo "The root password set ${pwd}  successuful"'''

                public.writeFile('mysql_root.sh', root_mysql)
                os.system("bash mysql_root.sh " + password)
                os.system("rm -f mysql_root.sh")

            else:
                if '5.7' in public.readFile(web.ctx.session.setupPath +
                                            '/mysql/version.pl'):
                    result = panelMysql.panelMysql().execute(
                        "update mysql.user set authentication_string=password('"
                        + password + "') where User='******'")
                else:
                    result = panelMysql.panelMysql().execute(
                        "update mysql.user set Password=password('" +
                        password + "') where User='******'")
                panelMysql.panelMysql().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")
            web.ctx.session.config['mysql_root'] = password
            return public.returnMsg(True, msg)
        except Exception, ex:
            return public.returnMsg(False, 'EDIT_ERROR')
Пример #47
0
def systemTask():
    try:
        import psutil, time
        filename = 'data/control.conf'
        sql = db.Sql().dbfile('system')
        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, ())
        cpuIo = cpu = {}
        cpuCount = psutil.cpu_count()
        used = count = 0
        reloadNum = 0
        network_up = network_down = diskio_1 = diskio_2 = networkInfo = cpuInfo = diskInfo = None
        while True:
            if not os.path.exists(filename):
                time.sleep(10)
                continue

            day = 30
            try:
                day = int(public.readFile(filename))
                if day < 1:
                    time.sleep(10)
                    continue
            except:
                day = 30

            tmp = {}
            #取当前CPU Io
            tmp['used'] = psutil.cpu_percent(interval=1)

            if not cpuInfo:
                tmp['mem'] = GetMemUsed()
                cpuInfo = tmp

            if cpuInfo['used'] < tmp['used']:
                tmp['mem'] = GetMemUsed()
                cpuInfo = tmp

            #取当前网络Io
            networkIo = psutil.net_io_counters()[:4]
            if not network_up:
                network_up = networkIo[0]
                network_down = networkIo[1]
            tmp = {}
            tmp['upTotal'] = networkIo[0]
            tmp['downTotal'] = networkIo[1]
            tmp['up'] = round(float((networkIo[0] - network_up) / 1024), 2)
            tmp['down'] = round(float((networkIo[1] - network_down) / 1024), 2)
            tmp['downPackets'] = networkIo[3]
            tmp['upPackets'] = networkIo[2]

            network_up = networkIo[0]
            network_down = networkIo[1]

            if not networkInfo: networkInfo = tmp
            if (tmp['up'] + tmp['down']) > (networkInfo['up'] +
                                            networkInfo['down']):
                networkInfo = tmp

            #取磁盘Io
            disk_ios = True
            try:
                if os.path.exists('/proc/diskstats'):
                    diskio_2 = psutil.disk_io_counters()
                    if not diskio_1: diskio_1 = diskio_2
                    tmp = {}
                    tmp['read_count'] = diskio_2.read_count - diskio_1.read_count
                    tmp['write_count'] = diskio_2.write_count - diskio_1.write_count
                    tmp['read_bytes'] = diskio_2.read_bytes - diskio_1.read_bytes
                    tmp['write_bytes'] = diskio_2.write_bytes - diskio_1.write_bytes
                    tmp['read_time'] = diskio_2.read_time - diskio_1.read_time
                    tmp['write_time'] = diskio_2.write_time - diskio_1.write_time

                    if not diskInfo:
                        diskInfo = tmp
                    else:
                        diskInfo['read_count'] += tmp['read_count']
                        diskInfo['write_count'] += tmp['write_count']
                        diskInfo['read_bytes'] += tmp['read_bytes']
                        diskInfo['write_bytes'] += tmp['write_bytes']
                        diskInfo['read_time'] += tmp['read_time']
                        diskInfo['write_time'] += tmp['write_time']

                    diskio_1 = diskio_2
            except:
                disk_ios = False

            #print diskInfo

            if count >= 12:
                try:
                    addtime = int(time.time())
                    deltime = addtime - (day * 86400)

                    data = (cpuInfo['used'], cpuInfo['mem'], addtime)
                    sql.table('cpuio').add('pro,mem,addtime', data)
                    sql.table('cpuio').where("addtime<?",
                                             (deltime, )).delete()

                    data = (networkInfo['up'] / 5, networkInfo['down'] / 5,
                            networkInfo['upTotal'], networkInfo['downTotal'],
                            networkInfo['downPackets'],
                            networkInfo['upPackets'], addtime)
                    sql.table('network').add(
                        'up,down,total_up,total_down,down_packets,up_packets,addtime',
                        data)
                    sql.table('network').where("addtime<?",
                                               (deltime, )).delete()
                    if os.path.exists('/proc/diskstats') and disk_ios:
                        data = (diskInfo['read_count'],
                                diskInfo['write_count'],
                                diskInfo['read_bytes'],
                                diskInfo['write_bytes'], diskInfo['read_time'],
                                diskInfo['write_time'], addtime)
                        sql.table('diskio').add(
                            'read_count,write_count,read_bytes,write_bytes,read_time,write_time,addtime',
                            data)
                        sql.table('diskio').where("addtime<?",
                                                  (deltime, )).delete()

                    #LoadAverage
                    load_average = GetLoadAverage()
                    lpro = round(
                        (load_average['one'] / load_average['max']) * 100, 2)
                    if lpro > 100: lpro = 100
                    sql.table('load_average').add(
                        'pro,one,five,fifteen,addtime',
                        (lpro, load_average['one'], load_average['five'],
                         load_average['fifteen'], addtime))

                    lpro = None
                    load_average = None
                    cpuInfo = None
                    networkInfo = None
                    diskInfo = None
                    count = 0
                    reloadNum += 1
                    if reloadNum > 1440:
                        reloadNum = 0
                except Exception as ex:
                    print(str(ex))
            del (tmp)

            time.sleep(5)
            count += 1
    except:
        time.sleep(30)
        systemTask()
 def get_CONFIG(self):
     if self.__CONFIG_DATA: return self.__CONFIG_DATA
     self.__CONFIG_DATA = json.loads(
         public.readFile(self._PLUGIN_PATH + self.__CONFIG))
Пример #49
0
 def __init__(self):
     ua = web.ctx.env.get('HTTP_USER_AGENT').lower();
     if ua.find('spider') != -1 or ua.find('bot') != -1: raise web.redirect('https://www.baidu.com');
     web.ctx.session.version = "5.9.18";
     if os.path.exists('data/title.pl'):
         web.ctx.session.webname = public.readFile('data/title.pl');
Пример #50
0
    def GetApacheValue(self):
        apachedefaultcontent = public.readFile(self.apachedefaultfile)
        apachempmcontent = public.readFile(self.apachempmfile)
        ps = [
            "%s,%s" %
            (public.GetMsg("SECOND"), public.GetMsg("REQUEST_TIMEOUT_TIME")),
            public.GetMsg("KEEP_ALIVE"),
            "%s,%s" %
            (public.GetMsg("SECOND"), public.GetMsg("CONNECT_TIMEOUT_TIME")),
            public.GetMsg("MAX_KEEP_ALIVE_REQUESTS")
        ]
        gets = [
            "Timeout", "KeepAlive", "KeepAliveTimeout", "MaxKeepAliveRequests"
        ]
        if public.get_webserver() == 'apache':
            shutil.copyfile(self.apachedefaultfile,
                            '/tmp/apdefault_file_bk.conf')
            shutil.copyfile(self.apachempmfile, '/tmp/apmpm_file_bk.conf')
        conflist = []
        n = 0
        for i in gets:
            rep = "(%s)\s+(\w+)" % i
            k = re.search(rep, apachedefaultcontent)
            if not k:
                return public.returnMsg(False, "Get Key {} False".format(k))
            k = k.group(1)
            v = re.search(rep, apachedefaultcontent)
            if not v:
                return public.returnMsg(False, "Get Value {} False".format(v))
            v = v.group(2)
            psstr = ps[n]
            kv = {"name": k, "value": v, "ps": psstr}
            conflist.append(kv)
            n += 1

        ps = [
            public.GetMsg("DEFUALT_PROCESSES"),
            public.GetMsg("MAX_SPARE_SERVERS"),
            "%s,%s" % (public.GetMsg("MAX_CONNECTIONS"),
                       public.GetMsg("NOT_LIMITED_BY_0")),
            public.GetMsg("MAX_PROCESSES")
        ]
        gets = [
            "StartServers", "MaxSpareServers", "MaxConnectionsPerChild",
            "MaxRequestWorkers"
        ]
        n = 0
        for i in gets:
            rep = "(%s)\s+(\w+)" % i
            k = re.search(rep, apachempmcontent)
            if not k:
                return public.returnMsg(False, "Get Key {} False".format(k))
            k = k.group(1)
            v = re.search(rep, apachempmcontent)
            if not v:
                return public.returnMsg(False, "Get Value {} False".format(v))
            v = v.group(2)
            psstr = ps[n]
            kv = {"name": k, "value": v, "ps": psstr}
            conflist.append(kv)
            n += 1
        return (conflist)
Пример #51
0
 def change_phpmyadmin_ssl_port(self, get):
     import re
     try:
         port = int(get.port)
         if 1 > port > 65535:
             return public.returnMsg(False, 'Port range is incorrect')
     except:
         return public.returnMsg(False, 'The port format is incorrect')
     for i in ["nginx", "apache"]:
         file = "/www/server/panel/vhost/{}/phpmyadmin.conf".format(i)
         conf = public.readFile(file)
         if not conf:
             return public.returnMsg(
                 False,
                 "Did not find the {} configuration file, please try to close the ssl port settings before opening"
                 .format(i))
         rulePort = [
             '80', '443', '21', '20', '8080', '8081', '8089', '11211',
             '6379'
         ]
         if get.port in rulePort:
             return public.returnMsg(False, 'AJAX_PHPMYADMIN_PORT_ERR')
         if i == "nginx":
             if not os.path.exists(
                     "/www/server/panel/vhost/apache/phpmyadmin.conf"):
                 return public.returnMsg(
                     False,
                     "Did not find the apache phpmyadmin ssl configuration file, please try to close the ssl port settings before opening"
                 )
             rep = "listen\s*([0-9]+)\s*.*;"
             oldPort = re.search(rep, conf)
             if not oldPort:
                 return public.returnMsg(
                     False,
                     'Did not detect the port that nginx phpmyadmin listens, please confirm whether the file has been manually modified.'
                 )
             oldPort = oldPort.groups()[0]
             conf = re.sub(rep, 'listen ' + get.port + ' ssl;', conf)
         else:
             rep = "Listen\s*([0-9]+)\s*\n"
             oldPort = re.search(rep, conf)
             if not oldPort:
                 return public.returnMsg(
                     False,
                     'Did not detect the port that apache phpmyadmin listens, please confirm whether the file has been manually modified.'
                 )
             oldPort = oldPort.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(file, conf)
         public.serviceReload()
         if i == "apache":
             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')
Пример #52
0
 def __check_panel_cert(self):
     key = public.readFile(self.__panel_cert_path + "privateKey.pem")
     cert = public.readFile(self.__panel_cert_path + "certificate.pem")
     if key and cert:
         return {"key": key, "cert": cert}
Пример #53
0
def panel_status():
    time.sleep(1)
    panel_path = '/www/server/panel'
    pool = 'http://'
    if os.path.exists(panel_path + '/data/ssl.pl'): pool = 'https://'
    port = '8888'
    if os.path.exists(panel_path + '/data/port.pl'):
        port = public.readFile(panel_path + '/data/port.pl').strip()
    panel_url = pool + '127.0.0.1:' + port + '/service_status'
    panel_pid = get_panel_pid()
    n = 0
    s = 0
    v = 0
    while True:
        time.sleep(5)
        if not panel_pid: panel_pid = get_panel_pid()
        if not panel_pid: run_panel()
        try:
            f = psutil.Process(panel_pid).cmdline()[-1]
            if f.find('runserver') == -1 and f.find('BT-Panel') == -1:
                run_panel()
                time.sleep(3)
                panel_pid = get_panel_pid()
                continue
        except:
            run_panel()
            time.sleep(3)
            panel_pid = get_panel_pid()
            continue

        n += 1
        v += 1

        if v > 10:
            v = 0
            log_path = panel_path + '/logs/error.log'
            if os.path.exists(log_path):
                e_body = public.GetNumLines(log_path, 10)
                if e_body:
                    if e_body.find(
                            'PyWSGIServer.do_close') != -1 or e_body.find(
                                'Expected GET method:') != -1 or e_body.find(
                                    'Invalid HTTP method:'
                                ) != -1 or e_body.find('table session') != -1:
                        result = public.httpGet(panel_url)
                        if result != 'True':
                            if e_body.find('table session') != -1:
                                sess_file = '/dev/shm/session.db'
                                if os.path.exists(sess_file):
                                    os.remove(sess_file)
                            public.ExecShell("/etc/init.d/bt reload &")
                            time.sleep(10)
                            result = public.httpGet(panel_url)
                            if result == 'True':
                                public.WriteLog('守护程序', '检查到面板服务异常,已自动恢复!')

        if n > 18000:
            n = 0
            result = public.httpGet(panel_url)
            if result == 'True':
                time.sleep(10)
                continue
            public.ExecShell("/etc/init.d/bt reload &")
            result = public.httpGet(panel_url)
            if result == 'True':
                public.WriteLog('守护程序', '检查到面板服务异常,已自动恢复!')
                time.sleep(10)
                continue
Пример #54
0
    def is_local(self):
        '''
            @name 处理本地连接
            @author hwliang<2020-08-07>
            @ps 如果host为127.0.0.1或localhost,则尝试自动使用publicKey登录
            @return void
        '''

        if self._pass: return
        if self._pkey: return
        if self._host in ['127.0.0.1', 'localhost']:
            try:
                self._port = public.get_ssh_port()
                self.set_sshd_config()
                s_file = '/www/server/panel/config/t_info.json'
                if os.path.exists(s_file):
                    ssh_info = json.loads(
                        public.en_hexb(public.readFile(s_file)))
                    self._host = ssh_info['host'].strip()
                    if 'username' in ssh_info:
                        self._user = ssh_info['username']
                    if 'pkey' in ssh_info:
                        self._pkey = ssh_info['pkey']
                    if 'password' in ssh_info:
                        self._pass = ssh_info['password']
                    self._old_conf = True
                    return

                login_user = self.get_login_user()
                if self._user == 'root' and login_user == 'root':
                    id_rsa_file = ['/root/.ssh/id_rsa', '/root/.ssh/id_rsa_bt']
                    for ifile in id_rsa_file:
                        if os.path.exists(ifile):
                            self._pkey = public.readFile(ifile)
                            host_path = self._save_path + self._host
                            if not os.path.exists(host_path):
                                os.makedirs(host_path, 384)
                            return

                if not self._pass or not self._pkey or not self._user:
                    home_path = '/home/' + login_user
                    if login_user == 'root':
                        home_path = '/root'
                    self._user = login_user
                    id_rsa_file = [
                        home_path + '/.ssh/id_rsa',
                        home_path + '/.ssh/id_rsa_bt'
                    ]
                    for ifile in id_rsa_file:
                        if os.path.exists(ifile):
                            self._pkey = public.readFile(ifile)
                            return

                    self._pass = '******'
                    return
                    # _ssh_ks = home_path + '/.ssh'
                    # if not  os.path.exists(_ssh_ks):
                    #     os.makedirs(_ssh_ks,384)
                    # os.system("ssh-keygen -t rsa -P '' -f {}/.ssh/id_rsa |echo y".format(home_path))
                    # pub_file = home_path + '/.ssh/id_rsa.pub'
                    # az_file = home_path + '/.ssh/authorized_keys'
                    # rsa_file = home_path + '/.ssh/id_rsa'
                    # public.ExecShell('cat {} >> {} && chmod 600 {} {}'.format(pub_file, az_file, az_file,rsa_file))
                    # os.remove(pub_file)
                    # public.ExecShell("chown -R {}:{} {}".format(self._user,self._user,_ssh_ks))
                    # public.ExecShell("chmod -R 600 {}".format(_ssh_ks))
                    # self._pkey = public.readFile(rsa_file)

            except:
                return
Пример #55
0
 def GetBetaStatus(self, get):
     try:
         return public.readFile('data/beta.pl').strip()
     except:
         return 'False'
Пример #56
0
 def get_cert_source(self):
     data = public.readFile(self.__panel_cert_path + "lets.info")
     if not data:
         return {"cert_type": "", "email": "", "domain": ""}
     return json.loads(data)
Пример #57
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|' + public.getCpuType() + '*' + str(
                        psutil.cpu_count()) + '|' + 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/updateLinuxEn'
                updateInfo = json.loads(public.httpPost(sUrl, data))
                if not updateInfo:
                    return public.returnMsg(False, "CONNECT_ERR")
                #updateInfo['msg'] = msg;
                updateInfo['is_beta'] = 0
                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_EN-' + 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")
Пример #58
0
    def CheckPHPINFO(self):
        php_versions = [
            '52', '53', '54', '55', '56', '70', '71', '72', '73', '74', '75'
        ]
        path = public.GetConfigValue(
            'setup_path') + '/panel/vhost/nginx/phpinfo.conf'
        nginx_path = '/www/server/nginx/conf/enable-php-'
        if not os.path.exists(path) or not os.path.exists(nginx_path +
                                                          '75.conf'):
            opt = ""
            for version in php_versions:
                opt += "\n\tlocation /" + version + " {\n\t\tinclude enable-php-" + version + ".conf;\n\t}"
                nginx_conf = nginx_path + version + '.conf'
                if not os.path.exists(nginx_conf):
                    nginx_body = '''location ~ [^/]\.php(/|$)
{
    try_files $uri =404;
    fastcgi_pass  unix:/tmp/php-cgi-%s.sock;
    fastcgi_index index.php;
    include fastcgi.conf;
	include pathinfo.conf;
}''' % version
                    public.WriteFile(nginx_conf, nginx_body)

            phpinfoBody = '''server
{
    listen 80;
    server_name 127.0.0.2;
    allow 127.0.0.1;
    index phpinfo.php index.html index.php;
    root  /www/server/phpinfo;
%s   
}''' % (opt, )
            public.writeFile(path, phpinfoBody)

        path = public.GetConfigValue(
            'setup_path') + '/panel/vhost/apache/phpinfo.conf'
        if not os.path.exists(path):
            opt = ""
            for version in php_versions:
                opt += """\n<Location /%s>
    SetHandler "proxy:unix:/tmp/php-cgi-%s.sock|fcgi://localhost"
</Location>""" % (version, version)

            try:
                apacheVersion = public.readFile(
                    '/www/server/apache/version.pl').strip()
                if apacheVersion == '2.2': opt = ""
            except:
                pass

            phpinfoBody = '''
<VirtualHost *:80>
DocumentRoot "/www/server/phpinfo"
ServerAdmin phpinfo
ServerName 127.0.0.2
%s
<Directory "/www/server/phpinfo">
    SetOutputFilter DEFLATE
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    DirectoryIndex index.php index.html index.htm default.php default.html default.htm
</Directory>
</VirtualHost>
''' % (opt, )
            public.writeFile(path, phpinfoBody)
        public.serviceReload()
 def get_sites(self, get=None):
     if self.__sites: return self.__sites
     data = json.loads(public.readFile(self.__plugin_path + '/sites.json'))
     self.__sites = data
     return data
Пример #60
0
    def backup_database(self, db_name, dfile=None, save=3):
        self.echo_start()
        if not dfile:
            fname = 'db_{}_{}.sql.gz'.format(
                db_name, public.format_date("%Y%m%d_%H%M%S"))
            dfile = os.path.join(self._path, 'database', fname)
        else:
            fname = os.path.basename(dfile)

        dpath = os.path.dirname(dfile)
        if not os.path.exists(dpath):
            os.makedirs(dpath, 384)

        import panelMysql
        if not self._db_mysql: self._db_mysql = panelMysql.panelMysql()
        d_tmp = self._db_mysql.query(
            "select sum(DATA_LENGTH)+sum(INDEX_LENGTH) from information_schema.tables where table_schema='%s'"
            % db_name)
        p_size = self.map_to_list(d_tmp)[0][0]

        if p_size == None:
            self.echo_error(
                'The specified database [ {} ] has no data!'.format(db_name))
            return

        character = public.get_database_character(db_name)

        self.echo_info('Backup database:{}'.format(db_name))
        self.echo_info("Database size: {}".format(public.to_size(p_size)))
        self.echo_info("Database character set: {}".format(character))
        disk_path, disk_free, disk_inode = self.get_disk_free(dfile)
        self.echo_info(
            "Partition {} available disk space is: {}, available Inode is: {}".
            format(disk_path, public.to_size(disk_free), disk_inode))
        if disk_path:
            if disk_free < p_size:
                self.echo_error(
                    "The available disk space of the target partition is less than {}, and the backup cannot be completed. Please increase the disk capacity or change the default backup directory on the settings page!"
                    .format(public.to_size(p_size)))
                return False

            if disk_inode < self._inode_min:
                self.echo_error(
                    "The available Inode of the target partition is less than {}, and the backup cannot be completed. Please increase the disk capacity or change the default backup directory on the settings page!"
                    .format(self._inode_min))
                return False

        stime = time.time()
        self.echo_info("Start exporting database: {}".format(
            public.format_date(times=stime)))
        if os.path.exists(dfile):
            os.remove(dfile)
        self.mypass(True)
        public.ExecShell(
            "/www/server/mysql/bin/mysqldump --default-character-set=" +
            character + " --force --hex-blob --opt " + db_name + " 2>" +
            self._err_log + "| gzip > " + dfile)
        self.mypass(False)
        gz_size = os.path.getsize(dfile)
        if gz_size < 400:
            self.echo_error("Database export failed!")
            self.echo_info(public.readFile(self._err_log))
            return False
        self.echo_info(
            "Database backup completed, took {:.2f} seconds, compressed package size: {}"
            .format(time.time() - stime, public.to_size(gz_size)))
        if self._cloud:
            self.echo_info("Uploading to {}, please wait ...".format(
                self._cloud._title))
            if self._cloud.upload_file(dfile, 'database'):
                self.echo_info("Successfully uploaded to {}".format(
                    self._cloud._title))
            else:
                self.echo_error('Error: File upload failed, skip this backup!')
                if os.path.exists(dfile):
                    os.remove(dfile)
                return False

        filename = dfile
        if self._cloud:
            filename = dfile + '|' + self._cloud._name + '|' + fname
        self.echo_info("Database has been backed up to: {}".format(dfile))
        if os.path.exists(self._err_log):
            os.remove(self._err_log)

        pid = public.M('databases').where('name=?', (db_name)).getField('id')
        pdata = {
            'type': '1',
            'name': fname,
            'pid': pid,
            'filename': filename,
            'addtime': public.format_date(),
            'size': os.path.getsize(dfile)
        }
        public.M('backup').insert(pdata)

        if self._cloud:
            if not self._is_save_local:
                if os.path.exists(dfile):
                    os.remove(dfile)
                    self.echo_info(
                        "User settings do not retain local backups, deleted {}"
                        .format(dfile))

        #清理多余备份
        if not self._cloud:
            backups = public.M('backup').where(
                "type=? and pid=? and filename LIKE '%/%'",
                ('1', pid)).field('id,name,filename').select()
        else:
            backups = public.M('backup').where(
                'type=? and pid=? and filename LIKE "%{}%"'.format(
                    self._cloud._name),
                ('1', pid)).field('id,name,filename').select()
        self.delete_old(backups, save, 'database')
        self.echo_end()
        return dfile