示例#1
0
 def SyncGetDatabases(self,get):
     data = panelMysql.panelMysql().query("show databases")
     isError = self.IsSqlError(data)
     if isError != None: return isError
     users = panelMysql.panelMysql().query("select User,Host from mysql.user where User!='root' AND Host!='localhost' AND Host!=''")
     sql = public.M('databases')
     nameArr = ['information_schema','performance_schema','mysql','sys']
     n = 0
     for  value in data:
         b = False
         for key in nameArr:
             if value[0] == key:
                 b = True 
                 break
         if b:continue
         if sql.where("name=?",(value[0],)).count(): continue
         host = '127.0.0.1'
         for user in users:
             if value[0] == user[0]:
                 host = user[1]
                 break
             
         ps = public.getMsg('INPUT_PS')
         if value[0] == 'test':
                 ps = public.getMsg('DATABASE_TEST')
         addTime = time.strftime('%Y-%m-%d %X',time.localtime())
         if sql.table('databases').add('name,username,password,accept,ps,addtime',(value[0],value[0],'',host,ps,addTime)): n +=1
     
     return public.returnMsg(True,'DATABASE_GET_SUCCESS',(str(n),))
示例#2
0
 def AddCrontab(self,get):
     if len(get['name'])<1:
          return public.returnMsg(False,'CRONTAB_TASKNAME_EMPTY')
     cuonConfig=""
     if get['type']=="day":
         cuonConfig = self.GetDay(get)
         name = public.getMsg('CRONTAB_TODAY')
     elif get['type']=="day-n":
         cuonConfig = self.GetDay_N(get)
         name = public.getMsg('CRONTAB_N_TODAY',(get['where1'],))
     elif get['type']=="hour":
         cuonConfig = self.GetHour(get)
         name = public.getMsg('CRONTAB_HOUR')
     elif get['type']=="hour-n":
         cuonConfig = self.GetHour_N(get)
         name = public.getMsg('CRONTAB_HOUR')
     elif get['type']=="minute-n":
         cuonConfig = self.Minute_N(get)
     elif get['type']=="week":
         get['where1']=get['week']
         cuonConfig = self.Week(get)
     elif get['type']=="month":
         cuonConfig = self.Month(get)
     cronPath=web.ctx.session.setupPath+'/cron'
     cronName=self.GetShell(get)
     if type(cronName) == dict: return cronName;
     cuonConfig += ' ' + cronPath+'/'+cronName+' >> '+ cronPath+'/'+cronName+'.log 2>&1'
     self.WriteShell(cuonConfig)
     self.CrondReload()
     addData=public.M('crontab').add('name,type,where1,where_hour,where_minute,echo,addtime',(get['name'],get['type'],get['where1'],get['hour'],get['minute'],cronName,time.strftime('%Y-%m-%d %X',time.localtime())))
     if addData>0:
          return public.returnMsg(True,'ADD_SUCCESS')
     return public.returnMsg(False,'ADD_ERROR')
示例#3
0
文件: ftp.py 项目: soitun/BaoTa-Panel
 def AddUser(self,get):
     try:
         import files,time
         fileObj=files.files()
         if re.search("\W + ",get['ftp_username']): return {'status':False,'code':501,'msg':public.getMsg('FTP_USERNAME_ERR_T')}
         if len(get['ftp_username']) < 3: return {'status':False,'code':501,'msg':public.getMsg('FTP_USERNAME_ERR_LEN')}
         if not fileObj.CheckDir(get['path']): return {'status':False,'code':501,'msg':public.getMsg('FTP_USERNAME_ERR_DIR')}
         if public.M('ftps').where('name=?',(get.ftp_username.strip(),)).count(): return public.returnMsg(False,'FTP_USERNAME_ERR_EXISTS',(get.ftp_username,))
         username = get['ftp_username'].replace(' ','')
         password = get['ftp_password']
         get.path = get['path'].replace(' ','')
         get.path = get.path.replace("\\", "/")
         fileObj.CreateDir(get)
         os.system('chown www.www ' + get.path)
         public.ExecShell(self.__runPath + '/pure-pw useradd ' + username + ' -u www -d ' + get.path + '<<EOF \n' + password + '\n' + password + '\nEOF')
         self.FtpReload()
         ps=get['ps']
         if get['ps']=='': ps= public.getMsg('INPUT_PS');
         addtime=time.strftime('%Y-%m-%d %X',time.localtime())
         
         pid = 0
         if hasattr(get,'pid'): pid = get.pid
         public.M('ftps').add('pid,name,password,path,status,ps,addtime',(pid,username,password,get.path,1,ps,addtime))
         public.WriteLog('TYPE_FTP', 'FTP_ADD_SUCCESS',(username,))
         return public.returnMsg(True,'ADD_SUCCESS')
     except Exception,ex:
         public.WriteLog('TYPE_FTP', 'FTP_ADD_ERR',(username,str(ex)))
         return public.returnMsg(False,'ADD_ERROR')
示例#4
0
def internalerror():
    errorStr = '''
    <meta charset="utf-8">
    <title>%s</title>
    </head><body>
    <h1>%s</h1>
        <p>%s</p>
    <hr>
    <address>%s 5.x <a href="https://www.bt.cn/bbs" target="_blank">%s</a></address>
    </body></html>
    '''  % (public.getMsg('PAGE_ERR_500_TITLE'),public.getMsg('PAGE_ERR_500_H1'),public.getMsg('PAGE_ERR_500_P1'),public.getMsg('NAME'),public.getMsg('PAGE_ERR_HELP'))
    return web.internalerror(errorStr)
示例#5
0
 def GetUserInfo(self,get):
     result = {}
     if self.__userInfo:
         userTmp = {}
         userTmp['username'] = self.__userInfo['username'][0:3]+'****'+self.__userInfo['username'][-4:];
         result['status'] = True;
         result['msg'] = public.getMsg('SSL_GET_SUCCESS');
         result['data'] = userTmp;
     else:
         userTmp = {}
         userTmp['username'] = public.getMsg('SSL_NOT_BTUSER');
         result['status'] = False;
         result['msg'] = public.getMsg('SSL_NOT_BTUSER');
         result['data'] = userTmp;
     return result;
示例#6
0
 def GetLastLine(self,inputfile,lineNum):
     try:
         fp = open(inputfile, 'r')
         lastLine = ""
         
         lines =  fp.readlines()
         count = len(lines)
         if count>lineNum:
             num=lineNum
         else:
             num=count
         i=1;
         lastre = []
         for i in range(1,(num+1)):
             if lines :
                 n = -i
                 lastLine = lines[n].strip()
                 fp.close()
                 lastre.append(lastLine)
         
         result = ''
         lineNum -= 1
         while lineNum > 0:
             result += lastre[lineNum]+"\n"
             lineNum -= 1
             
         return result
     except:
         return public.getMsg('TASK_SLEEP');
示例#7
0
 def setSession(self):
     if not hasattr(web.ctx.session,'brand'):
         web.ctx.session.brand = public.getMsg('BRAND');
         web.ctx.session.product = public.getMsg('PRODUCT');
         web.ctx.session.rootPath = '/www'
         web.ctx.session.webname = public.getMsg('NAME');
         web.ctx.session.downloadUrl = 'http://download.bt.cn';
         if os.path.exists('data/title.pl'):
             web.ctx.session.webname = public.readFile('data/title.pl'); 
         web.ctx.session.setupPath = self.setupPath;
         web.ctx.session.logsPath = '/www/wwwlogs';
     if not hasattr(web.ctx.session,'menu'):
         web.ctx.session.menu = public.getLan('menu');
     if not hasattr(web.ctx.session,'lan'):
         web.ctx.session.lan = public.get_language();
     if not hasattr(web.ctx.session,'home'):
         web.ctx.session.home = 'https://www.bt.cn';
示例#8
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');
示例#9
0
文件: ftp.py 项目: soitun/BaoTa-Panel
 def SetStatus(self,get):
     msg = public.getMsg('OFF');
     if get.status != '0': msg = public.getMsg('ON');
     try:
         id = get['id']
         username = get['username']
         status = get['status']
         if int(status)==0:
             public.ExecShell(self.__runPath + '/pure-pw usermod ' + username + ' -r 1')
         else:
             public.ExecShell(self.__runPath + '/pure-pw usermod ' + username + " -r ''")
         self.FtpReload()
         public.M('ftps').where("id=?",(id,)).setField('status',status)
         public.WriteLog('TYPE_FTP','FTP_STATUS', (msg,username))
         return public.returnMsg(True, 'SUCCESS')
     except Exception,ex:
         public.WriteLog('TYPE_FTP','FTP_STATUS_ERR', (msg,username,str(ex)))
         return public.returnMsg(False,'FTP_STATUS_ERR',(msg,))
示例#10
0
 def SetSshStatus(self,get):
     #return public.returnMsg(False,'演示服务器,禁止此操作!');
     version = public.readFile('/etc/redhat-release')
     if int(get['status'])==1:
         msg = public.getMsg('FIREWALL_SSH_STOP')
         act = 'stop'
     else:
         msg = public.getMsg('FIREWALL_SSH_START')
         act = 'start'
     
     if not os.path.exists('/etc/redhat-release'):
         public.ExecShell('service ssh ' + act);
     elif version.find(' 7.') != -1:
         public.ExecShell("systemctl "+act+" sshd.service")
     else:
         public.ExecShell("/etc/init.d/sshd "+act)
     
     public.WriteLog("TYPE_FIREWALL", msg)
     return public.returnMsg(True,'SUCCESS')
