def ResDatabasePassword(self,get): try: newpassword = get['password'] username = get['username'] id = get['id'] name = public.M('databases').where('id=?',(id,)).getField('name'); rep = "^[\w#@%\.]+$" if len(re.search(rep, newpassword).groups()) > 0: return public.returnMsg(False, 'DATABASE_NAME_ERR_T') #修改MYSQL if '5.7' in public.readFile(web.ctx.session.setupPath + '/mysql/version.pl'): result = panelMysql.panelMysql().execute("update mysql.user set authentication_string=password('" + newpassword + "') where User='******'") else: result = panelMysql.panelMysql().execute("update mysql.user set Password=password('" + newpassword + "') where User='******'") isError=self.IsSqlError(result) if isError != None: return isError panelMysql.panelMysql().execute("flush privileges") #if result==False: return public.returnMsg(False,'DATABASE_PASS_ERR_NOT_EXISTS') #修改SQLITE if int(id) > 0: public.M('databases').where("id=?",(id,)).setField('password',newpassword) else: public.M('config').where("id=?",(id,)).setField('mysql_root',newpassword) web.ctx.session.config['mysql_root'] = newpassword public.WriteLog("TYPE_DATABASE",'DATABASE_PASS_SUCCESS',(name,)) return public.returnMsg(True,'DATABASE_PASS_SUCCESS',(name,)) except Exception,ex: public.WriteLog("TYPE_DATABASE", 'DATABASE_PASS_ERROR',(name,str(ex))) return public.returnMsg(False,'DATABASE_PASS_ERROR',(name,))
def SetDataDir(self,get): if get.datadir[-1] == '/': get.datadir = get.datadir[0:-1]; if os.path.exists(get.datadir): os.system('mkdir -p ' + get.datadir); mysqlInfo = self.GetMySQLInfo(get); if mysqlInfo['datadir'] == get.datadir: return public.returnMsg(False,'DATABASE_MOVE_RE'); os.system('/etc/init.d/mysqld stop'); os.system('\cp -a -r ' + mysqlInfo['datadir'] + '/* ' + get.datadir + '/'); os.system('chown -R mysql.mysql ' + get.datadir); os.system('chmod -R 755 ' + get.datadir); os.system('rm -f ' + get.datadir + '/*.pid'); os.system('rm -f ' + get.datadir + '/*.err'); public.CheckMyCnf(); myfile = '/etc/my.cnf'; mycnf = public.readFile(myfile); public.writeFile('/etc/my_backup.cnf',mycnf); mycnf = mycnf.replace(mysqlInfo['datadir'],get.datadir); public.writeFile(myfile,mycnf); os.system('/etc/init.d/mysqld start'); result = public.ExecShell('/etc/init.d/mysqld status'); if result[0].find('SUCCESS') != -1: public.writeFile('data/datadir.pl',get.datadir); return public.returnMsg(True,'DATABASE_MOVE_SUCCESS'); else: os.system('pkill -9 mysqld'); public.writeFile(myfile,public.readFile('/etc/my_backup.cnf')); os.system('/etc/init.d/mysqld start'); return public.returnMsg(False,'DATABASE_MOVE_ERR');
def AddPackage(self,get): jsonFile = self.__setupPath + '/list.json'; if not os.path.exists(jsonFile): return public.returnMsg(False,'配置文件不存在!'); data = {} data = json.loads(public.readFile(jsonFile)); for d in data: if d['name'] == get.dname: return public.returnMsg(False,'您要添加的程序标识已存在!'); if d['title'] == get.title: return public.returnMsg(False,'您要添加的程序名称已存在!'); if hasattr(get,'rewrite'): get.rewrite = True; pinfo = {} pinfo['name'] = get.dname; pinfo['title'] = get.title; pinfo['version'] = get.version; pinfo['md5'] = get.md5; pinfo['rewrite'] = get.rewrite; pinfo['php'] = get.php; pinfo['ps'] = get.ps; pinfo['shell'] = get.shell; pinfo['download'] = get.download; data.append(pinfo); public.writeFile(jsonFile,json.dumps(data)); return public.returnMsg(True,'添加成功!');
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')
def GetTaskSpeed(self,get): tempFile = '/tmp/panelExec.log' freshFile = '/tmp/panelFresh' import db find = db.Sql().table('tasks').where('status=? OR status=?',('-1','0')).field('id,type,name,execstr').find() if not len(find): return public.returnMsg(False,'当前没有任务队列在执行-2!') isTask = '/tmp/panelTask.pl' public.writeFile(isTask,'True'); echoMsg = {} echoMsg['name'] = find['name'] echoMsg['execstr'] = find['execstr'] if find['type'] == 'download': import json try: tmp = public.readFile(tempFile) if len(tmp) < 10: return public.returnMsg(False,'当前没有任务队列在执行-3!') echoMsg['msg'] = json.loads(tmp) echoMsg['isDownload'] = True except: db.Sql().table('tasks').where("id=?",(find['id'],)).save('status',('0',)) return public.returnMsg(False,'当前没有任务队列在执行-4!') else: echoMsg['msg'] = self.GetLastLine(tempFile,20) echoMsg['isDownload'] = False echoMsg['task'] = public.M('tasks').where("status!=?",('1',)).field('id,status,name,type').order("id asc").select() return echoMsg
def SetSshPort(self,get): #return public.returnMsg(False,'演示服务器,禁止此操作!'); port = get.port if int(port) < 22 or int(port) > 65535: return public.returnMsg(False,'FIREWALL_SSH_PORT_ERR'); ports = ['21','25','80','443','8080','888','8888']; if port in ports: return public.returnMsg(False,''); file = '/etc/ssh/sshd_config' conf = public.readFile(file) rep = "#*Port\s+([0-9]+)\s*\n" conf = re.sub(rep, "Port "+port+"\n", conf) public.writeFile(file,conf) if self.__isFirewalld: self.__Obj.AddAcceptPort(port); public.ExecShell('setenforce 0'); public.ExecShell('sed -i "s#SELINUX=enforcing#SELINUX=disabled#" /etc/selinux/config'); public.ExecShell("systemctl restart sshd.service") elif self.__isUfw: public.ExecShell('ufw allow ' + port + '/tcp'); public.ExecShell("service ssh restart") else: public.ExecShell('iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport '+port+' -j ACCEPT') public.ExecShell("/etc/init.d/sshd restart") self.FirewallReload() public.M('firewall').where("ps=?",('SSH远程管理服务',)).setField('port',port) public.WriteLog("TYPE_FIREWALL", "FIREWALL_SSH_PORT",(port,)) return public.returnMsg(True,'EDIT_SUCCESS')
def BatchPaste(self,get): import shutil,web get.path = get.path.encode('utf-8'); if not self.CheckDir(get.path): return public.returnMsg(False,'FILE_DANGER'); i = 0; l = len(web.ctx.session.selected.data); if get.type == '1': for key in web.ctx.session.selected.data: i += 1 public.writeSpeed(key,i,l); try: sfile = web.ctx.session.selected.path + '/' + key.encode('utf-8') dfile = get.path + '/' + key.encode('utf-8') if os.path.isdir(sfile): shutil.copytree(sfile,dfile) else: shutil.copyfile(sfile,dfile) except: continue; public.WriteLog('TYPE_FILE','FILE_ALL_COPY',(web.ctx.session.selected.path,get.path)) else: for key in web.ctx.session.selected.data: try: i += 1 public.writeSpeed(key,i,l); sfile = web.ctx.session.selected.path + '/' + key.encode('utf-8') dfile = get.path + '/' + key.encode('utf-8') shutil.move(sfile,dfile) except: continue; public.WriteLog('TYPE_FILE','FILE_ALL_MOTE',(web.ctx.session.selected.path,get.path)) public.writeSpeed(None,0,0); errorCount = len(web.ctx.session.selected.data) - i del(web.ctx.session.selected) return public.returnMsg(True,'FILE_ALL',(str(i),str(errorCount)));
def GetFileBody(self,get) : get.path = get.path.encode('utf-8'); if not os.path.exists(get.path): if get.path.find('rewrite') == -1: return public.returnMsg(False,'FILE_NOT_EXISTS') public.writeFile(get.path,''); try: if os.path.getsize(get.path) > 2097152: return public.returnMsg(False,'不能在线编辑大于2MB的文件!'); srcBody = public.readFile(get.path) data = {} if srcBody: import chardet char=chardet.detect(srcBody) data['encoding'] = char['encoding'] if char['encoding'] == 'GB2312': data['encoding'] = 'GBK'; if char['encoding'] == 'ascii': data['encoding'] = 'utf-8' data['data'] = srcBody.decode(data['encoding']).encode('utf-8') else: data['data'] = srcBody data['encoding'] = 'utf-8' data['status'] = True return data except Exception,ex: return public.returnMsg(False,'FILE_GET_ERR' + str(ex))
def setPassword(self,get): #return public.returnMsg(False,'体验服务器,禁止修改!') if get.password1 != get.password2: return public.returnMsg(False,'USER_PASSWORD_CHECK') if len(get.password1) < 5: return public.returnMsg(False,'USER_PASSWORD_LEN') public.M('users').where("username=?",(web.ctx.session.username,)).setField('password',public.md5(get.password1.strip())) public.WriteLog('TYPE_PANEL','USER_PASSWORD_SUCCESS',(web.ctx.session.username,)) return public.returnMsg(True,'USER_PASSWORD_SUCCESS')
def BinLog(self,get): myfile = '/etc/my.cnf'; mycnf = public.readFile(myfile); if mycnf.find('#log-bin=mysql-bin') != -1: if hasattr(get,'status'): return public.returnMsg(False,'0'); mycnf = mycnf.replace('#log-bin=mysql-bin','log-bin=mysql-bin') mycnf = mycnf.replace('#binlog_format=mixed','binlog_format=mixed') os.system('sync') os.system('/etc/init.d/mysqld restart'); else: path = self.GetMySQLInfo(get)['datadir']; if hasattr(get,'status'): dsize = 0; for n in os.listdir(path): if len(n) < 9: continue; if n[0:9] == 'mysql-bin': dsize += os.path.getsize(path + '/' + n); return public.returnMsg(True,dsize); mycnf = mycnf.replace('log-bin=mysql-bin','#log-bin=mysql-bin') mycnf = mycnf.replace('binlog_format=mixed','#binlog_format=mixed') os.system('sync') os.system('/etc/init.d/mysqld restart'); os.system('rm -f ' + path + '/mysql-bin.*') public.writeFile(myfile,mycnf); return public.returnMsg(True,'SUCCESS');
def setPHPMaxSize(self,get): version = get.version max = get.max if int(max) < 2: return public.returnMsg(False,'PHP_UPLOAD_MAX_ERR') #设置PHP path = web.ctx.session.setupPath+'/php/'+version+'/etc/php.ini' conf = public.readFile(path) rep = u"\nupload_max_filesize\s*=\s*[0-9]+M" conf = re.sub(rep,u'\nupload_max_filesize = '+max+'M',conf) rep = u"\npost_max_size\s*=\s*[0-9]+M" conf = re.sub(rep,u'\npost_max_size = '+max+'M',conf) public.writeFile(path,conf) if public.get_webserver() == 'nginx': #设置Nginx path = web.ctx.session.setupPath+'/nginx/conf/nginx.conf' conf = public.readFile(path) rep = "client_max_body_size\s+([0-9]+)m" tmp = re.search(rep,conf).groups() if int(tmp[0]) < int(max): conf = re.sub(rep,'client_max_body_size '+max+'m',conf) public.writeFile(path,conf) public.serviceReload() public.phpReload(version); public.WriteLog("TYPE_PHP", "PHP_UPLOAD_MAX",(version,max)) return public.returnMsg(True,'SET_SUCCESS')
def DelCrontab(self,get): try: id = get['id'] find = public.M('crontab').where("id=?",(id,)).field('name,echo').find() x = web.ctx.session.server_os['x']; if x == 'RHEL': file='/var/spool/cron/root' else: file='/var/spool/cron/crontabs/root' conf=public.readFile(file) rep = ".+" + str(find['echo']) + ".+\n" conf = re.sub(rep, "", conf) cronPath = web.ctx.session.setupPath + '/cron' public.writeFile(file,conf) sfile = cronPath + '/' + find['echo'] if os.path.exists(sfile): os.remove(sfile) sfile = cronPath + '/' + find['echo'] + '.log' if os.path.exists(sfile): os.remove(sfile) self.CrondReload() public.M('crontab').where("id=?",(id,)).delete() public.WriteLog('TYPE_CRON', 'CRONTAB_DEL',(find['name'],)) return public.returnMsg(True, 'DEL_SUCCESS') except: return public.returnMsg(False, 'DEL_ERROR')
def DeleteDatabase(self,get): try: id=get['id'] name = get['name'] if os.path.exists('data/recycle_bin_db.pl'): return self.DeleteToRecycleBin(name); find = public.M('databases').where("id=?",(id,)).field('id,pid,name,username,password,accept,ps,addtime').find(); accept = find['accept']; username = find['username']; #删除MYSQL result = panelMysql.panelMysql().execute("drop database `" + name + "`") isError=self.IsSqlError(result) if isError != None: return isError users = panelMysql.panelMysql().query("select Host from mysql.user where User='******' AND Host!='localhost'") panelMysql.panelMysql().execute("drop user '" + username + "'@'localhost'") for us in users: panelMysql.panelMysql().execute("drop user '" + username + "'@'" + us[0] + "'") panelMysql.panelMysql().execute("flush privileges") #删除SQLITE public.M('databases').where("id=?",(id,)).delete() public.WriteLog("TYPE_DATABASE", 'DATABASE_DEL_SUCCESS',(name,)) return public.returnMsg(True, 'DEL_SUCCESS') except Exception,ex: public.WriteLog("TYPE_DATABASE",'DATABASE_DEL_ERR',(get.name , str(ex))) return public.returnMsg(False,'DEL_ERROR')
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')
def GetSSLInfo(self,get): self.__PDATA['data']['partnerOrderId'] = get.partnerOrderId; self.__PDATA['data'] = self.De_Code(self.__PDATA['data']); result = json.loads(public.httpPost(self.__APIURL + '/GetSSLInfo',self.__PDATA)); result['data'] = self.En_Code(result['data']); #写配置到站点 if hasattr(get,'siteName'): try: siteName = get.siteName; path = '/etc/letsencrypt/live/'+ siteName; if not os.path.exists(path): public.ExecShell('mkdir -p ' + path) csrpath = path+"/fullchain.pem"; keypath = path+"/privkey.pem"; pidpath = path+"/partnerOrderId"; #清理旧的证书链 public.ExecShell('rm -f ' + keypath) public.ExecShell('rm -f ' + csrpath) public.ExecShell('rm -rf ' + path + '-00*') public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName) public.ExecShell('rm -rf /etc/letsencrypt/archive/' + get.siteName + '-00*') public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '.conf') public.ExecShell('rm -f /etc/letsencrypt/renewal/'+ get.siteName + '-00*.conf') public.ExecShell('rm -f ' + path + '/README'); public.writeFile(keypath,result['data']['privateKey']); public.writeFile(csrpath,result['data']['cert']+result['data']['certCa']); public.writeFile(pidpath,get.partnerOrderId); import panelSite panelSite.panelSite().SetSSLConf(get); public.serviceReload(); return public.returnMsg(True,'SET_SUCCESS'); except Exception,ex: return public.returnMsg(False,'SET_ERROR,' + str(ex));
def GetLogs(self,get): id = get['id'] echo = public.M('crontab').where("id=?",(id,)).field('echo').find() logFile = web.ctx.session.setupPath+'/cron/'+echo['echo']+'.log' if not os.path.exists(logFile):return public.returnMsg(False, 'CRONTAB_TASKLOG_EMPTY') log = public.GetNumLines(logFile,2000) f = open(logFile,'r') tmp = f.readline() n=0; while tmp: n += 1; tmp = f.readline(); f.close(); if n > 2000: public.writeFile(logFile,log) where = "Warning: Using a password on the command line interface can be insecure.\n" if log.find(where)>-1: log = log.replace(where, '') public.writeFile('/tmp/read.tmp',log) import chardet; char=chardet.detect(log); encodeing = char['encoding']; if char['encoding'] == 'GB2312': encodeing = 'GBK'; if char['encoding'] == 'ascii': encodeing = 'utf-8'; log = log.decode(encodeing).encode('utf-8'); return public.returnMsg(True, log);
def IsSqlError(self,mysqlMsg): mysqlMsg=str(mysqlMsg) if "MySQLdb" in mysqlMsg: return public.returnMsg(False,'DATABASE_ERR_MYSQLDB') if "2002," in mysqlMsg: return public.returnMsg(False,'DATABASE_ERR_CONNECT') if "using password:"******"Connection refused" in mysqlMsg: return public.returnMsg(False,'DATABASE_ERR_CONNECT') if "1133" in mysqlMsg: return public.returnMsg(False,'DATABASE_ERR_NOT_EXISTS') return None
def remove_ssh_limit(self,get): ip = get.ip; if not ip in self.get_ssh_limit(): return public.returnMsg(True,'指定白名单不存在!'); allowConf = public.readFile(self.__ALLOW).strip(); while allowConf[-1:] == "\n" or allowConf[-1:] == " ": allowConf = allowConf[:-1]; allowConf = re.sub("\nsshd:"+ip+":allow\n?","\n",allowConf); public.writeFile(self.__ALLOW,allowConf+"\n"); return public.returnMsg(True,'删除成功!');
def GetFpmSlowLogs(self,get): path = '/www/server/php/' + get.version + '/var/log/slow.log'; if not os.path.exists(path): return public.returnMsg(False,'日志文件不存在!'); return public.returnMsg(True,public.GetNumLines(path,1000));
def setUsername(self,get): #return public.returnMsg(False,'体验服务器,禁止修改!') if get.username1 != get.username2: return public.returnMsg(False,'USER_USERNAME_CHECK') if len(get.username1) < 3: return public.returnMsg(False,'USER_USERNAME_LEN') public.M('users').where("username=?",(web.ctx.session.username,)).setField('username',get.username1.strip()) public.WriteLog('TYPE_PANEL','USER_USERNAME_SUCCESS',(web.ctx.session.username,get.username2)) web.ctx.session.username = get.username1 return public.returnMsg(True,'USER_USERNAME_SUCCESS')
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');
def AddPanelInfo(self,get): #校验是还是重复 isAdd = public.M('panel').where('title=? OR url=?',(get.title,get.url)).count(); if isAdd: return public.returnMsg(False,'PANEL_SSL_ADD_EXISTS'); import time,json; isRe = public.M('panel').add('title,url,username,password,click,addtime',(get.title,get.url,get.username,get.password,0,int(time.time()))); if isRe: return public.returnMsg(True,'ADD_SUCCESS'); return public.returnMsg(False,'ADD_ERROR');
def DelLogs(self,get): try: id = get['id'] echo = public.M('crontab').where("id=?",(id,)).getField('echo') logFile = web.ctx.session.setupPath+'/cron/'+echo+'.log' os.remove(logFile) return public.returnMsg(True, 'CRONTAB_TASKLOG_CLOSE') except: return public.returnMsg(False, 'CRONTAB_TASKLOG_CLOSE_ERR')
def KillProcess(self,get): #return public.returnMsg(False,'演示服务器,禁止此操作!'); import psutil p = psutil.Process(int(get.pid)); name = p.name(); if name == 'python': return public.returnMsg(False,'KILL_PROCESS_ERR'); p.kill(); public.WriteLog('TYPE_PROCESS','KILL_PROCESS',(get.pid,name)); return public.returnMsg(True,'KILL_PROCESS',(get.pid,name));
def setPHPDisable(self,get): filename = web.ctx.session.setupPath + '/php/' + get.version + '/etc/php.ini' if not os.path.exists(filename): return public.returnMsg(False,'PHP_NOT_EXISTS'); phpini = public.readFile(filename); rep = "disable_functions\s*=\s*.*\n" phpini = re.sub(rep, 'disable_functions = ' + get.disable_functions + "\n", phpini); public.WriteLog('TYPE_PHP','PHP_DISABLE_FUNCTION',(get.version,get.disable_functions)) public.writeFile(filename,phpini); public.phpReload(get.version); return public.returnMsg(True,'SET_SUCCESS');
def SetPanelInfo(self,get): #校验是还是重复 isSave = public.M('panel').where('(title=? OR url=?) AND id!=?',(get.title,get.url,get.id)).count(); if isSave: return public.returnMsg(False,'PANEL_SSL_ADD_EXISTS'); import time,json; #更新到数据库 isRe = public.M('panel').where('id=?',(get.id,)).save('title,url,username,password',(get.title,get.url,get.username,get.password)); if isRe: return public.returnMsg(True,'EDIT_SUCCESS'); return public.returnMsg(False,'EDIT_ERROR'); pass
def Recycle_bin(self,get): c = 'data/recycle_bin.pl'; if hasattr(get,'db'): c = 'data/recycle_bin_db.pl'; if os.path.exists(c): os.remove(c) public.WriteLog('TYPE_FILE','FILE_OFF_RECYCLE_BIN'); return public.returnMsg(True,'FILE_OFF_RECYCLE_BIN'); else: public.writeFile(c,'True'); public.WriteLog('TYPE_FILE','FILE_ON_RECYCLE_BIN'); return public.returnMsg(True,'FILE_ON_RECYCLE_BIN');
def a(self,get): if not hasattr(get,'name'): return public.returnMsg(False,'PLUGIN_INPUT_A'); path = self.__install_path + '/' + get.name if not os.path.exists(path + '/'+get.name+'_main.py'): return public.returnMsg(False,'PLUGIN_INPUT_B'); sys.path.append(path); plugin_main = __import__(get.name+'_main'); reload(plugin_main) pluginObject = eval('plugin_main.' + get.name + '_main()'); if not hasattr(pluginObject,get.s): return public.returnMsg(False,'PLUGIN_INPUT_C',(get.s,)); execStr = 'pluginObject.' + get.s + '(get)' return eval(execStr);
def CreateDir(self,get): get.path = get.path.encode('utf-8').strip(); try: if os.path.exists(get.path): return public.returnMsg(False,'DIR_EXISTS') os.makedirs(get.path) self.SetFileAccept(get.path); public.WriteLog('TYPE_FILE','DIR_CREATE_SUCCESS',(get.path,)) return public.returnMsg(True,'DIR_CREATE_SUCCESS') except: return public.returnMsg(False,'DIR_CREATE_ERR')
def SetQiniuAS(self,get): info = self.GetLibInfo(get.name); filename = web.ctx.session.setupPath + '/panel/data/'+get.name+'As.conf'; conf = get.access_key.strip() + '|' + get.secret_key.strip() + '|' + get.bucket_name.strip() + '|' + get.bucket_domain.strip(); public.writeFile(filename,conf); public.ExecShell("chmod 600 " + filename) result = public.ExecShell("python " + web.ctx.session.setupPath + "/panel/script/backup_"+get.name+".py list") if result[0].find("ERROR:") == -1: public.WriteLog("插件管理", "设置插件["+info['name']+"]AS!"); return public.returnMsg(True, '设置成功!'); return public.returnMsg(False, 'ERROR: 无法连接到'+info['name']+'服务器,请检查[AK/SK/存储空间]设置是否正确!');
def get_panel_error_logs(self, get): filename = 'logs/error.log' if not os.path.exists(filename): return public.returnMsg(False, 'LOG_CLOSE') result = public.GetNumLines(filename, 2000) return public.returnMsg(True, result)
def setPs(self,get): id = get.id if public.M(get.table).where("id=?",(id,)).setField('ps',get.ps): return public.returnMsg(True,'EDIT_SUCCESS') return public.returnMsg(False,'EDIT_ERROR')
def FixReplicate(self,get): file = "%s/plugin/masterslave/data.json" % self.setpath conf = json.loads(public.readFile(file)) status = self.GetReplicateStatus(get) slave_ip = get.slave_ip if status: status_list = status["msg"] for status in status_list: if status["slave_ip"] == slave_ip: if status["Slave_IO_Running"] != "Yes" or status["Slave_SQL_Running"] != "Yes": mversion = pm.panelMysql().query("select version()")[0][0].split("-")[0] Last_IO_Errno = re.search("Last_IO_Errno:\s+(\d+)", status["slavestatus"]).group(1) if Last_IO_Errno == "1236": if "5.5" in mversion: errormsg = re.search("Last_IO_Error:\s+(.+)",status["slavestatus"]).group(1) rep = "(mysql-bin\.\d+)\'\s\w{2}\s(\d+)" errormsg = re.search(rep, errormsg) errmysqlbin = errormsg.group(1) errlogpos = errormsg.group(2) os.system( "/www/server/mysql/bin/mysqlbinlog /www/server/data/%s|grep 'end_log_pos' > /www/server/data/btfix.log" % errmysqlbin) mpos = public.ExecShell("tail -n 1 /www/server/data/btfix.log|awk '{print $7}'")[0].split("\n")[0] print(mpos) if int(mpos) < int(errlogpos): change_sql='stop slave;change master to MASTER_LOG_FILE="%s",MASTER_LOG_POS=%s;start slave' % (errmysqlbin,mpos) print(change_sql) print(self.__ExceSql(status["slave_ip"], status["slave_port"], "user" + conf["slave_user"], "pass" + conf["slave_pass"], change_sql)) status = self.GetReplicateStatus(get) status = status["msg"] if status["Slave_IO_Running"] == "Yes" and status["Slave_SQL_Running"] == "Yes": os.system("rm -f /www/server/data/btfix.log") print("修复成功") return public.returnMsg(True, "修复成功") else: print("修复失败") return public.returnMsg(True, "修复失败") # 主键冲突处理 last_sql_errno = re.search("Last_SQL_Errno:\s+(\d+)", status["slavestatus"]).group(1) if last_sql_errno == "1062": while True: errormsg = re.search("Last_SQL_Error:\s+(.*)", status["slavestatus"]).group(1) primary = "entry\s'(\w+)'" defdb = "database:\s'(\w*)'" db_tb = "(insert|INSERT)\s+(into|INTO)\s+(`|)([\w\_\-\.]+)(`|)" primary = re.search(primary, errormsg).group(1) try: defdb = re.search(defdb, errormsg).group(1) except: defdb = "" db_tb = re.search(db_tb, errormsg).group(4) print(primary, defdb, db_tb) if defdb: db_tb=defdb+"."+db_tb.split(".")[-1] sql = "desc %s" % db_tb result = pm.panelMysql().query(sql) for i in result: if "PRI" in i: prikey = i[0] sql = 'delete from %s where %s=%s;stop slave;start slave;' % (db_tb, prikey, primary) print(sql) a = self.__ExceSql(status["slave_ip"], status["slave_port"], "user" + conf["slave_user"], "pass" + conf["slave_pass"], sql) print(a) status_list = self.GetReplicateStatus(get)["msg"] for status in status_list: if status["slave_ip"] == slave_ip: last_sql_errno = re.search("Last_SQL_Errno:\s+(\d+)", status["slavestatus"]).group(1) if last_sql_errno != "1062": return public.returnMsg(True, "修复成功") else: return public.returnMsg(False, "无法修复") else: print("同步正常无需修复") return public.returnMsg(True, "同步正常无需修复") else: return public.returnMsg(False, "获取主从状态失败")
def SetSlave(self,get): if not self.GetPort(get): return public.returnMsg(False, '请确定数据库是否已经开启') if not self.CheckBinLog(): return public.returnMsg(False, '请先开启Mysql二进制日志') sconf = public.readFile(self.__mfile) # 备份需要同步的数据库 masterinfo = self.BackUpMasterDbs(get) try: bkstatus = masterinfo["msg"] except: bkstatus = False if bkstatus: return bkstatus __dbpass = public.M('config').where('id=?', (1,)).getField('mysql_root') slave_version = masterinfo["slave_version"] create_replicate_sql = "" # Mysql5.5版本 if "5.5" in slave_version: create_replicate_sql += "CHANGE MASTER TO MASTER_HOST='%s',MASTER_PORT=%s,MASTER_USER='******',MASTER_PASSWORD='******',MASTER_LOG_FILE='%s',MASTER_LOG_POS=%s" % ( masterinfo["master_ip"], masterinfo["master_port"], masterinfo["slave_user"], masterinfo["slave_pass"], masterinfo["logfile"], masterinfo["logpos"]) # Mysql5.6+版本 addconf = """ log-slave-updates=true enforce-gtid-consistency=true gtid-mode=on""" if "5.5" not in slave_version and not re.match("10", slave_version): if not re.search("gtid-mode=on",sconf): sconf = re.sub("\[mysqld\]", "[mysqld]" + addconf, sconf) create_replicate_sql += "CHANGE MASTER TO MASTER_HOST='%s',MASTER_PORT=%s,MASTER_USER='******',MASTER_PASSWORD='******',MASTER_AUTO_POSITION = 1" % ( masterinfo["master_ip"], masterinfo["master_port"], masterinfo["slave_user"], masterinfo["slave_pass"]) # 构造要同步的数据库配置 replicate_dbs = "" if masterinfo["replicate_dbs"][0] != "alldatabases": for d in masterinfo["replicate_dbs"]: replicate_dbs += "\nreplicate-wild-do-table = %s.%s" % (d, "%") else: sconf = re.sub("replicate-wild-do-table\s*=\s*[\w\%\.\_\-]+","",sconf) print(replicate_dbs) try: serverid = masterinfo["slave_id"] except: serverid = [int(masterinfo["master_id"]) +1] localip = public.ExecShell("ip a")[0] netip = public.readFile("%s/data/iplist.txt") index = 0 try: for i in masterinfo["slave_ip"]: if i in localip or i in netip: index += masterinfo["slave_ip"].index("i") break if not index: return public.returnMsg(False, '主库没有设置该主机为从服务器,请先设置主服务器后再配置从库') except: pass serverid = serverid[index] if not re.search("replicate-wild-do-table",sconf): sconf = re.sub("server-id\s*=\s*\d+", "server-id = %s%s" % (serverid,replicate_dbs), sconf) public.writeFile(self.__mfile, sconf) # 导入主库数据库 try: pid_old = public.ExecShell("ps aux|grep 'mysql.sock'|awk 'NR==1 {print $2}'")[0].split("\n")[0] self.WriteLog("旧PID %s" % pid_old) pid_new = pid_old public.writeFile("/tmp/mysqlpid", "") for i in range(10): if i == 1: os.system("/etc/init.d/mysqld restart &") time.sleep(10) pid_new = public.ExecShell("ps aux|grep 'mysql.sock'|awk 'NR==1 {print $2}'")[0].split("\n")[0] self.WriteLog("新PID %s" % pid_new) if pid_old == pid_new: time.sleep(10) pid_new = public.ExecShell("ps aux|grep 'mysql.sock'|awk 'NR==1 {print $2}'")[0].split("\n")[0] else: public.writeFile("/tmp/mysqlpid", "ok") break pm.panelMysql().execute("stop slave") pm.panelMysql().execute("reset master") pm.panelMysql().execute("reset slave all") self.WriteLog("开始导入数据库") speed = public.getSpeed() public.writeSpeed("导入数据库", 1, speed["total"]) error = public.ExecShell("nohup /usr/bin/mysql -uroot -p%s < %s &" % (__dbpass, masterinfo["backsqlpath"])) self.WriteLog(str(error)) except Exception as e: self.WriteLog("导入数据库失败 %s" % e) return public.ReturnMsg(False, "导入失败") threading.Thread(target=self.SetSpeed()).start() self.WriteLog("导入数据库完成") self.WriteLog("删除备份的数据库文件") os.system("rm -f %s" % masterinfo["backsqlpath"]) os.system("rm -f /tmp/mysqlpid") self.WriteLog("重启mysql") pid_old = public.ExecShell("ps aux|grep 'mysql.sock'|awk 'NR==1 {print $2}'")[0].split("\n")[0] self.WriteLog("旧PID %s" % pid_old) pid_new = "" public.writeFile("/tmp/mysqlpid", "") restart = 0 for i in range(10): if i == 1: os.system("/etc/init.d/mysqld restart &") time.sleep(10) pid_new = public.ExecShell("ps aux|grep 'mysql.sock'|awk 'NR==1 {print $2}'")[0].split("\n")[0] self.WriteLog("新PID %s" % pid_new) if pid_old == pid_new: time.sleep(10) pid_new = public.ExecShell("ps aux|grep 'mysql.sock'|awk 'NR==1 {print $2}'")[0].split("\n")[0] else: public.writeFile("/tmp/mysqlpid","ok") restart +=1 break if restart == 0: return public.ReturnMsg(False, "导入数据后重启失败") public.writeSpeed("重启数据库", int(1), int(2)) threading.Thread(target=self.SetSpeed()).start() self.WriteLog("mysql重启完成") # 写入同步的数据库到面板数据库 for i in masterinfo["replicate_dbs_info"]: if not i: continue localdb = public.M('databases').where('name=?', (i[2],)).select() if not localdb: public.M('databases').add(("name,username,password,accept,ps"), (i[2], i[3], i[4], i[5], i[6])) # 完整复制将主root密码写入到从的面板 if masterinfo["replicate_dbs"][0] == "alldatabases": self.WriteLog("因为是完整同步,修改从库面板密码为主库") public.M('config').where('id=?', (1,)).setField('mysql_root', masterinfo["slave_ips"]) result = str(pm.panelMysql().query("select version()")[0]) self.WriteLog(result) if result == "1045": public.M('config').where('id=?', (1,)).setField('mysql_root', __dbpass) # Mairadb10.*版本 if re.match("10",slave_version): set_slave_pos_sql = "SET GLOBAL gtid_slave_pos='%s'" % masterinfo["gtid"] # 需要在数据重启后配置 pm.panelMysql().query(set_slave_pos_sql) create_replicate_sql += "CHANGE MASTER TO MASTER_HOST='%s',MASTER_PORT=%s,MASTER_USER='******',MASTER_PASSWORD='******',master_use_gtid=slave_pos" % ( masterinfo["master_ip"], masterinfo["master_port"], masterinfo["slave_user"], masterinfo["slave_pass"]) self.WriteLog("停止从服务") pm.panelMysql().query("stop slave") self.WriteLog("修改从服务器的主服务器信息") pm.panelMysql().query(create_replicate_sql) self.WriteLog("启动从服务") pm.panelMysql().query("start slave") time.sleep(2) self.WriteLog("获取从状态") slavestatus = pm.panelMysql().query("show slave status")[0] self.WriteLog(str(slavestatus)) self.WriteLog("创建Slave监控用户") create_status_user = "******" % ("user"+masterinfo["slave_user"], masterinfo["master_ip"], "pass"+masterinfo["slave_pass"]) grant_status_user = "******" % ("user"+masterinfo["slave_user"], masterinfo["master_ip"]) pm.panelMysql().execute(create_status_user) pm.panelMysql().execute(grant_status_user) n = 0 try: for i in slavestatus: if i == "Yes": n += 1 except: return public.returnMsg(False, '获取主从状态失败') if n == 2: print("设置成功") self.WriteLog("删除btmysql用户") self.__ExceSql('delete from mysql.user where user="******"', masterinfo=masterinfo) if masterinfo["replicate_dbs"][0] != "alldatabases": self.WriteLog("删除从btmysql用户") pm.panelMysql().execute("delete from mysql.user where user='******'") self.WriteLog("设置成功") os.system("rm -f %s" % self.totalspeedfile) return public.returnMsg(True, '设置成功') else: self.WriteLog("设置失败") os.system("rm -f %s" % self.totalspeedfile) return public.returnMsg(True, '设置失败')
def SetMaster(self,get): if not self.GetPort(get): print(self.GetPort(get)) return public.returnMsg(False, '请确定数据库是否已经开启') iprep = "(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})" if re.search(iprep, get.slave_ip): slave_ip = re.search(iprep, get.slave_ip).group() else: print('请输入正确的IP地址') return public.returnMsg(False, '请输入正确的IP地址') ip = self.GetLocalIP() for i in ip: if i == slave_ip: return public.returnMsg(False, '不能输入本机的IP') try: slave_port = int(get.slave_port) if slave_port >= 65535 or slave_port < 1: return public.returnMsg(False, '请输入正确的端口号') except: return public.returnMsg(False, '请输入正确的端口号') if not self.CheckBinLog(): return public.returnMsg(False, '请先开启Mysql二进制日志') if not self.CheckPort(slave_ip,slave_port): return public.returnMsg(False, '无法访问从服务器<br>请确认安全组是否已经放行<br>Mysql端口:%s' % slave_port) mconf = public.readFile(self.__mfile) masterinfo = self.GetMasterInfo(get) masterinfo["replicate_dbs"] = json.loads(get.replicate_dbs) dbmsg = [] if masterinfo["replicate_dbs"][0] == "alldatabases": for i in self.GetDbs(get): if i != "mysql": d = public.M('databases').where('name=?', ('%s' % i,)).find() dbmsg.append(d) else: for i in masterinfo["replicate_dbs"]: d = public.M('databases').where('name=?', (i,)).find() dbmsg.append(d) masterinfo["slave_ip"] = [slave_ip] masterinfo["slave_port"] = [str(slave_port)] masterinfo["replicate_dbs_info"] = dbmsg addconf = """ log-slave-updates=true enforce-gtid-consistency=true gtid-mode=on """ if masterinfo["replicate_dbs"][0] == "alldatabases": masterinfo["slave_ips"] = public.M('config').where('id=?', (1,)).getField('mysql_root') print(masterinfo["master_version"]) if "5.5" not in masterinfo["master_version"] and not re.match("10",masterinfo["master_version"]): print(masterinfo["master_version"]) if not re.search("gtid-mode=on", mconf): mconf = re.sub("\[mysqld\]","[mysqld]"+ addconf,mconf) public.writeFile(self.__mfile,mconf) self.WriteLog("重启mysql") pid_old = public.ExecShell("ps aux|grep 'mysql.sock'|awk 'NR==1 {print $2}'")[0].split("\n")[0] self.WriteLog("旧PID %s" % pid_old) pid_new = pid_old public.writeFile("/tmp/mysqlpid", "") for i in range(10): if i == 0: os.system("/etc/init.d/mysqld restart &") time.sleep(10) pid_new = public.ExecShell("ps aux|grep 'mysql.sock'|awk 'NR==1 {print $2}'")[0].split("\n")[0] self.WriteLog("新PID %s" % pid_new) if pid_old == pid_new: time.sleep(10) pid_new = public.ExecShell("ps aux|grep 'mysql.sock'|awk 'NR==1 {print $2}'")[0].split("\n")[0] else: public.writeFile("/tmp/mysqlpid", "ok") break time.sleep(1) self.CreateSalveUser(masterinfo,slave_ip) keys = base64.b64encode(json.dumps(masterinfo)) public.writeFile(self.datafile, json.dumps(masterinfo)) return keys
def getReadFile(self, filePath): if not os.path.exists(filePath): return public.returnMsg(False, 'DIR_NOT_EXISTS_ERR') sites_data = json.loads(public.ReadFile(filePath)) return sites_data
def GetSlowLogs(self, get): path = self.GetMySQLInfo(get)['datadir'] + '/mysql-slow.log' if not os.path.exists(path): return public.returnMsg(False, 'AJAX_LOG_FILR_NOT_EXISTS') return public.returnMsg(True, public.GetNumLines(path, 100))
def InputSql(self, get): #try: result = panelMysql.panelMysql().execute("show databases") isError = self.IsSqlError(result) if isError: return isError name = get['name'] file = get['file'] root = public.M('config').where('id=?', (1, )).getField('mysql_root') tmp = file.split('.') exts = ['sql', 'gz', 'zip'] ext = tmp[len(tmp) - 1] if ext not in exts: return public.returnMsg(False, 'DATABASE_INPUT_ERR_FORMAT') isgzip = False if ext != 'sql': tmp = file.split('/') tmpFile = tmp[len(tmp) - 1] tmpFile = tmpFile.replace('.sql.' + ext, '.sql') tmpFile = tmpFile.replace('.' + ext, '.sql') tmpFile = tmpFile.replace('tar.', '') backupPath = session['config']['backup_path'] + '/database' if ext == 'zip': public.ExecShell("cd " + backupPath + " && unzip " + '"' + file + '"') else: public.ExecShell("cd " + backupPath + " && tar zxf " + '"' + file + '"') if not os.path.exists(backupPath + "/" + tmpFile): public.ExecShell("cd " + backupPath + " && gunzip -q " + '"' + file + '"') isgzip = True if not os.path.exists(backupPath + '/' + tmpFile) or tmpFile == '': return public.returnMsg(False, 'FILE_NOT_EXISTS', (tmpFile, )) if not self.mypass(True, root): return public.returnMsg( False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists' ) os.system( public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < " + '"' + backupPath + '/' + tmpFile + '"') if not self.mypass(True, root): return public.returnMsg( False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists' ) if isgzip: os.system('cd ' + backupPath + ' && gzip ' + file.split('/')[-1][:-3]) else: os.system("rm -f " + backupPath + '/' + tmpFile) else: if not self.mypass(True, root): return public.returnMsg( False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists' ) os.system( public.GetConfigValue('setup_path') + "/mysql/bin/mysql -uroot -p" + root + " --force \"" + name + "\" < " + '"' + file + '"') if not self.mypass(True, root): return public.returnMsg( False, 'Database configuration file failed to get checked, please check if MySQL configuration file exists' ) public.WriteLog("TYPE_DATABASE", 'DATABASE_INPUT_SUCCESS', (name, )) return public.returnMsg(True, 'DATABASE_INPUT_SUCCESS')
def AddDatabase(self, get): try: data_name = get['name'].strip() if self.CheckRecycleBin(data_name): return public.returnMsg(False, 'DATABASE_DEL_RECYCLE_BIN', (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, 'DATABASE_USER_NAME_ERR') if data_name in checks or len(data_name) < 1: return public.returnMsg(False, 'DATABASE_NAME_ERR') 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')
def AlTable(self, get): info = self.AlterTable(get) if info: return public.returnMsg(True, "CHANGE_SUCCESS") else: return public.returnMsg(False, "CHANVE_FAIL")
def DelToken(self, get): public.ExecShell("rm -f " + self.__UPATH) session['focre_cloud'] = True return public.returnMsg(True, "SSL_BTUSER_UN")
def StartTask(self, get): echo = public.M('crontab').where('id=?', (get.id, )).getField('echo') execstr = public.GetConfigValue('setup_path') + '/cron/' + echo public.ExecShell('chmod +x ' + execstr) public.ExecShell('nohup ' + execstr + ' >> ' + execstr + '.log 2>&1 &') return public.returnMsg(True, 'CRONTAB_TASK_EXEC')
def SetConfig(self,get): dnsStr = "nameserver " + get.dns1 + "\n" if get.dns2: dnsStr += "nameserver " + get.dns2 + '\n' public.writeFile('/etc/resolv.conf',dnsStr) return public.returnMsg(True,'设置成功!')
def syncDate(self, get): result = public.ExecShell("ntpdate 0.asia.pool.ntp.org") public.WriteLog("TYPE_PANEL", "DATE_SUCCESS") return public.returnMsg(True, "DATE_SUCCESS")
def close_panel_limit(self, get): if os.path.exists(self.__LIMIT_CONF): os.remove(self.__LIMIT_CONF) return public.returnMsg(True, '已关闭IP限制!')
def SetTemplates(self, get): public.writeFile('data/templates.pl', get.templates) return public.returnMsg(True, 'SET_SUCCESS')
def flush_pay_status(self, get): if 'get_product_bay' in web.ctx.session: del (web.ctx.session['get_product_bay']) data = self.get_plugin_list(get) if not data: return public.returnMsg(False, '连接服务器失败!') return public.returnMsg(True, '状态刷新成功!')
def modify_msgpush(self,get): data = self.get_msgpush_list(get) push_name = get.push_name get_data = get.__dict__ keys = {"push_type":"推送类型", "cpu_alarm_value":"CPU阈值", "cpu_check_time":"CPU检查周期", "mem_alarm_value":"内存阈值", "mem_check_time":"内存检查周期", "net_alarm_value":"带宽预警阈值", "net_check_time":"带宽监测时间", "net_bandwidth":"最大带宽", "site_check_url":"检查URL", "site_check_word":"检查关键字", "disk_alarm_value":"监控磁盘阈值", "url_list":"监控域名", "adv":"精确站点监控", "key":"监控站点关键字", "site_name":"监控站点", "push_time":"推送间隔时间", "report":"报表发送时间", "report_type":"报表类型", "netcard":"网卡", "open":"检测开关"} alter_options = "" try: push_time = get.push_time except: get.push_time = 10 if int(get.push_time) < 10: return public.returnMsg(False, '邮件发送间隔时间不能小于10分钟') for i in data: if push_name == i["push_name"]: if not i.has_key("push_time"): i["push_time"] = "10" for k in keys.keys(): try: if get_data[k]: if "value" in k: try: a = int(get_data[k]) if a <= 0 or a > 100: return public.returnMsg(False, '阈值不能小于等于0或大于100') except: return public.returnMsg(False, '请输入整数') if "time" in k: try: a = int(get_data[k]) if a <= 0: return public.returnMsg(False, '不能输入负数或0') except: return public.returnMsg(False, '请输入整数') if str(i[k]) != get_data[k]: ldata = "" udata = "" if "value" in k: ldata += i[k] + "%" udata += get_data[k] + "%" elif "time" in k: ldata += i[k] + "分钟" udata += get_data[k] + "分钟" elif "open" in k or "adv" in k: if get_data[k] == "1": udata += "开启" ldata += "关闭" else: udata += "关闭" ldata += "开启" elif "bandwidth" in k: udata += get_data[k] + "Mbps" ldata += i[k] + "Mbps" elif "url" in k: udata += get_data[k] ldata += i[k] else: udata += get_data[k] ldata += i[k] alter_options += '推送名称 "%s" 的%s "%s" 修改为 "%s"' % (push_name, keys[k], ldata, udata) i[k] = get_data[k] except: pass if alter_options: public.WriteLog('消息推送', ' 修改配置[' + alter_options + ']') for i in data: try: if i["url_list"]: site = { "url_list":i["url_list"], "key":i["key"], "adv":i["adv"], "site_name":i["site_name"] } i.pop("url_list") i.pop("key") i.pop("adv") i.pop("site_name") i["site"] = site except: pass self.__write_config(self.__confPath, data) return public.returnMsg(True, '修改成功')
def BackUpMasterDbs(self,get): import MySQLdb bakpath = "/www/backup/database" # 是否为ip iprep = "(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})" if re.search(iprep, get.master_ip): master_ip = re.search(iprep, get.master_ip).group() else: print('请输入正确的IP地址') return public.returnMsg(False, '请输入正确的IP地址') ip = self.GetLocalIP() for i in ip: if i == master_ip: return public.returnMsg(False, '不能输入本机的IP') # 解码 masterinfo = json.loads(base64.b64decode(get.keys)) masterinfo["master_ip"] = master_ip # slave_version = pm.panelMysql().query("select version()")[0][0].split("-")[0] slave_version = self.GetVersion() masterinfo["slave_version"] = slave_version # 写入data.json供设置速度使用 self.WriteLog(json.dumps(masterinfo)) public.writeFile(self.datafile, json.dumps(masterinfo)) if not self.CheckPort(master_ip, masterinfo["master_port"]): return public.returnMsg(False, '无法访问从服务器<br>请确认安全组是否已经放行<br>Mysql端口:%s' % masterinfo["master_port"]) if slave_version in masterinfo["master_version"]: try: master_port = int(masterinfo["master_port"]) except Exception as e: return public.returnMsg(False, e) try: db = MySQLdb.connect(host=masterinfo["master_ip"],port=master_port, user="******", passwd=masterinfo["btmysql"], charset="utf8") cur = db.cursor() except: return public.returnMsg(False, '无法连接主服务器,请确定主服务器 IP端口是否正确,安全组是否已经放行Mysql端口') # 开始备份 backsqlpath = "%s/masterslave.sql" % (bakpath) backsh = "nohup mysqldump -h%s -P%s -u%s -p%s --master-data=2 --skip-lock-tables --single-transaction %s%s 1> %s 2>/dev/null&" if masterinfo["replicate_dbs"][0] == "alldatabases": print("Starting backup of databases alldatabases") self.WriteLog("开始备份数据库") # 统计数据库大小 cur.execute("select concat(round(sum(data_length/1024/1024),2),'MB') as data from information_schema.tables") total_db = int(float(cur.fetchall()[0][0].split("M")[0])) print(total_db) if total_db == 0: total_db = 2 public.writeSpeed("备份数据库",1,total_db) # 开始备份数据库 try: self.WriteLog("备份数据库 %s" % "alldatabases") error = public.ExecShell(backsh % (masterinfo["master_ip"], masterinfo["master_port"], "btmysql", masterinfo["btmysql"],"--all-databases","",backsqlpath))[1] if "error" in error or "not exist" in error: return public.returnMsg(False, '数据库备份失败 %s\n错误信息:%s\n ,请检测主库是否有问题' % ("alldatabases", error)) except: self.WriteLog("备份失败 %s" % "alldatabases") return public.returnMsg(False, '数据库备份失败 %s' % "alldatabases") threading.Thread(target=self.SetSpeed()).start() else: total_db = 1 replicate_dbs = "" cur.execute("use information_schema") for d in masterinfo["replicate_dbs"]: replicate_dbs += " %s " % d # 统计数据库大小 cur.execute("select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='%s'" % d) a = cur.fetchall()[0][0] if a: total_db += float(a.split("M")[0]) print(total_db) public.writeSpeed("备份数据库", 1, int(total_db)) print("Starting backup of databases %s" % replicate_dbs) # 开始备份数据库 try: self.WriteLog("备份数据库 %s" % replicate_dbs) error = public.ExecShell(backsh % ( masterinfo["master_ip"], masterinfo["master_port"], "btmysql", masterinfo["btmysql"], "--databases", replicate_dbs, backsqlpath))[1] if "error" in error or "not exist" in error: return public.returnMsg(False, '数据库备份失败 %s\n错误信息:%s\n ,请检测主库是否有问题' % ("replicate_dbs", error)) except: self.WriteLog("备份失败 %s" % replicate_dbs) return public.returnMsg(False, '数据库备份失败 %s' % replicate_dbs) threading.Thread(target=self.SetSpeed()).start() self.WriteLog("备份成功") masterlogdata = public.ExecShell("head -n 50 %s" % backsqlpath) try: masterlogdata = masterlogdata[0] rep = "CHANGE MASTER TO MASTER_LOG_FILE='([\w\-\.]+)',\s*MASTER_LOG_POS=(\d+);" logfile = re.search(rep, masterlogdata).group(1) logpos = re.search(rep, masterlogdata).group(2) except: return public.returnMsg(False, '获取Master信息失败') try: gtid = self.__ExceSql('SELECT BINLOG_GTID_POS("%s", %s)' % (logfile,logpos),masterinfo=masterinfo)[0].split("\n")[1] except: gtid = "" db.close() public.writeFile("%s/log.txt" % bakpath,str([logfile,logpos])) masterinfo["logfile"] = logfile masterinfo["logpos"] = logpos masterinfo["gtid"] = gtid masterinfo["backsqlpath"] = backsqlpath public.writeFile("%s/plugin/masterslave/data.json" % self.setpath, json.dumps(masterinfo)) public.writeFile("/tmp/mysql.log", masterinfo, "a+") return masterinfo else: self.WriteLog("mysql版本不一致 主版本%s 从版本%s" % (masterinfo["master_version"],slave_version)) return public.returnMsg(False, 'mysql版本不一致 主版本%s 从版本%s' % (masterinfo["master_version"],slave_version))
def remove_email(self, get): emails = self.get_email_list(get)['emails'] emails.remove(get.email) public.WriteLog('消息推送', '删除收件地址[' + get.email + ']') self.__write_config(self.__mail_list,emails) return public.returnMsg(True, '删除成功')
def GetReplicateStatus(self,get): conf = public.readFile(self.datafile) status_list = [] if os.path.exists(self.datafile) and conf != "": conf = json.loads(conf) # 兼容旧版本设置 if not isinstance(conf["slave_ip"],list): conf["slave_ip"] = [conf["slave_ip"]] conf["slave_port"] = [str(conf["slave_port"])] conf["slave_id"] = [int(conf["master_id"])+1] public.writeFile(self.datafile,json.dumps(conf)) try: slaveip = conf["slave_ip"] slaveport = conf["slave_port"] if "master_ip" in conf.keys(): slavestatus = pm.panelMysql().query("show slave status")[0] Slave_IO_Running = slavestatus[10] Slave_SQL_Running = slavestatus[11] master_ip = conf["master_ip"] slave_ip = "local" else: for i in slaveip: master_ip = "local" slave_ip = i if not self.CheckPort(slave_ip, slaveport[slaveip.index(i)]): status = { "Slave_IO_Running": "no", "Slave_SQL_Running": "no", "master_ip": master_ip, "slave_ip": slave_ip, "slavestatus": slavestatus, "replicate_dbs": conf["replicate_dbs"], "slave_port": slaveport[slaveip.index(i)] } status_list.append(status) continue # return public.returnMsg(False, '无法访问从服务器<br>请确认安全组是否已经放行<br>Mysql端口:%s' % i+":"+slaveport[slaveip.index(i)]) slavestatus = public.ExecShell( "mysql -h%s -P%s --connect_timeout=3 -u%s -p%s -e 'show slave status\G'" % (i,slaveport[slaveip.index(i)],"user"+conf["slave_user"],"pass"+conf["slave_pass"]))[0] Slave_IO_Running = "Slave_IO_Running:\s+(\w+)" Slave_SQL_Running = "Slave_SQL_Running:\s+(\w+)" if not slavestatus: Slave_IO_Running = "no" Slave_SQL_Running = "no" else: Slave_IO_Running = re.search(Slave_IO_Running, slavestatus).group(1) Slave_SQL_Running = re.search(Slave_SQL_Running, slavestatus).group(1) status = { "Slave_IO_Running": Slave_IO_Running, "Slave_SQL_Running": Slave_SQL_Running, "master_ip": master_ip, "slave_ip": slave_ip, "slavestatus": slavestatus, "replicate_dbs": conf["replicate_dbs"], "slave_port": slaveport[slaveip.index(i)] } status_list.append(status) except: slavestatus = "" Slave_IO_Running = "no" Slave_SQL_Running = "no" master_ip = "" slave_ip = "" else: return public.returnMsg(True, "获取成功") if not status_list: status_list = [{ "Slave_IO_Running": Slave_IO_Running, "Slave_SQL_Running": Slave_SQL_Running, "master_ip": master_ip, "slave_ip": slave_ip, "slavestatus": slavestatus, "replicate_dbs": conf["replicate_dbs"] }] return public.returnMsg(True, status_list)
def CheckServer(self, get): a = public.ExecShell("ps aux|grep 'msg_push'|grep -v 'grep'|wc -l")[0].strip() if a == "0": return public.returnMsg(False, '服务未启动') else: return public.returnMsg(True, '服务已启动')
def SetupPackage(self, get): name = get.dname site_name = get.site_name php_version = get.php_version #取基础信息 find = public.M('sites').where( 'name=?', (site_name, )).field('id,path,name').find() path = find['path'] if path.replace('//', '/') == '/': return public.returnMsg(False, 'Dangerous website root directory!') #获取包信息 pinfo = self.GetPackageInfo(name) id = pinfo['id'] if not pinfo: return public.returnMsg(False, 'The specified package does not exist.!') #检查本地包 self.WriteLogs( json.dumps({ 'name': 'Verifying package...', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) pack_path = self.__panelPath + '/package' if not os.path.exists(pack_path): os.makedirs(pack_path, 384) packageZip = pack_path + '/' + name + '.zip' isDownload = False if os.path.exists(packageZip): md5str = self.GetFileMd5(packageZip) if md5str != pinfo['versions'][0]['md5']: isDownload = True else: isDownload = True #下载文件 if isDownload: self.WriteLogs( json.dumps({ 'name': 'Downloading file ...', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if pinfo['versions'][0]['download']: self.DownloadFile( 'http://www.bt.cn/api/Pluginother/get_file?fname=' + pinfo['versions'][0]['download'], packageZip) if not os.path.exists(packageZip): return public.returnMsg(False, 'File download failed!' + packageZip) pinfo = self.set_temp_file(packageZip, path) if not pinfo: return public.returnMsg( False, 'Cannot find [aaPanel Auto Deployment Configuration File] in the installation package' ) #设置权限 self.WriteLogs( json.dumps({ 'name': 'Setting permissions', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) os.system('chmod -R 755 ' + path) os.system('chown -R www.www ' + path) if pinfo['chmod']: for chm in pinfo['chmod']: os.system('chmod -R ' + str(chm['mode']) + ' ' + (path + '/' + chm['path']).replace('//', '/')) #安装PHP扩展 self.WriteLogs( json.dumps({ 'name': 'Install the necessary PHP extensions', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) import files mfile = files.files() if type(pinfo['php_ext']) == str: pinfo['php_ext'] = pinfo['php_ext'].strip().split(',') for ext in pinfo['php_ext']: if ext == 'pathinfo': import config con = config.config() get.version = php_version get.type = 'on' con.setPathInfo(get) else: get.name = ext get.version = php_version get.type = '1' mfile.InstallSoft(get) #解禁PHP函数 if 'enable_functions' in pinfo: try: if type(pinfo['enable_functions']) == str: pinfo['enable_functions'] = pinfo[ 'enable_functions'].strip().split(',') php_f = public.GetConfigValue( 'setup_path') + '/php/' + php_version + '/etc/php.ini' php_c = public.readFile(php_f) rep = "disable_functions\s*=\s{0,1}(.*)\n" tmp = re.search(rep, php_c).groups() disable_functions = tmp[0].split(',') for fun in pinfo['enable_functions']: fun = fun.strip() if fun in disable_functions: disable_functions.remove(fun) disable_functions = ','.join(disable_functions) php_c = re.sub( rep, 'disable_functions = ' + disable_functions + "\n", php_c) public.writeFile(php_f, php_c) public.phpReload(php_version) except: pass #执行额外shell进行依赖安装 self.WriteLogs( json.dumps({ 'name': 'Execute extra SHELL', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if os.path.exists(path + '/install.sh'): os.system('cd ' + path + ' && bash ' + 'install.sh ' + find['name'] + " &> install.log") os.system('rm -f ' + path + '/install.sh') #是否执行Composer if os.path.exists(path + '/composer.json'): self.WriteLogs( json.dumps({ 'name': 'Execute Composer', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if not os.path.exists(path + '/composer.lock'): execPHP = '/www/server/php/' + php_version + '/bin/php' if execPHP: if public.get_url().find('125.88'): os.system( 'cd ' + path + ' && ' + execPHP + ' /usr/bin/composer config repo.packagist composer https://packagist.phpcomposer.com' ) import panelSite phpini = '/www/server/php/' + php_version + '/etc/php.ini' phpiniConf = public.readFile(phpini) phpiniConf = phpiniConf.replace( 'proc_open,proc_get_status,', '') public.writeFile(phpini, phpiniConf) os.system( 'nohup cd ' + path + ' && ' + execPHP + ' /usr/bin/composer install -vvv > /tmp/composer.log 2>&1 &' ) #写伪静态 self.WriteLogs( json.dumps({ 'name': 'Set URL rewrite', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) swfile = path + '/nginx.rewrite' if os.path.exists(swfile): rewriteConf = public.readFile(swfile) dwfile = self.__panelPath + '/vhost/rewrite/' + site_name + '.conf' public.writeFile(dwfile, rewriteConf) swfile = path + '/.htaccess' if os.path.exists(swfile): swpath = (path + '/' + pinfo['run_path'] + '/.htaccess').replace( '//', '/') if pinfo['run_path'] != '/' and not os.path.exists(swpath): public.writeFile(swpath, public.readFile(swfile)) #删除伪静态文件 public.ExecShell("rm -f " + path + '/*.rewrite') #删除多余文件 rm_file = path + '/index.html' if os.path.exists(rm_file): rm_file_body = public.readFile(rm_file) if rm_file_body.find('panel-heading') != -1: os.remove(rm_file) #设置运行目录 self.WriteLogs( json.dumps({ 'name': 'Set the run directory', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if pinfo['run_path'] != '/': import panelSite siteObj = panelSite.panelSite() mobj = obj() mobj.id = find['id'] mobj.runPath = pinfo['run_path'] siteObj.SetSiteRunPath(mobj) #导入数据 self.WriteLogs( json.dumps({ 'name': 'Import database', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if os.path.exists(path + '/import.sql'): databaseInfo = public.M('databases').where( 'pid=?', (find['id'], )).field('username,password').find() if databaseInfo: os.system('/www/server/mysql/bin/mysql -u' + databaseInfo['username'] + ' -p' + databaseInfo['password'] + ' ' + databaseInfo['username'] + ' < ' + path + '/import.sql') os.system('rm -f ' + path + '/import.sql') siteConfigFile = (path + '/' + pinfo['db_config']).replace( '//', '/') if os.path.exists(siteConfigFile): siteConfig = public.readFile(siteConfigFile) siteConfig = siteConfig.replace('BT_DB_USERNAME', databaseInfo['username']) siteConfig = siteConfig.replace('BT_DB_PASSWORD', databaseInfo['password']) siteConfig = siteConfig.replace('BT_DB_NAME', databaseInfo['username']) public.writeFile(siteConfigFile, siteConfig) #清理文件和目录 self.WriteLogs( json.dumps({ 'name': '清理多余的文件', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if type(pinfo['remove_file']) == str: pinfo['remove_file'] = pinfo['remove_file'].strip().split(',') print(pinfo['remove_file']) for f_path in pinfo['remove_file']: if not f_path: continue filename = (path + '/' + f_path).replace('//', '/') if os.path.exists(filename): if not os.path.isdir(filename): if f_path.find('.user.ini') != -1: public.ExecShell("chattr -i " + filename) os.remove(filename) else: public.ExecShell("rm -rf " + filename) public.serviceReload() if id: self.depTotal(id) self.WriteLogs( json.dumps({ 'name': 'Ready to deploy', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) return public.returnMsg(True, pinfo)
def CheckTotal(self,get): path = "/www/server/panel/plugin/total/total_main.py" if not os.path.exists(path): return public.returnMsg(False, '请先安装监控报表') else: return public.returnMsg(True, '已经安装监控报表')
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
def add_panel_limit(self, get): limitIp = self.get_panel_limit() if get.ip in limitIp: return public.returnMsg(True, '指定IP白名单已存在!') limitIp.append(get.ip) public.writeFile(self.__LIMIT_CONF, ','.join(limitIp)) return public.returnMsg(True, '添加成功!')
def clean_panel_error_logs(self, get): filename = 'logs/error.log' public.writeFile(filename, '') public.WriteLog('P_CONF', 'CLEARING_LOG') return public.returnMsg(True, 'CLEARED')
def remove_panel_limit(self, get): limitIp = self.get_panel_limit() if not get.ip in limitIp: return public.returnMsg(True, '指定IP白名单不存在!') limitIp.remove(get.ip) public.writeFile(self.__LIMIT_CONF, ','.join(limitIp)) return public.returnMsg(True, '删除成功!')
def ReloadNetwork(self,get): if os.path.exists('/usr/bin/systemctl'): os.system('systemctl restart network.service') else: os.system('service network reload') return public.returnMsg(True,'网络已重启!')
def SetSessionConf(self, get): g = get.save_handler ip = get.ip port = get.port passwd = get.passwd if g != "files": iprep = "(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})\.(2(5[0-5]{1}|[0-4]\d{1})|[0-1]?\d{1,2})" if not re.search(iprep, ip): return public.returnMsg(False, 'FIREWALL_IP_FORMAT') try: port = int(port) if port >= 65535 or port < 1: return public.returnMsg(False, 'SITE_ADD_ERR_PORT') except: return public.returnMsg(False, 'SITE_ADD_ERR_PORT') prep = "[\~\`\/\=]" if re.search(prep, passwd): return public.returnMsg(False, 'SPECIAL_CHARACTRES', ('" ~ ` / = "')) filename = '/www/server/php/' + get.version + '/etc/php.ini' phpini = public.readFile(filename) rep = 'session.save_handler\s*=\s*(.+)\r?\n' val = 'session.save_handler = ' + g + '\n' phpini = re.sub(rep, val, phpini) if g == "memcached": if not re.search("memcached.so", phpini): return public.returnMsg(False, 'INSTALL_EXTEND_FIRST', (g)) rep = '\nsession.save_path\s*=\s*(.+)\r?\n' val = '\nsession.save_path = "%s:%s" \n' % (ip, port) if re.search(rep, phpini): phpini = re.sub(rep, val, phpini) else: phpini = re.sub('\n;session.save_path = "/tmp"', '\n;session.save_path = "/tmp"' + val, phpini) if g == "memcache": if not re.search("memcache.so", phpini): return public.returnMsg(False, 'INSTALL_EXTEND_FIRST', (g)) rep = '\nsession.save_path\s*=\s*(.+)\r?\n' val = '\nsession.save_path = "tcp://%s:%s"\n' % (ip, port) if re.search(rep, phpini): phpini = re.sub(rep, val, phpini) else: phpini = re.sub('\n;session.save_path = "/tmp"', '\n;session.save_path = "/tmp"' + val, phpini) if g == "redis": if not re.search("redis.so", phpini): return public.returnMsg(False, 'INSTALL_EXTEND_FIRST', (g)) if passwd: passwd = "?auth=" + passwd else: passwd = "" rep = '\nsession.save_path\s*=\s*(.+)\r?\n' val = '\nsession.save_path = "tcp://%s:%s%s"\n' % (ip, port, passwd) res = re.search(rep, phpini) if res: phpini = re.sub(rep, val, phpini) else: phpini = re.sub('\n;session.save_path = "/tmp"', '\n;session.save_path = "/tmp"' + val, phpini) if g == "files": rep = '\nsession.save_path\s*=\s*(.+)\r?\n' val = '\nsession.save_path = "/tmp"\n' if re.search(rep, phpini): phpini = re.sub(rep, val, phpini) else: phpini = re.sub('\n;session.save_path = "/tmp"', '\n;session.save_path = "/tmp"' + val, phpini) public.writeFile(filename, phpini) os.system('/etc/init.d/php-fpm-' + get.version + ' reload') return public.returnMsg(True, 'SET_SUCCESS')