def _restore_backup(self, local_backup_file_path, site_info, args): # 判断备份文件是否存在,如果不存在继续检查是否远程备份 if not os.path.exists(local_backup_file_path): self._progress_rewrite('No backup file found: {}'.format( str(local_backup_file_path))) return public.returnMsg( False, 'Panel does not find the backup file: {}'.format( local_backup_file_path)) # 将网站目录移至回收站 self._progress_rewrite( 'Move the current website directory to the recycle bin: {}'.format( str(args.path))) self._remove_old_website_file_to_trush(args) if not os.path.exists(args.path): self._progress_rewrite( 'Create an empty directory for the site: {}'.format( str(args.path))) os.makedirs(site_info['site_path']) if 'zip' in args.file_name: uncompress_comand = 'unzip' else: uncompress_comand = 'tar -zxvf' self._progress_rewrite('The decompression command is: {}'.format( str(uncompress_comand))) self._progress_rewrite('Start to restore data......') public.ExecShell('cd {} && {} {} >> /tmp/restore_site.log'.format( site_info['site_path'], uncompress_comand, local_backup_file_path)) if len(os.listdir(site_info['site_path'])) == 2: public.ExecShell('cd {s} && mv {s}/{d}/* .'.format( s=site_info['site_path'], d=site_info['site_name'])) public.ExecShell('cd {s} && rmdir {d}'.format( s=site_info['site_path'], d=site_info['site_name'])) # 将文件全新设置为644,文件夹设置为755 self._progress_rewrite('Setting site permissions......') files.files().fix_permissions(args)
def menu(client) : while True : client.send("dialog --menu \"Menu List\" 30 50 8 1 \"User Management\" 2 \"Directory Management\" 3 \"File Management\" 4 \"Software Management\" 5 \"Device Partition Management\" 6 \"Logical Volume Management\" 7 \"Server Management\" 8 \"Exit\" ") choice = client.recv(10) if choice == "1" : import user user.user(client) elif choice == "2" : import dirs dirs.dirs(client) elif choice == "3" : import files files.files(client) elif choice == "4" : import software software.software(client) elif choice == "5" : import dpm dpm.dpm(client) elif choice == "6" : import lvm lvm.lvm(client) elif choice == "7" : import sm sm.sm(client) elif choice == "8" : client.send("recieve only") client.send("dialog --infobox \"Thank You... \n Exiting....\" 5 18") client.send("false")
def set_file_accept(self, filename): # public.ExecShell('chown -R www:www ' + filename) # public.ExecShell('chmod -R 755 ' + filename) import files from collections import namedtuple get = namedtuple('get', ['path']) get.path = filename files.files().fix_permissions(get)
def POST(self): get = web.input(zunfile = {},data = []) if hasattr(get,'path'): get.path = get.path.replace('//','/').replace('\\','/'); import files filesObject = files.files() defs = ( 'UploadFile', 'GetDir', 'CreateFile', 'CreateDir', 'DeleteDir', 'DeleteFile', 'CopyFile', 'CopyDir', 'MvFile', 'GetFileBody', 'SaveFileBody', 'Zip', 'UnZip', 'GetFileAccess', 'SetFileAccess', 'GetDirSize', 'SetBatchData', 'BatchPaste', 'DownloadFile', 'setPassword' ) for key in defs: if key == get.action: fun = 'filesObject.'+key+'(get)' return public.getJson(eval(fun)) return public.returnJson(False,'Invalid specified parameter!')
def __init__(self, user_Id, impersonation = False): super(user, self).__init__() self.user_Id = user_Id self.impersonation = impersonation if self.impersonation: self.file_prefs = (DIR_SETTINGS + 'gDrivePro.json') prefs = load(self.file_prefs) # client_id = prefs.get('client_id', None) or raw_input('Please enter the id for your Google API client: ') # client_secret = prefs.get('client_secret', None) or raw_input('Please enter the secret for your Google API client: ') # scope = ["https://www.googleapis.com/auth/drive"] tokens = prefs.get('tokens') data = load(DIR_SETTINGS + 'oauth2service.json') private_key = data.get('private_key') client_email = data.get('client_email') scope = ['https://www.googleapis.com/auth/drive'] self.auth = auth.ServiceAuthenticator(client_email, private_key, scope, tokens) else: pass self.file = files(self) self.proc = processor(self)
def AddUser(self,get): try: if not os.path.exists('/www/server/pure-ftpd/sbin/pure-ftpd'): return public.returnMsg(False,'Please install the Pure-FTPd service in the software store first.') 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) public.ExecShell('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=public.xssencode(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 as ex: public.WriteLog('TYPE_FTP', 'FTP_ADD_ERR',(username,str(ex))) return public.returnMsg(False,'ADD_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 send_file(self,local_path): ''' send file over tcp this method implement the protocol :param client: :param local_path: :return: ''' if os.path.isfile(local_path): fileStream = files.files(1024) fileStream.open(local_path,mode='rb') fileName = os.path.basename(local_path) client =tcp_client.tcp_client(self.ip,self.port,5) if os.path.exists(local_path): client.connect() print("Sending " + fileName + " to " + str(self.ip) + ":" + str(self.port)) # send command client.write_bin(b'0xff') # send remote path where file is going to be copied client.write_bin(self._to_byte(self.rem_path)) # send file name client.write_bin(self._to_byte(fileName)) #send file self._read_and_send(client,fileStream) fileStream.close() client.close() print("File sent") else: print('file does not exists') else: print("Local path must be path file")
def delete(self, name): f = files.files(name) f.deleteFile() # delete sub files lSubFiles = f.getListResizeFilesToDir() for __file in lSubFiles: f.deleteFile(__file) return 'ok'
def POST(self): import files filesObject = files.files() defs = ('CheckExistsFiles','GetExecLog','GetSearch','ExecShell','GetExecShellMsg','UploadFile','GetDir','CreateFile','CreateDir','DeleteDir','DeleteFile', 'CopyFile','CopyDir','MvFile','GetFileBody','SaveFileBody','Zip','UnZip', 'GetFileAccess','SetFileAccess','GetDirSize','SetBatchData','BatchPaste', 'DownloadFile','GetTaskSpeed','CloseLogs','InstallSoft','UninstallSoft', 'RemoveTask','ActionTask','Re_Recycle_bin','Get_Recycle_bin','Del_Recycle_bin','Close_Recycle_bin','Recycle_bin') return publicObject(filesObject,defs);
def upload(self): filename = self.__data['fileToUpload'].filename if len(filename) == 0: return self.sendError('is no file') self.delete(filename) f = files.files(filename) if f.isPath() == False: f.createDir(f.getPath()) curFile = f.getPathFile() self.__data['fileToUpload'].save(curFile) return self.send(f.getSitePathFile())
def GetRedirectFile(self,get): import files conf = self.__read_config(self.__redirectfile) sitename = get.sitename redirectname = get.redirectname proxyname_md5 = self.__calc_md5(redirectname) get.path = "%s/panel/vhost/%s/redirect/%s/%s_%s.conf" % (self.setupPath, get.webserver, sitename,proxyname_md5,sitename) for i in conf: if redirectname == i["redirectname"] and sitename == i["sitename"] and i["type"] != 1: return public.returnMsg(False, '重定向已暂停') f = files.files() return f.GetFileBody(get),get.path
def make_cdi (sfobj, name, defaults_file = None, eff_file = None, wp_file = None, continuous_file = None, slim = None, Check=True): rf = FutureFile() df = defaults_file if not isinstance(df, sfObject): df = files(df, no_files_ok = True) ef = eff_file if not isinstance(ef, sfObject): ef = files(ef, no_files_ok = True) wp = wp_file if not isinstance(wp, sfObject): wp = files(wp, no_files_ok = True) continuous = continuous_file if not isinstance(continuous, sfObject): continuous = files(continuous, no_files_ok = True) comboGlobals.Commands += [CDI(sfobj, name, df, ef, wp, continuous, slim, Check, rf)] return rf
def resize(self, **args): name = args['args'].get('name', 'none') w = args['args'].get('w', 0) h = args['args'].get('h', 0) f = files.files(name) if f.isFile(): img = Image.open(f.getPathFile()) newSize = resize.getNewSize(img.size, w=w, h=h) img.resize(newSize, PIL.Image.BICUBIC).save(f.getPathFileResize(w, h)) return img.format, f.getPathFileResize(w, h) else: return 'error', ''
def files(pdata = None): comReturn = comm.local() if comReturn: return comReturn if request.method == method_get[0] and not request.args.get('path') and not pdata: data = {} data['lan'] = public.GetLan('files') return render_template('files.html',data=data) import files filesObject = files.files() defs = ('CheckExistsFiles','GetExecLog','GetSearch','ExecShell','GetExecShellMsg','UploadFile','GetDir','CreateFile','CreateDir','DeleteDir','DeleteFile', 'CopyFile','CopyDir','MvFile','GetFileBody','SaveFileBody','Zip','UnZip','SearchFiles','upload','read_history', 'GetFileAccess','SetFileAccess','GetDirSize','SetBatchData','BatchPaste','install_rar','get_path_size', 'DownloadFile','GetTaskSpeed','CloseLogs','InstallSoft','UninstallSoft','SaveTmpFile','GetTmpFile','del_files_store','add_files_store','get_files_store','del_files_store_types','add_files_store_types', 'RemoveTask','ActionTask','Re_Recycle_bin','Get_Recycle_bin','Del_Recycle_bin','Close_Recycle_bin','Recycle_bin') return publicObject(filesObject,defs,None,pdata);
def WriteBlockToDisk(self, term, posting_list, num): file_name = "%s%d.%s" % ('Merge', self.merge_num, 'txt') # print file_name file_path = self.directory + file_name file = files(file_path) file.open_file('a') # file = open(file_path,'w') if self.flag: file.close_file() self.flag = False return file_path else: if num == self.length: self.term_num += 1 self.posting_list_num += len(posting_list) file.write_file(block(term, posting_list))
def modify_data_directory(self, args): # 修改储存路径 # 处理前端传过来的参数 args = self.processing_parameter(args) old_data_directory = self.get_data_directory(args)['data'] new_data_directory = args.data_directory if not files.files().CheckDir(new_data_directory) or not str(new_data_directory).strip().startswith("/"): return {'data': "您提交的目录不合法,迁移失败", "status": False} public.ExecShell("mkdir -p {}".format(new_data_directory)) public.ExecShell("/etc/init.d/pgsql stop") public.ExecShell('''cp -ar {}/* {} '''.format(old_data_directory, new_data_directory)) public.ExecShell('''chown -R postgres:postgres {}'''.format(new_data_directory)) public.ExecShell('''chmod -R 700 {} '''.format(new_data_directory)) public.ExecShell('''chmod 777 /www/server/pgsql/logs/pgsql.log ''') public.WriteFile("/www/server/pgsql/data_directory", new_data_directory, mode='w') public.ExecShell("/etc/init.d/pgsql start") # 返回数据到前端 return {'data': "迁移成功", "status": True}
def WriteBlockToDisk(self, sorted_iterms, dictionary, output_file): file_name = "%s%d.%s" % ('block', self.block_num, 'txt') print file_name file_path = self.directory + file_name print file_path # if not os.path.exists(file_path): # os.mknod(file_path) file = files(file_path) file.open_file('w') # file = open(file_path,'w') for term in sorted_iterms: # print dictionary[term] # file.write_file(content) file.write_file(block(term, dictionary[term])) # file.close_file() file.close_file() return file
def WriteBlockToDisk(self, term, posting_list): file_name = "%s%d.%s" % ('Merge', self.merge_num, 'txt') # print file_name file_path = self.directory + file_name # print file_path # if not os.path.exists(file_path): # os.mknod(file_path) file = files(file_path) file.open_file('a') # file = open(file_path,'w') if self.flag: file.close_file() self.flag = False return file_path # for term in sorted_iterms: # print dictionary[term] # file.write_file(content) # print posting_list else: file.write_file(block(term, posting_list))
cwd = os.getcwd() os.system("cd "+cwd) print("working direcory :"+cwd) #vertical image and pad vertical2H=vertical2H() vertical2H.getvimg() vertical2H.v2h() #img to mp4 converter img2mp4=img2mp4() img2mp4.getimg2mp4() #get list of videos vlist=files().getfiles() #select subclip subclip=subclip() subclip.getsubclip(vlist) #check size/audio videofix=videofix() videofix.videofix(subclip.vlistedit) #slomotion random slowmo=slowmo() slowmo.getslowmo(subclip.vlistedit) #concatenate all video concatenate=concatenate()
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').find(); path = find['path']; #获取包信息 pinfo = self.GetPackageInfo(name); if not pinfo: return public.returnMsg(False,'指定软件包不存在!'); #检查本地包 self.WriteLogs(json.dumps({'name':'检查软件包','total':0,'used':0,'pre':0,'speed':0})); packageZip = self.__setupPath + '/package/' + name + '.zip'; isDownload = False; if os.path.exists(packageZip): md5str = self.GetFileMd5(packageZip); if md5str != pinfo['md5']: isDownload = True; else: isDownload = True; #下载文件 if isDownload: self.WriteLogs(json.dumps({'name':'下载文件','total':0,'used':0,'pre':0,'speed':0})); self.DownloadFile(pinfo['download'], packageZip); if not os.path.exists(packageZip): return public.returnMsg(False,'文件下载失败!'); os.system('unzip -o '+packageZip+' -d ' + path + '/'); #设置权限 self.WriteLogs(json.dumps({'name':'设置权限','total':0,'used':0,'pre':0,'speed':0})); os.system('chmod -R 755 ' + path); os.system('chown -R www.www ' + path); if pinfo['chmod'] != "": access = pinfo['chmod'].split(',') for chm in access: tmp = chm.split('|'); if len(tmp) != 2: continue; os.system('chmod -R ' + tmp[0] + ' ' + path + '/' + tmp[1]); #安装PHP扩展 self.WriteLogs(json.dumps({'name':'安装必要的PHP扩展','total':0,'used':0,'pre':0,'speed':0})); if pinfo['ext'] != '': exts = pinfo['ext'].split(','); import files mfile = files.files(); for ext in exts: 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); #执行额外shell进行依赖安装 self.WriteLogs(json.dumps({'name':'执行额外SHELL','total':0,'used':0,'pre':0,'speed':0})); if os.path.exists(path+'/install.sh'): os.system('cd '+path+' && bash ' + 'install.sh'); os.system('rm -f ' + path+'/install.sh') #是否执行Composer if os.path.exists(path + '/composer.json'): self.WriteLogs(json.dumps({'name':'执行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':'设置伪静态','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); #设置运行目录 self.WriteLogs(json.dumps({'name':'设置运行目录','total':0,'used':0,'pre':0,'speed':0})); if pinfo['run'] != '/': import panelSite; siteObj = panelSite.panelSite(); mobj = obj(); mobj.id = find['id']; mobj.runPath = pinfo['run']; siteObj.SetSiteRunPath(mobj); #导入数据 self.WriteLogs(json.dumps({'name':'导入数据库','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['config']; 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) public.serviceReload(); self.depTotal(name); self.WriteLogs(json.dumps({'name':'准备部署','total':0,'used':0,'pre':0,'speed':0})); return public.returnMsg(True,pinfo);
sfObject.restrict_ignore = lambda self: self.filter( ignore=[".*25-pt-30.*",".*300-pt-400.*"] ) sfObject.restrict = lambda self: self.restrict_good().restrict_ignore() #################################### # Bottom Flavor Inputs and fits # Note: sources is used to do a systematic error x-check. # ttbar_pdf_7_all = files("ttbar_pdf/EM/JVF05/6PT_MV1c/*6bins.txt") \ .restrict() \ .filter(analyses = ["PDF_6bins_emu_2j", "PDF_6bins_emu_3j", \ "PDF_6bins_ll_2j", "PDF_6bins_ll_3j", \ ]) ttbar_pdf_7_2j = ttbar_pdf_7_all \ .filter(analyses = ["PDF_6bins_ll_2j", "PDF_6bins_emu_2j", \ ]) ttbar_pdf_7_3j = ttbar_pdf_7_all \ .filter(analyses = ["PDF_6bins_ll_3j", "PDF_6bins_emu_3j", \ ]) sources_7 = ttbar_pdf_7_all # The file "commonbinning.txt" just contains some empty specifications that have the binning. They don't contain
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(); for ext in pinfo['php_ext']: if ext == 'pathinfo': import config con = config.config(); get.version = php_version; get.type = 'on'; con.setPathInfo(get); else: get.name = ext get.version = php_version get.type = '1'; mfile.InstallSoft(get); #解禁PHP函数 if 'enable_functions' in pinfo: try: php_f = public.GetConfigValue('setup_path') + '/php/' + php_version + '/etc/php.ini' php_c = public.readFile(php_f) rep = "disable_functions\s*=\s{0,1}(.*)\n" tmp = re.search(rep,phpini).groups(); disable_functions = tmp[0].split(','); for fun in pinfo['enable_functions']: fun = fun.strip() if fun in disable_functions: disable_functions.remove(fun) disable_functions = ','.join(disable_functions) php_c = re.sub(rep, 'disable_functions = ' + disable_functions + "\n", php_c); public.writeFile(php_f,php_c) public.phpReload(php_version) except:pass #执行额外shell进行依赖安装 self.WriteLogs(json.dumps({'name':'Execute extra SHELL','total':0,'used':0,'pre':0,'speed':0})); if os.path.exists(path+'/install.sh'): os.system('cd '+path+' && bash ' + 'install.sh ' + find['name']); os.system('rm -f ' + path+'/install.sh') #是否执行Composer if os.path.exists(path + '/composer.json'): self.WriteLogs(json.dumps({'name':'Execute Composer','total':0,'used':0,'pre':0,'speed':0})); if not os.path.exists(path + '/composer.lock'): execPHP = '/www/server/php/' + php_version +'/bin/php'; if execPHP: if public.get_url().find('125.88'): os.system('cd ' +path+' && '+execPHP+' /usr/bin/composer config repo.packagist composer https://packagist.phpcomposer.com'); import panelSite; phpini = '/www/server/php/' + php_version + '/etc/php.ini' phpiniConf = public.readFile(phpini); phpiniConf = phpiniConf.replace('proc_open,proc_get_status,',''); public.writeFile(phpini,phpiniConf); os.system('nohup cd '+path+' && '+execPHP+' /usr/bin/composer install -vvv > /tmp/composer.log 2>&1 &'); #写伪静态 self.WriteLogs(json.dumps({'name':'Set URL rewrite','total':0,'used':0,'pre':0,'speed':0})); swfile = path + '/nginx.rewrite'; if os.path.exists(swfile): rewriteConf = public.readFile(swfile); dwfile = self.__panelPath + '/vhost/rewrite/' + site_name + '.conf'; public.writeFile(dwfile,rewriteConf); #删除伪静态文件 public.ExecShell("rm -f " + path + '/*.rewrite') #删除多余文件 rm_file = path + '/index.html' if os.path.exists(rm_file): rm_file_body = public.readFile(rm_file) if rm_file_body.find('panel-heading') != -1: os.remove(rm_file) #设置运行目录 self.WriteLogs(json.dumps({'name':'Set the run directory','total':0,'used':0,'pre':0,'speed':0})); if pinfo['run_path'] != '/': import panelSite; siteObj = panelSite.panelSite(); mobj = obj(); mobj.id = find['id']; mobj.runPath = pinfo['run_path']; siteObj.SetSiteRunPath(mobj); #导入数据 self.WriteLogs(json.dumps({'name':'Import database','total':0,'used':0,'pre':0,'speed':0})); if os.path.exists(path+'/import.sql'): databaseInfo = public.M('databases').where('pid=?',(find['id'],)).field('username,password').find(); if databaseInfo: os.system('/www/server/mysql/bin/mysql -u' + databaseInfo['username'] + ' -p' + databaseInfo['password'] + ' ' + databaseInfo['username'] + ' < ' + path + '/import.sql'); os.system('rm -f ' + path + '/import.sql'); siteConfigFile = (path + '/' + pinfo['db_config']).replace('//','/'); if os.path.exists(siteConfigFile): siteConfig = public.readFile(siteConfigFile) siteConfig = siteConfig.replace('BT_DB_USERNAME',databaseInfo['username']) siteConfig = siteConfig.replace('BT_DB_PASSWORD',databaseInfo['password']) siteConfig = siteConfig.replace('BT_DB_NAME',databaseInfo['username']) public.writeFile(siteConfigFile,siteConfig) #清理文件和目录 for f_path in pinfo['remove_file']: filename = (path + '/' + f_path).replace('//','/') if os.path.exists(filename): if not os.path.isdir(filename): if f_path.find('.user.ini') != -1: public.ExecShell("chattr -i " + filename) os.remove(filename) else: public.ExecShell("rm -rf " + filename) public.serviceReload(); if id: self.depTotal(id); self.WriteLogs(json.dumps({'name':'Ready to deploy','total':0,'used':0,'pre':0,'speed':0})); return public.returnMsg(True,pinfo);
def addDomainList(self, args): # 获取用户确认后的 site信息 # sites_data = self.getReadFile(self.SITE_ADD_FILE) # result = {} # result['size'] = len(sites_data); # # data = json.loads(args.domain_info) # for site in sites_data: # return {"status": "Success", "data":sites_data} data = json.loads(args.domain_info) site_file = self.SITE_ADD_FILE sites_data = self.getReadFile(site_file) successSize = [] failureSize = [] # # 获取前端表单数据 for site in sites_data: domain = site["domain"] second_domain = site["second_domain"] # if self.checkDomainExist(domain): # return {"status": "error", "msg": "试图添加的域名[" + domain + "]已经存在!"} # 构造创建网站必须的参数 site_obj = dict_obj() site_obj.webname = json.dumps({ "domain": domain, "domainlist": [second_domain], "count": 0 }) site_obj.path = data['path'] + domain site_obj.type = data['type'] site_obj.type_id = 0 site_obj.version = data['version'] site_obj.port = data['port'] site_obj.ps = "[" + domain + "] 一键部署" site_obj.codeing = "utf8" site_obj.ftp = "true" site_obj.ftp_username = site['ftp_username'] site_obj.ftp_password = site['ftp_password'] site_obj.sql = "true" site_obj.datauser = site['datauser'] site_obj.datapassword = site['datapassword'] #替换老数据库属性变量 site_obj.sqlConfigPath = data['sqlConfigPath'] site_obj.oldSqlName = data['oldSqlName'] site_obj.oldSqlUser = data['oldSqlUser'] site_obj.oldSqlPW = data['oldSqlPW'] zipPath = data["zip"] sqlPath = data['sqlPath'] domainPath = data['path'] + domain # 添加网站 psa = BT_SITE.AddSite(site_obj) if "siteStatus" in psa.keys(): successSize.append(psa.copy()) if "status" in psa.keys(): failureSize.append(psa.copy()) # 保存 建站日志到 本地 # resultSize.append(successSize) # resultSize.append(failureSize) # self.setWriteFile(successSize, self.PLUGIN_RESULT_LOG) # return {"status": "Success", "failureSize": failureSize} # 删除网站目录下的所有无用的文件 os.popen("cd " + domainPath + " && rm -rf *") # 解压文件 os.popen("cd " + self.BAG_PATH + " && unzip -o " + zipPath + " -d " + domainPath + "/") cmd = "" # 判断网站根目录下是否存在 index.php 文件 while not os.path.exists(domainPath + "/index.php"): for file in os.listdir(domainPath): if os.path.isdir(domainPath + "/" + file): # 将文件夹拷贝到上级文件夹 os.popen("mv " + domainPath + "/" + file + "/* " + domainPath) # 删除原文件 os.popen("cd " + domainPath + " && rm -rf " + file) self.replaceStr(site_obj) # 导入数据库 dataObj = dict_obj() dataObj.file = data['path'] + domain + sqlPath dataObj.name = site_obj.datauser BT_DATA.InputSql(dataObj) # 创建FTP # BTftp = ftp.ftp() FTP = dict_obj() FTP.ftp_username = site_obj.ftp_username FTP.ftp_password = site_obj.ftp_password # FTP.path = domainPath # FTP.ps = site_obj.ps # BTftp.AddUser(FTP) # 修改配置文件 # 构建PHP 的配置文件 PhpConfig = '''<?php #[数据库参数] $dbHost="127.0.0.1"; $dbName="%s"; $dbUser="******"; $dbPass="******"; #[数据表前缀] $TablePre="dev"; #[语言] $sLan="zh_cn"; #[网址] $SiteUrl="http://%s"; #----------------------------------# ?> ''' % (site_obj.datauser, site_obj.datauser, site_obj.datapassword, domain) # 写入站点 public.WriteFile(domainPath + "/config.inc.php", PhpConfig.encode("UTF-8")) # 删除原目录下的 install 文件夹 os.popen("rm -rf " + domainPath + "/base/install/") file = dict_obj() file.filename = domainPath file.user = "******" file.access = "755" file.all = "True" files.files().SetFileAccess(file) count = successSize + failureSize self.setWriteFile(successSize, self.PLUGIN_RESULT_LOG) return { "status": "Success", "site": { "count": len(count), "successSize": len(successSize), "failureSize": len(failureSize) } }
# define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') if __name__ == '__main__': #create objects from class obj_File = files() obj_Encryption = Encryption() state = True flag = True #print options menu print("\n\nEncrypt and decrypt text files using Caesar encryption.") while state: print( "\nSelect an option:\n\n\t1).- Encript text \n\t2).- Encrypt text \n\t3).-Exit" ) opt = int(input("Enter option: ")) if opt == 1: try: clear() fileName = input("File name: ")
def SaveRedirectFile(self, get): import files f = files.files() return f.SaveFileBody(get)
# # We are only looking at the following (a nice way to add a function onto an object!): # sfObject.restrict = lambda self: self.filter( taggers=taggers, ignore=ignore_analyses ) #################################### # Bottom Flavor Inputs and fits # Note: sources is used to do a systematic error x-check. # s8 = files("system8/*.txt") \ .restrict() ptrel = files("ptrel/*.txt") \ .restrict() ttbar_pdf_7_all = files ("ttbar_pdf/6bins/*.txt") \ .restrict() ttbar_pdf_10_all = files("ttbar_pdf/10bins/*.txt") \ .restrict() ttbar_kinfit = files("KinFit_ljet/*.txt") \ .restrict() ttbar_kinsel = files("KinSel_dilet/*.txt") \ .restrict()
taggers=taggers, jets=["AntiKt4TopoEMJVF0_5", "AntiKt4TopoLCJVF0_5", "AntiKt4TopoEMnoJVF", "AntiKt4TopoLCnoJVF","AntiKt2Track","AntiKt3Track"], ).verify_OPs("8TeV") sfObject.restrict_ignore = lambda self: self.filter( ignore=[".*25-pt-30.*",".*300-pt-400.*", ".*system8.*20-pt-30.*", ".*MV1-0.1340-AntiKt4TopoLCnoJVF.*", ".*MV1c-0.8353-AntiKt4TopoEMnoJVF.*", ".*0.1644-AntiKt4TopoEMnoJVF.*"] ) sfObject.restrict = lambda self: self.restrict_good().restrict_ignore() #################################### # Bottom Flavor Inputs and fits # Note: sources is used to do a systematic error x-check. # s8 = files("system8/*.txt") \ .restrict() # the topo are also known as the T&P ttbar analysis. ttdilep_topo = files("topo_ttemu/*.txt") \ .restrict() # PDF are from Giacinto, who can't keep the names straight, which makes for a mess here. ttbar_pdf_7_all = (files("ttbar_pdf/EM/*/*/*6bins.txt") + files("ttbar_pdf/LC/*/*/*7bins.txt")) \ .restrict() \ .filter(analyses = ["PDF_6bins_emu_2jets", "PDF_6bins_emu_3jets", \ "PDF_6bins_ll_2jets", "PDF_6bins_ll_3jets", \ ]) ttbar_pdf_7_2j = ttbar_pdf_7_all \ .filter(analyses = ["PDF_6bins_ll_2jets", "PDF_6bins_emu_2jets", \ ])
sfObject.restrict_tight = lambda self: self.restrict_good().restrict_ignore_tight() sfObject.restrict_trackjets = lambda self: self.restrict_good().restrict_ignore_trackjets() #################################### # Bottom Flavor Inputs and fits # Note: sources is used to do a systematic error x-check. # # Run-I PDF pre-recommendations # these are needed for the c-jet calibration since # we want the high-pT extrapolation to kick in at 200 GeV # for the b-jet calibration pre_ttbar_pdf_7_all = files("ttbar_pdf/pre/*6bins.txt") \ .restrict() \ .filter(analyses = ["pre_PDF_6bins_emu_2j", "pre_PDF_6bins_emu_3j", \ "pre_PDF_6bins_ll_2j", "pre_PDF_6bins_ll_3j"]) # Run-II PDF recommendations ttbar_pdf_7_all = (files("ttbar_pdf/*emu*7bins*.txt") + files("ttbar_pdf/*ll*7bins*.txt")) \ .restrict() \ .filter(analyses = ["PDF_6bins_emu_2j", "PDF_6bins_emu_3j", \ "PDF_6bins_ll_2j", "PDF_6bins_ll_3j"]) \ .filter(jets=["AntiKt4EMTopoJets"]) ttbar_pdf_7_2j = ttbar_pdf_7_all \ .filter(analyses = ["PDF_6bins_emu_2j", "PDF_6bins_ll_2j"]) ttbar_pdf_7_3j = ttbar_pdf_7_all \ .filter(analyses = ["PDF_6bins_emu_3j", "PDF_6bins_ll_3j"])
def test_get_path_md5(self): f = files.files('test.jpg') self.assertEqual(f.getPathFile(), '/app/img/041/test.jpg')
def _remove_old_website_file_to_trush(self, args): # 将原来目录移至回收站 files.files().DeleteDir(args)
def test_base_path(self): f = files.files('test.jpg') self.assertEqual(f.BASEPATH, '/app/img')
def check_root_path(self, rootPath): if not files.files().CheckDir(rootPath): return public.returnMsg(False, 'PATH_ERROR') return False
# adding a restrict function onto the default object. This is one of those # very cool things about how python works. sfObject.restrict = lambda self: self.filter( taggers=taggers, jets=["AntiKt4TopoEMJVF0_5", "AntiKt4TopoLCJVF0_5"], ignore=[".*25-pt-30.*",".*300-pt-400.*", ".*system8.*20-pt-30.*", ".*JetFitterCharm-.*AntiKt4TopoEM.*"] ) ############################### # Bottom inputs # top ttbar_pdf_7_all = files("ttbar_pdf/*/JVF05/*7bins.txt") \ .restrict() \ .filter(analyses =["ttbar_pdf_emu_2jets_7bins", "ttbar_pdf_emu_3jets_7bins", "ttbar_pdf_ll_2jets_7bins", "ttbar_pdf_ll_3jets_7bins", "PDF_dl_7bins_ll_2jets", "PDF_dl_7bins_ll_3jets", "PDF_dl_7bins_emu_2jets", "PDF_dl_7bins_emu_3jets"]) ttbar_pdf_7_2j = files("ttbar_pdf/*/JVF05/*7bins.txt") \ .restrict() \ .filter(analyses =["ttbar_pdf_emu_2jets_7bins", "ttbar_pdf_ll_2jets_7bins", "PDF_dl_7bins_ll_2jets", "PDF_dl_7bins_emu_2jets"]) ttbar_pdf_7_combined = ttbar_pdf_7_all.bbb_fit("ttbar_pdf_7_fit") ttbar_pdf_7_combined_2j = ttbar_pdf_7_2j.bbb_fit("ttbar_pdf_7_2j_fit") ttbar = ttbar_pdf_7_combined + ttbar_pdf_7_combined_2j sources = ttbar_pdf_7_all + ttbar_pdf_7_2j ###############################
# And the filtering of the taggers mentioned above is done by # adding a restrict function onto the default object. This is one of those # very cool things about how python works. sfObject.restrict = lambda self: self.filter( taggers=taggers, jets=["AntiKt4Topo"], ignore=[".*25-pt-30.*"] ) ############################### #### Bottom inputs # di-jet input - S8 s8 = files("system8/*.txt") \ .restrict() # di-jet input - pTrel ptrel = files ("ptrel/*txt") \ .restrict() # top input - kinematic selection in di-lepton channel ttbar_kinsel = files("ttbar_kinsel/*.txt") \ .restrict() ttbar_kinfit = files("KinFit_ljet/*.txt") \ .restrict() # top input - PDF with different final states and 6 bins ttbar_pdf_6_all = files("ttbar_pdf/6bins/*.txt") \ .restrict()
def get(self, name): f = files.files(name) return self.send(f.getSitePathFile())
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').find() path = find['path'] #获取包信息 pinfo = self.GetPackageInfo(name) if not pinfo: return public.returnMsg(False, '指定软件包不存在!') #检查本地包 self.WriteLogs( json.dumps({ 'name': '检查软件包', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) packageZip = self.__setupPath + '/package/' + name + '.zip' isDownload = False if os.path.exists(packageZip): md5str = self.GetFileMd5(packageZip) if md5str != pinfo['md5']: isDownload = True else: isDownload = True #下载文件 if isDownload: self.WriteLogs( json.dumps({ 'name': '下载文件', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) self.DownloadFile(pinfo['download'], packageZip) if not os.path.exists(packageZip): return public.returnMsg(False, '文件下载失败!') os.system('unzip -o ' + packageZip + ' -d ' + path + '/') #设置权限 self.WriteLogs( json.dumps({ 'name': '设置权限', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) os.system('chmod -R 755 ' + path) os.system('chown -R www.www ' + path) if pinfo['chmod'] != "": access = pinfo['chmod'].split(',') for chm in access: tmp = chm.split('|') if len(tmp) != 2: continue os.system('chmod -R ' + tmp[0] + ' ' + path + '/' + tmp[1]) #安装PHP扩展 self.WriteLogs( json.dumps({ 'name': '安装必要的PHP扩展', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if pinfo['ext'] != '': exts = pinfo['ext'].split(',') import files mfile = files.files() for ext in exts: 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) #执行额外shell进行依赖安装 self.WriteLogs( json.dumps({ 'name': '执行额外SHELL', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if os.path.exists(path + '/install.sh'): os.system('cd ' + path + ' && bash ' + 'install.sh') os.system('rm -f ' + path + '/install.sh') #是否执行Composer if os.path.exists(path + '/composer.json'): self.WriteLogs( json.dumps({ 'name': '执行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': '设置伪静态', '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) #设置运行目录 self.WriteLogs( json.dumps({ 'name': '设置运行目录', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) if pinfo['run'] != '/': import panelSite siteObj = panelSite.panelSite() mobj = obj() mobj.id = find['id'] mobj.runPath = pinfo['run'] siteObj.SetSiteRunPath(mobj) #导入数据 self.WriteLogs( json.dumps({ 'name': '导入数据库', '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['config'] 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) public.serviceReload() self.depTotal(name) self.WriteLogs( json.dumps({ 'name': '准备部署', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) return public.returnMsg(True, pinfo)
def ClearRecycle_Bin(): import files f = files.files(); f.Close_Recycle_bin(None);
import xlrd as xlrd try: import pandas as pd except: os.system( 'python3 -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas' ) import pandas as pd # 添加包引用位置并引用公共包 sys.path.append("class/") # 配置全局变量 BT_SITE = panelSite.panelSite() BT_DATA = database.database() BT_FILE = files.files() BT_DOMAIN_DATA = data.data() # 取通用对象 class dict_obj: def __contains__(self, key): return getattr(self, key, None) def __setitem__(self, key, value): setattr(self, key, value) def __getitem__(self, key): return getattr(self, key, None) def __delitem__(self, key):
def ClearRecycle_Bin(): import files f = files.files() f.Close_Recycle_bin(None)
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() if not 'path' in find: return public.returnMsg(False, '网站不存在!') path = find['path'] if path.replace('//', '/') == '/': return public.returnMsg(False, '危险的网站根目录!') #获取包信息 pinfo = self.GetPackageInfo(name) id = pinfo['id'] if not pinfo: return public.returnMsg(False, '指定软件包不存在!') #检查本地包 self.WriteLogs( json.dumps({ 'name': '正在校验软件包...', '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': '正在下载文件 ...', '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, '文件下载失败!' + packageZip) pinfo = self.set_temp_file(packageZip, path) if not pinfo: return public.returnMsg(False, '在安装包中找不到【宝塔自动部署配置文件】') #设置权限 self.WriteLogs( json.dumps({ 'name': '设置权限', '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': '安装必要的PHP扩展', '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': '执行额外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': '执行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': '设置伪静态', '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': '设置运行目录', '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': '导入数据库', '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': '准备部署', 'total': 0, 'used': 0, 'pre': 0, 'speed': 0 })) return public.returnMsg(True, pinfo)