示例#11
0
 def AddDatabase(self,get):
     try:
         data_name = get['name'].strip()
         if self.CheckRecycleBin(data_name): return public.returnMsg(False,'数据库['+data_name+']已在回收站,请从回收站恢复!');
         if len(data_name) > 16: return public.returnMsg(False, 'DATABASE_NAME_LEN')
         reg = "^\w+$"
         if not re.match(reg, data_name): return public.returnMsg(False,'DATABASE_NAME_ERR_T')
         if not hasattr(get,'db_user'): get.db_user = data_name;
         username = get.db_user.strip();
         checks = ['root','mysql','test','sys','panel_logs']
         if username in checks or len(username) < 1: return public.returnMsg(False,'数据库用户名不合法!');
         if data_name in checks or len(data_name) < 1: return public.returnMsg(False,'数据库名称不合法!');
         data_pwd = get['password']
         if len(data_pwd)<1:
             data_pwd = public.md5(time.time())[0:8]
         
         sql = public.M('databases')
         if sql.where("name=? or username=?",(data_name,username)).count(): return public.returnMsg(False,'DATABASE_NAME_EXISTS')
         address = get['address'].strip()
         user = '******'
         password = data_pwd
         
         codeing = get['codeing']
         
         wheres={
                 'utf8'      :   'utf8_general_ci',
                 'utf8mb4'   :   'utf8mb4_general_ci',
                 'gbk'       :   'gbk_chinese_ci',
                 'big5'      :   'big5_chinese_ci'
                 }
         codeStr=wheres[codeing]
         #添加MYSQL
         result = panelMysql.panelMysql().execute("create database `" + data_name + "` DEFAULT CHARACTER SET " + codeing + " COLLATE " + codeStr)
         isError = self.IsSqlError(result)
         if  isError != None: return isError
         panelMysql.panelMysql().execute("drop user '" + username + "'@'localhost'")
         panelMysql.panelMysql().execute("drop user '" + username + "'@'" + address + "'")
         panelMysql.panelMysql().execute("grant all privileges on `" + data_name + "`.* to '" + username + "'@'localhost' identified by '" + data_pwd + "'")
         for a in address.split(','):
             panelMysql.panelMysql().execute("grant all privileges on `" + data_name + "`.* to '" + username + "'@'" + a + "' identified by '" + data_pwd + "'")
         panelMysql.panelMysql().execute("flush privileges")
         
         if get['ps'] == '': get['ps']=public.getMsg('INPUT_PS');
         addTime = time.strftime('%Y-%m-%d %X',time.localtime())
         
         pid = 0
         if hasattr(get,'pid'): pid = get.pid
         #添加入SQLITE
         sql.add('pid,name,username,password,accept,ps,addtime',(pid,data_name,username,password,address,get['ps'],addTime))
         public.WriteLog("TYPE_DATABASE", 'DATABASE_ADD_SUCCESS',(data_name,))
         return public.returnMsg(True,'ADD_SUCCESS')
     except Exception,ex:
         public.WriteLog("TYPE_DATABASE",'DATABASE_ADD_ERR', (data_name,str(ex)))
         return public.returnMsg(False,'ADD_ERROR')
示例#12
0
 def toWeek(self,num):
     wheres={
             0   :   public.getMsg('CRONTAB_SUNDAY'),
             1   :   public.getMsg('CRONTAB_MONDAY'),
             2   :   public.getMsg('CRONTAB_TUESDAY'),
             3   :   public.getMsg('CRONTAB_WEDNESDAY'),
             4   :   public.getMsg('CRONTAB_THURSDAY'),
             5   :   public.getMsg('CRONTAB_FRIDAY'),
             6   :   public.getMsg('CRONTAB_SATURDAY')
             }
     try:
         return wheres[num]
     except:
         return ''
示例#13
0
 def GET(self):
     import vilidate,time
     if hasattr(web.ctx.session,'codeTime'):
         if (time.time() - web.ctx.session.codeTime) < 0.1:
             return public.getMsg('CODE_BOOM');
     vie = vilidate.vieCode();
     codeImage = vie.GetCodeImage(80,4);
     try:
         from cStringIO import StringIO
     except:
         from StringIO import StringIO
     out = StringIO();
     codeImage[0].save(out, "png")
     web.ctx.session.codeStr  = public.md5("".join(codeImage[1]).lower())
     web.ctx.session.codeTime = time.time()
     web.header('Cache-Control', 'private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
     web.header('Pragma', 'no-cache');
     web.header('Content-Type','image/png');
     return out.getvalue();
示例#14
0
 def setPanel(self,get):
     #return public.returnMsg(False,'体验服务器,禁止修改!')
     if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK');
     if get.domain:
         reg = "^([\w\-\*]{1,100}\.){1,4}(\w{1,10}|\w{1,10}\.\w{1,10})$";
         if not re.match(reg, get.domain): return public.returnMsg(False,'SITE_ADD_ERR_DOMAIN');
     isReWeb = False
     oldPort = web.ctx.host.split(':')[1];
     newPort = get.port;
     if oldPort != get.port:
         if self.IsOpen(get.port):
             return public.returnMsg(False,'PORT_CHECK_EXISTS',(get,port,))
         if int(get.port) >= 65535 or  int(get.port) < 100: return public.returnMsg(False,'PORT_CHECK_RANGE');
         public.writeFile('data/port.pl',get.port)
         import firewalls
         get.ps = public.getMsg('PORT_CHECK_PS');
         fw = firewalls.firewalls();
         fw.AddAcceptPort(get);
         get.port = oldPort;
         get.id = public.M('firewall').where("port=?",(oldPort,)).getField('id');
         fw.DelAcceptPort(get);
         isReWeb = True
     
     if get.webname != web.ctx.session.webname: 
         web.ctx.session.webname = get.webname
         public.writeFile('data/title.pl',get.webname);
     
     limitip = public.readFile('data/limitip.conf');
     if get.limitip != limitip: public.writeFile('data/limitip.conf',get.limitip);
     
     public.writeFile('data/domain.conf',get.domain.strip())
     public.writeFile('data/iplist.txt',get.address)
     
     public.M('config').where("id=?",('1',)).save('backup_path,sites_path',(get.backup_path,get.sites_path))
     web.ctx.session.config['backup_path'] = get.backup_path
     web.ctx.session.config['sites_path'] = get.sites_path
     
     data = {'uri':web.ctx.fullpath,'host':web.ctx.host.split(':')[0]+':'+newPort,'status':True,'isReWeb':isReWeb,'msg':public.getMsg('PANEL_SAVE')}
     public.WriteLog('TYPE_PANEL','PANEL_SAVE',(newPort,get.domain,get.backup_path,get.sites_path,get.address,get.limitip))
     return data
示例#15
0
文件: ftp.py 项目: soitun/BaoTa-Panel
 def setPort(self,get):
     try:
         port = get['port']
         if int(port) < 1 or int(port) > 65535: return public.returnMsg(False,'PORT_CHECK_RANGE')
         file = web.ctx.session.setupPath + '/pure-ftpd/etc/pure-ftpd.conf'
         conf = public.readFile(file)
         rep = u"\n#?\s*Bind\s+[0-9]+\.[0-9]+\.[0-9]+\.+[0-9]+,([0-9]+)"
         #preg_match(rep,conf,tmp)
         conf = re.sub(rep,"\nBind        0.0.0.0," + port,conf)
         public.writeFile(file,conf)
         public.ExecShell('/etc/init.d/pure-ftpd restart')
         public.WriteLog('TYPE_FTP', "FTP_PORT",(port,))
         #添加防火墙
         #data = ftpinfo(port=port,ps = 'FTP端口')
         get.port=port
         get.ps = public.getMsg('FTP_PORT_PS');
         firewalls.firewalls().AddAcceptPort(get)
         web.ctx.session.port=port
         return public.returnMsg(True, 'EDIT_SUCCESS')
     except Exception,ex:
         public.WriteLog('TYPE_FTP', 'FTP_PORT_ERR',(str(ex),))
         return public.returnMsg(False,'EDIT_ERROR')
示例#16
0
 def UpdatePanel(self,get):
     #return public.returnMsg(False,'演示服务器,禁止此操作!');
     try:
         if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK');
         import web,json
         if int(web.ctx.session.config['status']) == 0:
             public.httpGet(web.ctx.session.home+'/Api/SetupCount?type=Linux');
             public.M('config').where("id=?",('1',)).setField('status',1);
         
         #取回远程版本信息
         if hasattr(web.ctx.session,'updateInfo') == True and hasattr(get,'check') == False:
             updateInfo = web.ctx.session.updateInfo;
         else:
             login_temp = 'data/login.temp';
             if os.path.exists(login_temp):
                 logs = public.readFile(login_temp)
                 os.remove(login_temp);
             else:
                 logs = '';
             import psutil,panelPlugin,system;
             mem = psutil.virtual_memory();
             mplugin = panelPlugin.panelPlugin();
             mplugin.ROWS = 10000;
             panelsys = system.system();
             data = {}
             data['sites'] = str(public.M('sites').count());
             data['ftps'] = str(public.M('ftps').count());
             data['databases'] = str(public.M('databases').count());
             data['system'] = panelsys.GetSystemVersion() + '|' + str(mem.total / 1024 / 1024) + 'MB|' + public.getCpuType() + '*' + str(psutil.cpu_count()) + '|' + public.get_webserver() + '|' + web.ctx.session.version;
             data['system'] += '||'+self.GetInstalleds(mplugin.getPluginList(None));
             data['logs'] = logs
             data['oem'] = ''
             msg = public.getMsg('PANEL_UPDATE_MSG');
             sUrl = web.ctx.session.home + '/Api/updateLinux';
             betaIs = 'data/beta.pl';
             betaStr = public.readFile(betaIs);
             if betaStr:
                 if betaStr.strip() != 'False':
                     sUrl = web.ctx.session.home + '/Api/updateLinuxBeta';
                     msg = public.getMsg('PANEL_UPDATE_MSG_TEST');
             
             betaIs = 'plugin/beta/config.conf';
             betaStr = public.readFile(betaIs);
             if betaStr:
                 if betaStr.strip() != 'False':
                     sUrl = web.ctx.session.home + '/Api/updateLinuxBeta';
                     msg = public.getMsg('PANEL_UPDATE_MSG_TEST');
             
             updateInfo = json.loads(public.httpPost(sUrl,data));
             if not updateInfo: return public.returnMsg(False,"CONNECT_ERR");
             updateInfo['msg'] = msg;
             web.ctx.session.updateInfo = updateInfo;
             
         #检查是否需要升级
         if updateInfo['version'] == web.ctx.session.version:
             try:
                 return public.returnMsg(False,updateInfo['msg']);
             except:
                 return public.returnMsg(False,'PANEL_UPDATE_ERR_NEW');
         
         
         #是否执行升级程序 
         if(updateInfo['force'] == True or hasattr(get,'toUpdate') == True or os.path.exists('data/autoUpdate.pl') == True):
             setupPath = web.ctx.session.setupPath;
             uptype = 'update';
             betaIs = 'plugin/beta/config.conf';
             betaStr = public.readFile(betaIs);
             if betaStr:
                 if betaStr.strip() != 'False': uptype = 'updateTest';
             betaIs = 'data/beta.pl';
             betaStr = public.readFile(betaIs);
             if betaStr:
                 if betaStr.strip() != 'False': uptype = 'updateTest';
             httpUrl = public.get_url();
             if httpUrl: updateInfo['downUrl'] =  httpUrl + '/install/' + uptype + '/LinuxPanel-' + updateInfo['version'] + '.zip';
             
             public.downloadFile(updateInfo['downUrl'],'panel.zip');
             if os.path.getsize('panel.zip') < 1048576: return public.returnMsg(False,"PANEL_UPDATE_ERR_DOWN");
             public.ExecShell('unzip -o panel.zip -d ' + setupPath + '/');
             import compileall
             if os.path.exists(setupPath + '/panel/main.py'): public.ExecShell('rm -f ' + setupPath + '/panel/*.pyc');
             if os.path.exists(setupPath + '/panel/class/common.py'): public.ExecShell('rm -f ' + setupPath + '/panel/class/*.pyc');
             
             compileall.compile_dir(setupPath + '/panel');
             compileall.compile_dir(setupPath + '/panel/class');
             public.ExecShell('rm -f panel.zip');
             web.ctx.session.version = updateInfo['version']
             return public.returnMsg(True,'PANEL_UPDATE',(updateInfo['version'],));
         
         #输出新版本信息
         data = {
             'status' : True,
             'version': updateInfo['version'],
             'updateMsg' : updateInfo['updateMsg']
         };
         
         public.ExecShell('rm -rf /www/server/phpinfo/*');
         return data;
     except Exception,ex:
         return public.returnMsg(False,"CONNECT_ERR");
示例#17
0
    def connect(self):
        '''
            @name 连接服务器
            @author hwliang<2020-08-07>
            @return dict{
                status: bool 状态
                msg: string 详情
            }
        '''
        if not self._host: return returnMsg(False, 'WRONG_CONN_ADDR')

        if not self._user: self._user = '******'
        if not self._port: self._port = 22
        self.is_local()

        if self._host in ['127.0.0.1', 'localhost']:
            self._port = public.get_ssh_port()

        num = 0
        while num < 5:
            num += 1
            try:
                self.debug(public.getMsg('RECONN_TIMES', (num, )))
                if self._rep_ssh_config: time.sleep(0.1)
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(2 + num)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 8192)
                sock.connect((self._host, self._port))
                break
            except Exception as e:
                if num == 5:
                    self.set_sshd_config(True)
                    self.debug(public.getMsg('RECONN_FAILED', (e, )))
                    if self._host in ['127.0.0.1', 'localhost']:
                        return returnMsg(
                            False, 'CONN_FAIL',
                            ("Authentication failed ," + self._user + "@" +
                             self._host + ":" + str(self._port), ))
                    return returnMsg(False, 'CONN_FAIL1',
                                     (self._host, self._port))
                else:
                    time.sleep(0.2)

        import paramiko

        self._tp = paramiko.Transport(sock)

        try:
            self._tp.start_client()
            if not self._pass and not self._pkey:
                self.set_sshd_config(True)
                return public.returnMsg(False, 'SSH_LOGIN_INFO_ERR',
                                        (self._host, str(self._port)))
            self._tp.banner_timeout = 60
            if self._pkey:
                self.debug(public.getMsg('AUTH_PRI_KEY'))
                if sys.version_info[0] == 2:
                    try:
                        self._pkey = self._pkey.encode('utf-8')
                    except:
                        pass
                    p_file = BytesIO(self._pkey)
                else:
                    p_file = StringIO(self._pkey)
                try:
                    pkey = paramiko.RSAKey.from_private_key(p_file)
                except:
                    try:
                        p_file.seek(0)
                        pkey = paramiko.Ed25519Key.from_private_key(p_file)
                    except:
                        try:
                            p_file.seek(0)
                            pkey = paramiko.ECDSAKey.from_private_key(p_file)
                        except:
                            p_file.seek(0)
                            pkey = paramiko.DSSKey.from_private_key(p_file)
                self._tp.auth_publickey(username=self._user, key=pkey)
            else:
                try:
                    self._tp.auth_none(self._user)
                except Exception as e:
                    e = str(e)
                    if e.find('keyboard-interactive') >= 0:
                        self._auth_interactive()
                    else:
                        self.debug('Authenticating password')
                        self._tp.auth_password(username=self._user,
                                               password=self._pass)
                # self._tp.auth_password(username=self._user, password=self._pass)
        except Exception as e:
            if self._old_conf:
                s_file = '/www/server/panel/config/t_info.json'
                if os.path.exists(s_file): os.remove(s_file)
            self.set_sshd_config(True)
            self._tp.close()
            e = str(e)
            if e.find('websocket error!') != -1:
                return returnMsg(True, 'connection succeeded')
            if e.find('Authentication timeout') != -1:
                self.debug("认证超时{}".format(e))
                return returnMsg(
                    False,
                    'Authentication timed out, please press enter to try again!{}'
                    .format(e))
            if e.find('Authentication failed') != -1:
                self.debug(public.getMsg('AUTH_FAIL', (str(e), )))
                return returnMsg(False, 'SSH_LOGIN_ERR1',
                                 (str(e + "," + self._user + "@" + self._host +
                                      ":" + str(self._port)), ))
            if e.find('Bad authentication type; allowed types') != -1:
                self.debug(public.getMsg('AUTH_FAIL', (str(e), )))
                if self._host in ['127.0.0.1', 'localhost'
                                  ] and self._pass == 'none':
                    return returnMsg(
                        False, 'USER_OR_PASSWD_ERR',
                        (str("Authentication failed ," + self._user + "@" +
                             self._host + ":" + str(self._port)), ))
                return returnMsg(False, 'SSH_LOGIN_ERR2', (str(e)))
            if e.find('Connection reset by peer') != -1:
                self.debug(public.getMsg('SSH_LOGIN_ERR3'))
                return returnMsg(False, 'SSH_LOGIN_ERR3')
            if e.find('Error reading SSH protocol banner') != -1:
                self.debug('SSH_LOGIN_ERR10')
                return returnMsg(False,
                                 public.getMsg('SSH_LOGIN_ERR4', (str(e), )))
            if not e:
                self.debug('SSH_LOGIN_ERR11')
                return returnMsg(False, "SSH_LOGIN_ERR5")
            err = public.get_error_info()
            self.debug(err)
            return returnMsg(False,
                             public.getMsg("SSH_LOGIN_ERR6", (str(err), )))

        self.debug('SSH_LOGIN_INFO3')
        self._ssh = self._tp.open_session()
        self._ssh.get_pty(term='xterm', width=100, height=34)
        self._ssh.invoke_shell()
        self._connect_time = time.time()
        self._last_send = []
        from BTPanel import request
        self._client = public.GetClientIp() + ':' + str(
            request.environ.get('REMOTE_PORT'))
        public.WriteLog(self._log_type, 'SSH_LOGIN',
                        (self._host, str(self._port)))
        self.history_send("LOGIN_SUCCESS2")
        self.set_sshd_config(True)
        self.debug('SSH_LOGIN_INFO2')
        return returnMsg(True, 'CONNECTION_SUCCEEDED')
示例#18
0
 def GetLastLine(self, inputfile, lineNum):
     result = public.GetNumLines(inputfile, lineNum)
     if len(result) < 1:
         return public.getMsg('TASK_SLEEP')
     return result
示例#19
0
    def GET(self):
        if os.path.exists('/www/server/panel/install.pl'): raise web.seeother('/install');
        web.ctx.session.lan = public.get_language();
        if not hasattr(session,'webname'): session.webname = public.getMsg('NAME');
        tmp = web.ctx.host.split(':')
        domain = public.readFile('data/domain.conf')
        if domain:
            if(tmp[0].strip() != domain.strip()): 
                errorStr = '''
<meta charset="utf-8">
<title>%s</title>
</head><body>
<h1>%s</h1>
    <p>%s</p>
    <p>%s</p>
    <p>%s</p>
<hr>
<address>%s 5.x <a href="http://www.bt.cn/bbs" target="_blank">%s</a></address>
</body></html>
    ''' % (public.getMsg('PAGE_ERR_TITLE'),public.getMsg('PAGE_ERR_DOMAIN_H1'),public.getMsg('PAGE_ERR_DOMAIN_P1'),public.getMsg('PAGE_ERR_DOMAIN_P2'),public.getMsg('PAGE_ERR_DOMAIN_P3'),public.getMsg('NAME'),public.getMsg('PAGE_ERR_HELP'))
                web.header('Content-Type','text/html; charset=utf-8', unique=True)
                return errorStr
        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(','):
                    errorStr = '''
<meta charset="utf-8">
<title>%s</title>
</head><body>
<h1>%s</h1>
    <p>%s</p>
    <p>%s</p>
    <p>%s</p>
<hr>
<address>%s 5.x <a href="http://www.bt.cn/bbs" target="_blank">%s</a></address>
</body></html>
''' % (public.getMsg('PAGE_ERR_TITLE'),public.getMsg('PAGE_ERR_IP_H1'),public.getMsg('PAGE_ERR_IP_P1',(web.ctx.ip,)),public.getMsg('PAGE_ERR_IP_P2'),public.getMsg('PAGE_ERR_IP_P3'),public.getMsg('NAME'),public.getMsg('PAGE_ERR_HELP'))
                    web.header('Content-Type','text/html; charset=utf-8', unique=True)
                    return errorStr;
        
        get = web.input()
        sql = db.Sql()
        if hasattr(get,'dologin'):
            if web.ctx.session.login != False:
                web.ctx.session.login = False;
                web.ctx.session.kill();
            import time
            time.sleep(0.2);
            raise web.seeother('/login')
        
        if hasattr(web.ctx.session,'login'):
            if web.ctx.session.login == True:
                raise web.seeother('/')
        
        if not hasattr(web.ctx.session,'code'):
            web.ctx.session.code = False
        data = {}
        data['lan'] = public.getLan('login')
        render = web.template.render('templates/' + templateName + '/',globals={'session': session,'web':web})
        return render.login(data)
示例#20
0
    def GetCrontab(self, get):
        self.checkBackup()
        self.__clean_log()
        cront = public.M('crontab').order("id desc").field(self.field).select()
        if type(cront) == str:
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'status' INTEGER DEFAULT 1", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'save' INTEGER DEFAULT 3", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'backupTo' TEXT DEFAULT off", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'sName' TEXT", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'sBody' TEXT", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'sType' TEXT", ())
            public.M('crontab').execute(
                "ALTER TABLE 'crontab' ADD 'urladdress' TEXT", ())
            cront = public.M('crontab').order("id desc").field(
                self.field).select()

        data = []
        for i in range(len(cront)):
            tmp = cront[i]
            if cront[i]['type'] == "day":
                tmp['type'] = public.getMsg('CRONTAB_TODAY')
                tmp['cycle'] = public.getMsg('CRONTAB_TODAY_CYCLE', (str(
                    cront[i]['where_hour']), str(cront[i]['where_minute'])))
            elif cront[i]['type'] == "day-n":
                tmp['type'] = public.getMsg('CRONTAB_N_TODAY',
                                            (str(cront[i]['where1']), ))
                tmp['cycle'] = public.getMsg(
                    'CRONTAB_N_TODAY_CYCLE',
                    (str(cront[i]['where1']), str(cront[i]['where_hour']),
                     str(cront[i]['where_minute'])))
            elif cront[i]['type'] == "hour":
                tmp['type'] = public.getMsg('CRONTAB_HOUR')
                tmp['cycle'] = public.getMsg('CRONTAB_HOUR_CYCLE',
                                             (str(cront[i]['where_minute']), ))
            elif cront[i]['type'] == "hour-n":
                tmp['type'] = public.getMsg('CRONTAB_N_HOUR',
                                            (str(cront[i]['where1']), ))
                tmp['cycle'] = public.getMsg(
                    'CRONTAB_N_HOUR_CYCLE',
                    (str(cront[i]['where1']), str(cront[i]['where_minute'])))
            elif cront[i]['type'] == "minute-n":
                tmp['type'] = public.getMsg('CRONTAB_N_MINUTE',
                                            (str(cront[i]['where1']), ))
                tmp['cycle'] = public.getMsg('CRONTAB_N_MINUTE_CYCLE',
                                             (str(cront[i]['where1']), ))
            elif cront[i]['type'] == "week":
                tmp['type'] = public.getMsg('CRONTAB_WEEK')
                if not cront[i]['where1']: cront[i]['where1'] = '0'
                tmp['cycle'] = public.getMsg(
                    'CRONTAB_WEEK_CYCLE', (self.toWeek(int(
                        cront[i]['where1'])), str(cront[i]['where_hour']),
                                           str(cront[i]['where_minute'])))
            elif cront[i]['type'] == "month":
                tmp['type'] = public.getMsg('CRONTAB_MONTH')
                tmp['cycle'] = public.getMsg(
                    'CRONTAB_MONTH_CYCLE',
                    (str(cront[i]['where1']), str(cront[i]['where_hour']),
                     str(cront[i]['where_minute'])))
            data.append(tmp)
        return data
示例#21
0
    def request_get(self, get):
        #if os.path.exists('/www/server/panel/install.pl'): raise redirect('/install');
        if not 'title' in session: session['title'] = public.getMsg('NAME')
        domain = public.readFile('data/domain.conf')

        if domain:
            if (public.GetHost().lower() != domain.strip().lower()):
                errorStr = public.ReadFile('./BTPanel/templates/' +
                                           public.GetConfigValue('template') +
                                           '/error2.html')
                try:
                    errorStr = errorStr.format(
                        public.getMsg('PAGE_ERR_TITLE'),
                        public.getMsg('PAGE_ERR_DOMAIN_H1'),
                        public.getMsg('PAGE_ERR_DOMAIN_P1'),
                        public.getMsg('PAGE_ERR_DOMAIN_P2'),
                        public.getMsg('PAGE_ERR_DOMAIN_P3'),
                        public.getMsg('NAME'), public.getMsg('PAGE_ERR_HELP'))
                except IndexError:
                    pass
                return errorStr
        if os.path.exists('data/limitip.conf'):
            iplist = public.readFile('data/limitip.conf')
            if iplist:
                iplist = iplist.strip()
                if not public.GetClientIp() in iplist.split(','):
                    errorStr = public.ReadFile(
                        './BTPanel/templates/' +
                        public.GetConfigValue('template') + '/error2.html')
                    try:
                        errorStr = errorStr.format(
                            public.getMsg('PAGE_ERR_TITLE'),
                            public.getMsg('PAGE_ERR_IP_H1'),
                            public.getMsg('PAGE_ERR_IP_P1',
                                          (public.GetClientIp(), )),
                            public.getMsg('PAGE_ERR_IP_P2'),
                            public.getMsg('PAGE_ERR_IP_P3'),
                            public.getMsg('NAME'),
                            public.getMsg('PAGE_ERR_HELP'))
                    except IndexError:
                        pass
                    return errorStr

        if 'login' in session:
            if session['login'] == True:
                return redirect('/')

        if not 'code' in session:
            session['code'] = False
        self.error_num(False)
示例#22
0
    def setPanel(self, get):
        if not public.IsRestart():
            return public.returnMsg(False, 'EXEC_ERR_TASK')
        isReWeb = False
        sess_out_path = 'data/session_timeout.pl'
        if 'session_timeout' in get:
            session_timeout = int(get.session_timeout)
            s_time_tmp = public.readFile(sess_out_path)
            if not s_time_tmp: s_time_tmp = '0'
            if int(s_time_tmp) != session_timeout:
                if session_timeout < 300:
                    return public.returnMsg(False, 'NOT_LESS_THAN_TIMEOUT')
                public.writeFile(sess_out_path, str(session_timeout))
                isReWeb = True

        workers_p = 'data/workers.pl'
        if 'workers' in get:
            workers = int(get.workers)
            if int(public.readFile(workers_p)) != workers:
                if workers < 1 or workers > 1024:
                    return public.returnMsg(
                        False, public.GetMsg("PANEL_THREAD_RANGE_ERR"))
                public.writeFile(workers_p, str(workers))
                isReWeb = True

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

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

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

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

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

        public.M('config').where("id=?", ('1', )).save(
            'backup_path,sites_path', (get.backup_path, get.sites_path))
        session['config']['backup_path'] = os.path.join('/', get.backup_path)
        session['config']['sites_path'] = os.path.join('/', get.sites_path)
        mhost = public.GetHost()
        if get.domain.strip(): mhost = get.domain
        data = {
            'uri': request.path,
            'host': mhost + ':' + newPort,
            'status': True,
            'isReWeb': isReWeb,
            'msg': public.getMsg('PANEL_SAVE')
        }
        public.WriteLog('TYPE_PANEL', 'PANEL_SET_SUCCESS',
                        (newPort, get.domain, get.backup_path, get.sites_path,
                         get.address, get.limitip))
        if isReWeb: public.restart_panel()
        return data
示例#23
0
 def GetCrontab(self, get):
     self.checkBackup()
     cront = public.M('crontab').order("id desc").field(
         'id,name,type,where1,where_hour,where_minute,echo,addtime').select(
         )
     data = []
     for i in range(len(cront)):
         tmp = cront[i]
         if cront[i]['type'] == "day":
             tmp['type'] = public.getMsg('CRONTAB_TODAY')
             tmp['cycle'] = public.getMsg('CRONTAB_TODAY_CYCLE', (str(
                 cront[i]['where_hour']), str(cront[i]['where_minute'])))
         elif cront[i]['type'] == "day-n":
             tmp['type'] = public.getMsg('CRONTAB_N_TODAY',
                                         (str(cront[i]['where1']), ))
             tmp['cycle'] = public.getMsg(
                 'CRONTAB_N_TODAY_CYCLE',
                 (str(cront[i]['where1']), str(cront[i]['where_hour']),
                  str(cront[i]['where_minute'])))
         elif cront[i]['type'] == "hour":
             tmp['type'] = public.getMsg('CRONTAB_HOUR')
             tmp['cycle'] = public.getMsg('CRONTAB_HOUR_CYCLE',
                                          (str(cront[i]['where_minute']), ))
         elif cront[i]['type'] == "hour-n":
             tmp['type'] = public.getMsg('CRONTAB_N_HOUR',
                                         (str(cront[i]['where1']), ))
             tmp['cycle'] = public.getMsg(
                 'CRONTAB_N_HOUR_CYCLE',
                 (str(cront[i]['where1']), str(cront[i]['where_minute'])))
         elif cront[i]['type'] == "minute-n":
             tmp['type'] = public.getMsg('CRONTAB_N_MINUTE',
                                         (str(cront[i]['where1']), ))
             tmp['cycle'] = public.getMsg('CRONTAB_N_MINUTE_CYCLE',
                                          (str(cront[i]['where1']), ))
         elif cront[i]['type'] == "week":
             tmp['type'] = public.getMsg('CRONTAB_WEEK')
             tmp['cycle'] = public.getMsg(
                 'CRONTAB_WEEK_CYCLE', (self.toWeek(int(
                     cront[i]['where1'])), str(cront[i]['where_hour']),
                                        str(cront[i]['where_minute'])))
         elif cront[i]['type'] == "month":
             tmp['type'] = public.getMsg('CRONTAB_MONTH')
             tmp['cycle'] = public.getMsg(
                 'CRONTAB_MONTH_CYCLE',
                 (str(cront[i]['where1']), str(cront[i]['where_hour']),
                  str(cront[i]['where_minute'])))
         data.append(tmp)
     return data
示例#24
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;
示例#25
0
    def setPanel(self, get):
        if not public.IsRestart():
            return public.returnMsg(False, 'EXEC_ERR_TASK')
        if get.domain:
            reg = "^([\w\-\*]{1,100}\.){1,4}(\w{1,10}|\w{1,10}\.\w{1,10})$"
            if not re.match(reg, get.domain):
                return public.returnMsg(False, 'SITE_ADD_ERR_DOMAIN')
        isReWeb = False
        try:
            oldPort = web.ctx.host.split(':')[1]
        except:
            oldPort = public.readFile('data/port.pl').strip()
        newPort = get.port
        if oldPort != get.port:
            get.port = str(int(get.port))
            if self.IsOpen(get.port):
                return public.returnMsg(False, 'PORT_CHECK_EXISTS',
                                        (get.port, ))
            if int(get.port) >= 65535 or int(get.port) < 100:
                return public.returnMsg(False, 'PORT_CHECK_RANGE')
            public.writeFile('data/port.pl', get.port)
            import firewalls
            get.ps = public.getMsg('PORT_CHECK_PS')
            fw = firewalls.firewalls()
            fw.AddAcceptPort(get)
            get.port = oldPort
            get.id = public.M('firewall').where("port=?",
                                                (oldPort, )).getField('id')
            fw.DelAcceptPort(get)
            isReWeb = True

        if get.webname != web.ctx.session.webname:
            web.ctx.session.webname = get.webname
            public.writeFile('data/title.pl', get.webname)

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

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

        public.M('config').where("id=?", ('1', )).save(
            'backup_path,sites_path', (get.backup_path, get.sites_path))
        web.ctx.session.config['backup_path'] = get.backup_path
        web.ctx.session.config['sites_path'] = get.sites_path
        mhost = web.ctx.host.split(':')[0]
        if get.domain.strip():
            mhost = get.domain
        data = {
            'uri': web.ctx.fullpath,
            'host': mhost + ':' + newPort,
            'status': True,
            'isReWeb': isReWeb,
            'msg': public.getMsg('PANEL_SAVE')
        }
        public.WriteLog('TYPE_PANEL', 'PANEL_SAVE',
                        (newPort, get.domain, get.backup_path, get.sites_path,
                         get.address, get.limitip))
        self.setService()
        if isReWeb:
            os.system("sleep 2 && /etc/init.d/bt restart &")
        return data
示例#26
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
示例#27
0
    def AddDatabase(self, get):
        try:
            data_name = get['name'].strip()
            if self.CheckRecycleBin(data_name):
                return public.returnMsg(False,
                                        '数据库[' + data_name + ']已在回收站,请从回收站恢复!')
            if len(data_name) > 16:
                return public.returnMsg(False, 'DATABASE_NAME_LEN')
            reg = "^[\w\.-]+$"
            if not re.match(reg, data_name):
                return public.returnMsg(False, 'DATABASE_NAME_ERR_T')
            if not hasattr(get, 'db_user'): get.db_user = data_name
            username = get.db_user.strip()
            checks = ['root', 'mysql', 'test', 'sys', 'panel_logs']
            if username in checks or len(username) < 1:
                return public.returnMsg(False, '数据库用户名不合法!')
            if data_name in checks or len(data_name) < 1:
                return public.returnMsg(False, '数据库名称不合法!')
            data_pwd = get['password']
            if len(data_pwd) < 1:
                data_pwd = public.md5(time.time())[0:8]

            sql = public.M('databases')
            if sql.where("name=? or username=?",
                         (data_name, username)).count():
                return public.returnMsg(False, 'DATABASE_NAME_EXISTS')
            address = get['address'].strip()
            user = '******'
            password = data_pwd

            codeing = get['codeing']

            wheres = {
                'utf8': 'utf8_general_ci',
                'utf8mb4': 'utf8mb4_general_ci',
                'gbk': 'gbk_chinese_ci',
                'big5': 'big5_chinese_ci'
            }
            codeStr = wheres[codeing]
            #添加MYSQL
            mysql_obj = panelMysql.panelMysql()
            result = mysql_obj.execute("create database `" + data_name +
                                       "` DEFAULT CHARACTER SET " + codeing +
                                       " COLLATE " + codeStr)
            isError = self.IsSqlError(result)
            if isError != None: return isError
            mysql_obj.execute("drop user '" + username + "'@'localhost'")
            for a in address.split(','):
                mysql_obj.execute("drop user '" + username + "'@'" + a + "'")

            self.__CreateUsers(data_name, username, password, address)

            if get['ps'] == '': get['ps'] = public.getMsg('INPUT_PS')
            addTime = time.strftime('%Y-%m-%d %X', time.localtime())

            pid = 0
            if hasattr(get, 'pid'): pid = get.pid
            #添加入SQLITE
            sql.add('pid,name,username,password,accept,ps,addtime',
                    (pid, data_name, username, password, address, get['ps'],
                     addTime))
            public.WriteLog("TYPE_DATABASE", 'DATABASE_ADD_SUCCESS',
                            (data_name, ))
            return public.returnMsg(True, 'ADD_SUCCESS')
        except Exception as ex:
            public.WriteLog("TYPE_DATABASE", 'DATABASE_ADD_ERR',
                            (data_name, str(ex)))
            return public.returnMsg(False, 'ADD_ERROR')
示例#28
0
 def UpdatePanel(self,get):
     #return public.returnMsg(False,'演示服务器,禁止此操作!');
     try:
         if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK');
         import web,json
         if int(web.ctx.session.config['status']) == 0:
             public.httpGet(web.ctx.session.home+'/Api/SetupCount?type=Linux');
             public.M('config').where("id=?",('1',)).setField('status',1);
         
         #取回远程版本信息
         if hasattr(web.ctx.session,'updateInfo') == True and hasattr(get,'check') == False:
             updateInfo = web.ctx.session.updateInfo;
         else:
             login_temp = 'data/login.temp';
             if os.path.exists(login_temp):
                 logs = public.readFile(login_temp)
                 os.remove(login_temp);
             else:
                 logs = '';
             import psutil,panelPlugin,system;
             mem = psutil.virtual_memory();
             mplugin = panelPlugin.panelPlugin();
             mplugin.ROWS = 10000;
             panelsys = system.system();
             data = {}
             data['sites'] = str(public.M('sites').count());
             data['ftps'] = str(public.M('ftps').count());
             data['databases'] = str(public.M('databases').count());
             data['system'] = panelsys.GetSystemVersion() + '|' + str(mem.total / 1024 / 1024) + 'MB|' + public.getCpuType() + '*' + str(psutil.cpu_count()) + '|' + public.get_webserver() + '|' + web.ctx.session.version;
             data['system'] += '||'+self.GetInstalleds(mplugin.getPluginList(None));
             data['logs'] = logs
             data['oem'] = ''
             data['intrusion'] = self.get_ssh_intrusion();
             msg = public.getMsg('PANEL_UPDATE_MSG');
             sUrl = web.ctx.session.home + '/Api/updateLinux';
             betaIs = 'data/beta.pl';
             betaStr = public.readFile(betaIs);
             if betaStr:
                 if betaStr.strip() != 'False':
                     sUrl = web.ctx.session.home + '/Api/updateLinuxBeta';
                     msg = public.getMsg('PANEL_UPDATE_MSG_TEST');
             
             betaIs = 'plugin/beta/config.conf';
             betaStr = public.readFile(betaIs);
             if betaStr:
                 if betaStr.strip() != 'False':
                     sUrl = web.ctx.session.home + '/Api/updateLinuxBeta';
                     msg = public.getMsg('PANEL_UPDATE_MSG_TEST');
             
             updateInfo = json.loads(public.httpPost(sUrl,data));
             if not updateInfo: return public.returnMsg(False,"CONNECT_ERR");
             updateInfo['msg'] = msg;
             web.ctx.session.updateInfo = updateInfo;
             
         #检查是否需要升级
         if updateInfo['version'] == web.ctx.session.version:
             try:
                 return public.returnMsg(False,updateInfo['msg']);
             except:
                 return public.returnMsg(False,'PANEL_UPDATE_ERR_NEW');
         
         
         #是否执行升级程序 
         if(updateInfo['force'] == True or hasattr(get,'toUpdate') == True or os.path.exists('data/autoUpdate.pl') == True):
             setupPath = web.ctx.session.setupPath;
             uptype = 'update';
             betaIs = 'plugin/beta/config.conf';
             betaStr = public.readFile(betaIs);
             if betaStr:
                 if betaStr.strip() != 'False': uptype = 'updateTest';
             betaIs = 'data/beta.pl';
             betaStr = public.readFile(betaIs);
             if betaStr:
                 if betaStr.strip() != 'False': uptype = 'updateTest';
             httpUrl = public.get_url();
             if httpUrl: updateInfo['downUrl'] =  httpUrl + '/install/' + uptype + '/LinuxPanel-' + updateInfo['version'] + '.zip';
             
             public.downloadFile(updateInfo['downUrl'],'panel.zip');
             if os.path.getsize('panel.zip') < 1048576: return public.returnMsg(False,"PANEL_UPDATE_ERR_DOWN");
             public.ExecShell('unzip -o panel.zip -d ' + setupPath + '/');
             import compileall
             if os.path.exists(setupPath + '/panel/main.py'): public.ExecShell('rm -f ' + setupPath + '/panel/*.pyc');
             if os.path.exists(setupPath + '/panel/class/common.py'): public.ExecShell('rm -f ' + setupPath + '/panel/class/*.pyc');
             
             compileall.compile_dir(setupPath + '/panel');
             compileall.compile_dir(setupPath + '/panel/class');
             public.ExecShell('rm -f panel.zip');
             web.ctx.session.version = updateInfo['version']
             return public.returnMsg(True,'PANEL_UPDATE',(updateInfo['version'],));
         
         #输出新版本信息
         data = {
             'status' : True,
             'version': updateInfo['version'],
             'updateMsg' : updateInfo['updateMsg']
         };
         
         public.ExecShell('rm -rf /www/server/phpinfo/*');
         return data;
     except Exception,ex:
         return public.returnMsg(False,"CONNECT_ERR");
示例#29
0
 def setPHPMyAdmin(self,get):
     import re;
     #try:
     if public.get_webserver() == 'nginx':
         filename = web.ctx.session.setupPath + '/nginx/conf/nginx.conf';
     else:
         filename = web.ctx.session.setupPath + '/apache/conf/extra/httpd-vhosts.conf';
     
     conf = public.readFile(filename);
     if hasattr(get,'port'):
         mainPort = public.readFile('data/port.pl').strip();
         if mainPort == get.port:
             return public.returnMsg(False,'SOFT_PHPVERSION_ERR_PORT_RE');
         if public.get_webserver() == 'nginx':
             rep = "listen\s+([0-9]+)\s*;"
             oldPort = re.search(rep,conf).groups()[0];
             conf = re.sub(rep,'listen ' + get.port + ';\n',conf);
         else:
             rep = "Listen\s+([0-9]+)\s*\n";
             oldPort = re.search(rep,conf).groups()[0];
             conf = re.sub(rep,"Listen " + get.port + "\n",conf,1);
             rep = "VirtualHost\s+\*:[0-9]+"
             conf = re.sub(rep,"VirtualHost *:" + get.port,conf,1);
         
         if oldPort == get.port: return public.returnMsg(False,'SOFT_PHPVERSION_ERR_PORT');
         
         public.writeFile(filename,conf);
         import firewalls
         get.ps = public.getMsg('SOFT_PHPVERSION_PS');
         fw = firewalls.firewalls();
         fw.AddAcceptPort(get);           
         public.serviceReload();
         public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_PORT',(get.port,))
         get.id = public.M('firewall').where('port=?',(oldPort,)).getField('id');
         get.port = oldPort;
         fw.DelAcceptPort(get);
         return public.returnMsg(True,'SET_PORT_SUCCESS');
     
     if hasattr(get,'phpversion'):
         if public.get_webserver() == 'nginx':
             filename = web.ctx.session.setupPath + '/nginx/conf/enable-php.conf';
             conf = public.readFile(filename);
             rep = "php-cgi.*\.sock"
             conf = re.sub(rep,'php-cgi-' + get.phpversion + '.sock',conf);
         else:
             rep = "php-cgi.*\.sock"
             conf = re.sub(rep,'php-cgi-' + get.phpversion + '.sock',conf);
             
         public.writeFile(filename,conf);
         public.serviceReload();
         public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_PHP',(get.phpversion,))
         return public.returnMsg(True,'SOFT_PHPVERSION_SET');
     
     if hasattr(get,'password'):
         import panelSite;
         if(get.password == 'close'):
             return panelSite.panelSite().CloseHasPwd(get);
         else:
             return panelSite.panelSite().SetHasPwd(get);
     
     if hasattr(get,'status'):
         if conf.find(web.ctx.session.setupPath + '/stop') != -1:
             conf = conf.replace(web.ctx.session.setupPath + '/stop',web.ctx.session.setupPath + '/phpmyadmin');
             msg = public.getMsg('START')
         else:
             conf = conf.replace(web.ctx.session.setupPath + '/phpmyadmin',web.ctx.session.setupPath + '/stop');
             msg = public.getMsg('STOP')
         
         public.writeFile(filename,conf);
         public.serviceReload();
         public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_STATUS',(msg,))
         return public.returnMsg(True,'SOFT_PHPMYADMIN_STATUS',(msg,));
示例#30
0
文件: ajax.py 项目: gitDream/panel-bt
 def setPHPMyAdmin(self,get):
     import re;
     #try:
     filename = self.__get_webserver_conffile()
     conf = public.readFile(filename)
     if not conf: return public.returnMsg(False,'ERROR')
     if hasattr(get,'port'):
         mainPort = public.readFile('data/port.pl').strip()
         rulePort = ['80','443','21','20','8080','8081','8089','11211','6379']
         if get.port in rulePort:
             return public.returnMsg(False,'AJAX_PHPMYADMIN_PORT_ERR')
         if public.get_webserver() == 'nginx':
             rep = "listen\s+([0-9]+)\s*;"
             oldPort = re.search(rep,conf).groups()[0]
             conf = re.sub(rep,'listen ' + get.port + ';\n',conf)
         else:
             rep = "Listen\s+([0-9]+)\s*\n"
             oldPort = re.search(rep,conf).groups()[0]
             conf = re.sub(rep,"Listen " + get.port + "\n",conf,1)
             rep = "VirtualHost\s+\*:[0-9]+"
             conf = re.sub(rep,"VirtualHost *:" + get.port,conf,1)
         
         if oldPort == get.port: return public.returnMsg(False,'SOFT_PHPVERSION_ERR_PORT')
         
         public.writeFile(filename,conf)
         import firewalls
         get.ps = public.getMsg('SOFT_PHPVERSION_PS')
         fw = firewalls.firewalls()
         fw.AddAcceptPort(get);           
         public.serviceReload()
         public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_PORT',(get.port,))
         get.id = public.M('firewall').where('port=?',(oldPort,)).getField('id')
         get.port = oldPort
         fw.DelAcceptPort(get)
         return public.returnMsg(True,'SET_PORT_SUCCESS')
     
     if hasattr(get,'phpversion'):
         if public.get_webserver() == 'nginx':
             filename = public.GetConfigValue('setup_path') + '/nginx/conf/enable-php.conf'
             conf = public.readFile(filename)
             rep = "php-cgi.*\.sock"
             conf = re.sub(rep,'php-cgi-' + get.phpversion + '.sock',conf,1)
         else:
             rep = "php-cgi.*\.sock"
             conf = re.sub(rep,'php-cgi-' + get.phpversion + '.sock',conf,1)
             
         public.writeFile(filename,conf)
         public.serviceReload()
         public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_PHP',(get.phpversion,))
         return public.returnMsg(True,'SOFT_PHPVERSION_SET')
     
     if hasattr(get,'password'):
         import panelSite;
         if(get.password == 'close'):
             return panelSite.panelSite().CloseHasPwd(get)
         else:
             return panelSite.panelSite().SetHasPwd(get)
     
     if hasattr(get,'status'):
         if conf.find(public.GetConfigValue('setup_path') + '/stop') != -1:
             conf = conf.replace(public.GetConfigValue('setup_path') + '/stop',public.GetConfigValue('setup_path') + '/phpmyadmin')
             msg = public.getMsg('START')
         else:
             conf = conf.replace(public.GetConfigValue('setup_path') + '/phpmyadmin',public.GetConfigValue('setup_path') + '/stop')
             msg = public.getMsg('STOP')
         
         public.writeFile(filename,conf)
         public.serviceReload()
         public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_STATUS',(msg,))
         return public.returnMsg(True,'SOFT_PHPMYADMIN_STATUS',(msg,))
示例#31
0
 def GetCrontab(self,get):
     self.checkBackup()
     cront = public.M('crontab').order("id desc").field('id,name,type,where1,where_hour,where_minute,echo,addtime').select()
     data=[]
     for i in range(len(cront)):
         tmp=cront[i]
         if cront[i]['type']=="day":
             tmp['type']=public.getMsg('CRONTAB_TODAY')
             tmp['cycle']= public.getMsg('CRONTAB_TODAY_CYCLE',(str(cront[i]['where_hour']),str(cront[i]['where_minute'])))
         elif cront[i]['type']=="day-n":
             tmp['type']=public.getMsg('CRONTAB_N_TODAY',(str(cront[i]['where1']),))
             tmp['cycle']=public.getMsg('CRONTAB_N_TODAY_CYCLE',(str(cront[i]['where1']),str(cront[i]['where_hour']),str(cront[i]['where_minute'])))
         elif cront[i]['type']=="hour":
             tmp['type']=public.getMsg('CRONTAB_HOUR')
             tmp['cycle']=public.getMsg('CRONTAB_HOUR_CYCLE',(str(cront[i]['where_minute']),))
         elif cront[i]['type']=="hour-n":
             tmp['type']=public.getMsg('CRONTAB_N_HOUR',(str(cront[i]['where1']),))
             tmp['cycle']=public.getMsg('CRONTAB_N_HOUR_CYCLE',(str(cront[i]['where1']),str(cront[i]['where_minute'])))
         elif cront[i]['type']=="minute-n":
             tmp['type']=public.getMsg('CRONTAB_N_MINUTE',(str(cront[i]['where1']),))
             tmp['cycle']=public.getMsg('CRONTAB_N_MINUTE_CYCLE',(str(cront[i]['where1']),))
         elif cront[i]['type']=="week":
             tmp['type']=public.getMsg('CRONTAB_WEEK')
             tmp['cycle']= public.getMsg('CRONTAB_WEEK_CYCLE',(self.toWeek(int(cront[i]['where1'])),str(cront[i]['where_hour']),str(cront[i]['where_minute'])))
         elif cront[i]['type']=="month":
             tmp['type']=public.getMsg('CRONTAB_MONTH')
             tmp['cycle']=public.getMsg('CRONTAB_MONTH_CYCLE',(str(cront[i]['where1']),str(cront[i]['where_hour']),str(cront[i]['where_minute'])))
         data.append(tmp)
     return data
示例#32
0
class ssh_terminal:
    _panel_path = '/www/server/panel'
    _save_path = _panel_path + '/config/ssh_info/'
    _host = None
    _port = 22
    _user = None
    _pass = None
    _pkey = None
    _ws = None
    _ssh = None
    _last_cmd = ""
    _last_cmd_tip = 0
    _log_type = public.getMsg('TYPE_TERMINAL')
    _history_len = 0
    _client = ""
    _rep_ssh_config = False
    _sshd_config_backup = None
    _rep_ssh_service = False

    def connect(self):
        '''
            @name 连接服务器
            @author hwliang<2020-08-07>
            @return dict{
                status: bool 状态
                msg: string 详情
            }
        '''
        if not self._host: return returnMsg(False, '错误的连接地址')

        if not self._user: self._user = '******'
        if not self._port: self._port = 22
        self.is_local()

        try:
            if self._rep_ssh_config: time.sleep(0.1)
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 8192)
            sock.connect((self._host, self._port))
        except Exception as e:
            self.set_sshd_config(True)
            return returnMsg(False, "CONCTION_FAILURE")
        import paramiko

        self._ssh = paramiko.Transport(sock)

        try:
            self._ssh.start_client()
            if not self._pass and not self._pkey:
                self.set_sshd_config(True)
                return public.returnMsg(False, 'SSH_LOGIN_INFO_ERR',
                                        (self._host, self._port))
            self._ssh.banner_timeout = 60
            if self._pkey:
                if sys.version_info[0] == 2:
                    p_file = BytesIO(self._pkey)
                else:
                    p_file = StringIO(self._pkey)
                pkey = paramiko.RSAKey.from_private_key(p_file)
                self._ssh.auth_publickey(username=self._user, key=pkey)
            else:
                self._ssh.auth_password(username=self._user,
                                        password=self._pass)
        except Exception as e:
            self.set_sshd_config(True)
            self._ssh.close()
            e = str(e)
            if e.find('Authentication failed') != -1:
                if self._host in ['127.0.0.1', 'localhost'] and self._pkey:
                    return returnMsg(False, 'SSH_LOGIN_ERR')
                return returnMsg(False, 'SSH_LOGIN_ERR1',
                                 (e + "," + self._user, ))
            if e.find('Bad authentication type; allowed types') != -1:
                return returnMsg(False, 'SSH_LOGIN_ERR2', (e, ))
            if e.find('Connection reset by peer') != -1:
                return returnMsg(False, 'SSH_LOGIN_ERR3')
            if e.find('Error reading SSH protocol banner') != -1:
                return returnMsg(False, 'SSH_LOGIN_ERR4', (e, ))
            if not e:
                return returnMsg(False, "SSH_LOGIN_ERR5")
            return returnMsg(False, "SSH_LOGIN_ERR6",
                             (public.get_error_info(), ))

        self._ssh = self._ssh.open_session()
        self._ssh.get_pty(term='xterm', width=100, height=34)
        self._ssh.invoke_shell()
        self._connect_time = time.time()
        self._last_send = []
        from BTPanel import request
        self._client = public.GetClientIp() + ':' + str(
            request.environ.get('REMOTE_PORT'))
        public.WriteLog(self._log_type, 'SSH_LOGIN', (self._host, self._port))
        self.history_send("LOGIN_SUCCESS2")
        self.set_sshd_config(True)
        return returnMsg(True, 'CONNECTION_SUCCEEDED')

    def get_login_user(self):
        '''
            @name 获取本地登录用户
            @author hwliang<2020-08-07>
            @return string
        '''

        if self._user != 'root': return self._user
        l_user = '******'
        ssh_config_file = '/etc/ssh/sshd_config'
        ssh_config = public.readFile(ssh_config_file)
        if not ssh_config: return l_user

        if ssh_config.find('PermitRootLogin yes') != -1: return l_user

        user_list = self.get_ulist()
        login_user = ''
        for u_info in user_list:
            if u_info['user'] == 'root': continue
            if u_info['login'] == '/bin/bash':
                login_user = u_info['user']
                break

        if not login_user:
            return l_user

        return login_user

    def get_ulist(self):
        '''
            @name 获取本地用户列表
            @author hwliang<2020-08-07>
            @return list
        '''
        u_data = public.readFile('/etc/passwd')
        u_list = []
        for i in u_data.split("\n"):
            u_tmp = i.split(':')
            if len(u_tmp) < 3: continue
            u_info = {}
            u_info['user'], u_info['pass'], u_info['uid'], u_info[
                'gid'], u_info['user_msg'], u_info['home'], u_info[
                    'login'] = u_tmp
            u_list.append(u_info)
        return u_list

    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._host in ['127.0.0.1', 'localhost']:
            try:
                login_user = self.get_login_user()
                self.set_sshd_config()
                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

                    _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

    def get_sys_version(self):
        '''
            @name 获取操作系统版本
            @author hwliang<2020-08-13>
            @return bool
        '''
        version = public.readFile('/etc/redhat-release')
        if not version:
            version = public.readFile('/etc/issue').strip().split(
                "\n")[0].replace('\\n', '').replace('\l', '').strip()
        else:
            version = version.replace('release ',
                                      '').replace('Linux',
                                                  '').replace('(Core)',
                                                              '').strip()
        return version

    def get_ssh_status(self):
        '''
            @name 获取SSH服务状态
            @author hwliang<2020-08-13>
            @return bool
        '''
        version = self.get_sys_version()
        if os.path.exists('/usr/bin/apt-get'):
            if os.path.exists('/etc/init.d/sshd'):
                status = public.ExecShell(
                    "service sshd status | grep -P '(dead|stop|not running)'|grep -v grep"
                )
            else:
                status = public.ExecShell(
                    "service ssh status | grep -P '(dead|stop|not running)'|grep -v grep"
                )
        else:
            if version.find(' 7.') != -1 or version.find(
                    ' 8.') != -1 or version.find('Fedora') != -1:
                status = public.ExecShell(
                    "systemctl status sshd.service | grep 'dead'|grep -v grep")
            else:
                status = public.ExecShell(
                    "/etc/init.d/sshd status | grep -e 'stopped' -e '已停'|grep -v grep"
                )
        if len(status[0]) > 3:
            status = False
        else:
            status = True
        return status

    def is_running(self, rep=False):
        '''
            @name 处理SSH服务状态
            @author hwliang<2020-08-13>
            @param rep<bool> 是否恢复原来的SSH服务状态
            @return bool
        '''
        try:
            if rep and self._rep_ssh_service:
                self.restart_ssh('stop')
                return True

            ssh_status = self.get_ssh_status()
            if not ssh_status:
                self.restart_ssh('start')
                self._rep_ssh_service = True
                return True
            return False
        except:
            return False

    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)
        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

    def restart_ssh(self, act='reload'):
        '''
        重启ssh 无参数传递
        '''
        version = public.readFile('/etc/redhat-release')
        if not os.path.exists('/etc/redhat-release'):
            public.ExecShell('service ssh ' + act)
        elif version.find(' 7.') != -1 or version.find(' 8.') != -1:
            public.ExecShell("systemctl " + act + " sshd.service")
        else:
            public.ExecShell("/etc/init.d/sshd " + act)

    def resize(self, data):
        '''
            @name 调整终端大小
            @author hwliang<2020-08-07>
            @param data<dict> 终端尺寸数据
            {
                cols: int 列
                rows: int 行
            }
            @return bool
        '''
        try:
            data = json.loads(data)
            self._ssh.resize_pty(width=data['cols'], height=data['rows'])
            return True
        except:
            return False

    def recv(self):
        '''
            @name 读取tty缓冲区数据
            @author hwliang<2020-08-07>
            @return void
        '''
        try:
            while not self._ws.closed:
                resp_line = self._ssh.recv(1024)
                if not resp_line:
                    self._ws.send(public.getMsg('RECONNECT_SSH'))
                    self.close()
                    return

                if not resp_line: continue
                if self._ws.closed:
                    return
                try:
                    result = resp_line.decode()
                except:
                    result = str(resp_line)
                self._ws.send(result)

                self.history_recv(result)
        except:
            self._ws.send(public.get_error_info())
        self.close()

    def send(self):
        '''
            @name 写入数据到缓冲区
            @author hwliang<2020-08-07>
            @return void
        '''
        try:
            while not self._ws.closed:
                client_data = self._ws.receive()
                if not client_data: continue
                if len(client_data) > 10:
                    if client_data.find('{"host":"') != -1:
                        continue
                    if client_data.find('"resize":1') != -1:
                        self.resize(client_data)
                        continue
                self._ssh.send(client_data)
                self.history_send(client_data)
        except Exception as ex:
            ex = str(ex)
            if ex.find('_io.BufferedReader') != -1:
                self.send()
                return
        self.close()

    def history_recv(self, recv_data):
        '''
            @name 从接收实体保存命令
            @author hwliang<2020-08-12>
            @param recv_data<string> 数据实体
            @return void
        '''
        #处理TAB补登
        if self._last_cmd_tip == 1:
            if not recv_data.startswith('\r\n'):
                self._last_cmd += recv_data.replace('\u0007', '').strip()
            self._last_cmd_tip = 0

        #上下切换命令
        if self._last_cmd_tip == 2:
            self._last_cmd = recv_data.strip().replace("\x08", "").replace(
                "\x07", "").replace("\x1b[K", "")
            self._last_cmd_tip = 0

    def history_send(self, send_data):
        '''
            @name 从发送实体保存命令
            @author hwliang<2020-08-12>
            @param send_data<string> 数据实体
            @return void
        '''
        if not send_data: return
        his_path = self._save_path + self._host
        if not os.path.exists(his_path): return
        his_file = his_path + '/history.pl'

        #上下切换命令
        if send_data in ["\x1b[A", "\x1b[B"]:
            self._last_cmd_tip = 2
            return

        #退格
        if send_data == "\x7f":
            self._last_cmd = self._last_cmd[:-1]
            return

        #过滤特殊符号
        if send_data in [
                "\x1b[C", "\x1b[D", "\x1b[K", "\x07", "\x08", "\x03", "\x01",
                "\x02", "\x04", "\x05", "\x06", "\u0007"
        ]:
            return

        #Tab补全处理
        if send_data == '\t':
            self._last_cmd_tip = 1
            return

        if send_data[-1] in ['\r', '\n']:
            if not self._last_cmd: return
            his_shell = [
                int(time.time()), self._client, self._user, self._last_cmd
            ]
            public.writeFile(his_file, json.dumps(his_shell) + "\n", "a+")
            self._last_cmd = ""

            #超过5M则保留最新的200行
            if os.stat(his_file).st_size > 5242880:
                his_tmp = public.GetNumLines(his_file, 200)
                public.writeFile(his_file, his_tmp)
        else:
            self._last_cmd += send_data

    def close(self):
        '''
            @name 释放连接
            @author hwliang<2020-08-07>
            @return void
        '''
        try:
            if self._ssh:
                self._ssh.close()
                self._ssh = None
            if not self._ws.closed:
                self._ws.close()
                self._ws = None
        except:
            pass

    def set_attr(self, ssh_info):
        '''
            @name 设置对象属性,并连接服务器
            @author hwliang<2020-08-07>
            @return void
        '''
        self._host = ssh_info['host'].strip()
        self._port = int(ssh_info['port'])
        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']

        result = self.connect()
        return result

    def run(self, web_socket, ssh_info=None):
        '''
            @name 启动SSH客户端对象
            @author hwliang<2020-08-07>
            @param web_socket<websocket> websocket句柄对像
            @param ssh_info<dict> SSH信息{
                host: 主机地址,
                port: 端口
                username: 用户名
                password: 密码
                pkey: 密钥(如果不为空,将使用密钥连接)
            }
            @return void
        '''
        self._ws = web_socket
        if not self._ssh:
            if not ssh_info:
                return

            result = self.set_attr(ssh_info)
        else:
            result = returnMsg(True, '已连接')

        if result['status']:
            sendt = threading.Thread(target=self.send)
            recvt = threading.Thread(target=self.recv)
            sendt.start()
            recvt.start()
            sendt.join()
            recvt.join()
            self.close()
            self._ws = None
        else:
            self._ws.send(result['msg'])

    def __del__(self):
        '''
            自动释放
        '''
        self.close()
示例#33
0
 def setPHPMyAdmin(self,get):
     import re;
     #try:
     if public.get_webserver() == 'nginx':
         filename = web.ctx.session.setupPath + '/nginx/conf/nginx.conf';
     else:
         filename = web.ctx.session.setupPath + '/apache/conf/extra/httpd-vhosts.conf';
     
     conf = public.readFile(filename);
     if hasattr(get,'port'):
         mainPort = public.readFile('data/port.pl').strip();
         if mainPort == get.port:
             return public.returnMsg(False,'SOFT_PHPVERSION_ERR_PORT_RE');
         if public.get_webserver() == 'nginx':
             rep = "listen\s+([0-9]+)\s*;"
             oldPort = re.search(rep,conf).groups()[0];
             conf = re.sub(rep,'listen ' + get.port + ';\n',conf);
         else:
             rep = "Listen\s+([0-9]+)\s*\n";
             oldPort = re.search(rep,conf).groups()[0];
             conf = re.sub(rep,"Listen " + get.port + "\n",conf,1);
             rep = "VirtualHost\s+\*:[0-9]+"
             conf = re.sub(rep,"VirtualHost *:" + get.port,conf,1);
         
         if oldPort == get.port: return public.returnMsg(False,'SOFT_PHPVERSION_ERR_PORT');
         
         public.writeFile(filename,conf);
         import firewalls
         get.ps = public.getMsg('SOFT_PHPVERSION_PS');
         fw = firewalls.firewalls();
         fw.AddAcceptPort(get);           
         public.serviceReload();
         public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_PORT',(get.port,))
         get.id = public.M('firewall').where('port=?',(oldPort,)).getField('id');
         get.port = oldPort;
         fw.DelAcceptPort(get);
         return public.returnMsg(True,'SET_PORT_SUCCESS');
     
     if hasattr(get,'phpversion'):
         if public.get_webserver() == 'nginx':
             filename = web.ctx.session.setupPath + '/nginx/conf/enable-php.conf';
             conf = public.readFile(filename);
             rep = "php-cgi.*\.sock"
             conf = re.sub(rep,'php-cgi-' + get.phpversion + '.sock',conf,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(web.ctx.session.setupPath + '/stop') != -1:
             conf = conf.replace(web.ctx.session.setupPath + '/stop',web.ctx.session.setupPath + '/phpmyadmin');
             msg = public.getMsg('START')
         else:
             conf = conf.replace(web.ctx.session.setupPath + '/phpmyadmin',web.ctx.session.setupPath + '/stop');
             msg = public.getMsg('STOP')
         
         public.writeFile(filename,conf);
         public.serviceReload();
         public.WriteLog('TYPE_SOFT','SOFT_PHPMYADMIN_STATUS',(msg,))
         return public.returnMsg(True,'SOFT_PHPMYADMIN_STATUS',(msg,));
示例#34
0
echo "root密码成功修改为: ${pwd}"

                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')

    # 修改用户密码
    def ResDatabasePassword(self, get):
        try:
            newpassword = get['password']
            username = get['username']
            id = get['id']