def show_file_info(self, flag=False, filepath='/'): filepath = self.abspath(filepath) info = self.cloud.get_file_info(filepath) color_format = '%s '+color.render_color('%-6s','purple')+' %9s '+color.render_color('%-s','blue') normal_format = '%s '+color.render_color('%-6s','green')+' %9s '+color.render_color('%-s','yellow') info_type = info['file-type'] info_name = ''.join(filepath.split('/')[-2:]) info_format = normal_format if filepath == '/': info_time = 'None' info_name = '/' else: info_time = datetime.fromtimestamp(int(info['file-date'])) if info['file-type'] == 'folder': info_type = '<dir>' info_format = color_format info_size = '' else: info_type = '<file>' info_size = self.readable(info['file-size']) if flag: print info_format % (info_time, info_type, info_size, info_name) else: print info_format[-14:] % (info_name)
def main(): cli = CLI(username='******',passwd='testtest',bucket='kehrspace',timeout=60,endpoint=upyun.ED_AUTO) try: cli.cmdloop() except KeyboardInterrupt: print color.render_color('\nWarning: operation was interrupted by user !') main() except SystemExit: pass
def __init__(self, prompt='>>> ',bucket=None, username=None, passwd=None, timeout=60, endpoint=upyun.ED_AUTO): cmd.Cmd.__init__(self) self.intro = manual.get_tips() self.doc_header=color.render_color('All commands you can use (type help <command> get more info):') self.undoc_header=color.render_color('All alias command:') self.prompt = color.render_color(prompt,'blue') self.init_upcloud(bucket, username, passwd, timeout, endpoint) self.current_local_workspace = os.path.abspath('.') self.sort_flag = 'name' self.reverse = False
def do_get(self, args): try: current_upyun_workspace = self.cloud.get_current_workspace() self.cmdline('get', args) except SystemExit: print 'Type "get -h" for help.' except OSError as e: print color.render_color('Error: ','error') , e finally: self.cloud.swith_workspace(current_upyun_workspace)
def main(): try: cmd_parser() except KeyboardInterrupt: print '\nexit !' except EOFError: print '\nexit !' except upyun.UpYunServiceException as e: print color.render_color('Server error:','error'),e.msg except upyun.UpYunClientException as e: print color.render_color('Client error:','error'),e.msg
def do_put(self, args): try: current_local_path = os.path.abspath('.') self.cmdline('put', args) except SystemExit: print 'Type "put -h" for help.' except OSError as e: print color.render_color('Error: ','error') , e finally: # 最后要回到程序的初始工作目录 os.chdir(current_local_path) # refresh the cache of current workspace self.cloud.get_file_list(self.cloud.get_current_workspace())
def put_local_files(self, source_list=[], destination='/', level=0): des_pre = destination for source_path in source_list: # 递归获取的文件列表是相对路径,这里需要再一次处理 path = os.path.abspath(source_path) if not os.path.exists(path): print color.render_color(path+':','error')+'file not exits !' else: if os.path.isdir(path): print color.render_color(path, 'blue')+':' self.put_dirs_count += 1 # enter sub dir os.chdir(path) file_list = os.listdir(path) self.put_local_files(file_list, des_pre, level) # return to parent dir (necessary!) os.chdir('..') else: print color.render_color('from: ','purple') + path path_list = path.split('/') path_list.pop(0) # remove the begain space if level >= len(path_list): level = len(path_list) - 1 destination = des_pre + '/'.join(path_list[level:]) print color.render_color('to: ','green') + destination self.cloud.upload(path,destination) self.put_files_count += 1
def get_upyun_files(self, source_list=[], destination='/tmp/', level=0): if not destination.endswith('/'): des_pre = destination + '/' else: des_pre = destination for source_path in source_list: path = self.abspath(source_path) check_file = self.check(path) if not check_file: print color.render_color(path+':','error')+'file not exits !' else: if check_file == 'folder': print color.render_color(path, 'blue')+':' self.get_dirs_count += 1 # enter sub dir self.cloud.swith_workspace(path) file_list = self.show_file_list(True,path) self.get_upyun_files(file_list, des_pre, level) # return to parent dir (necessary!) self.cloud.swith_workspace(self.abspath('..')) else: path = path[:-1] #去掉末尾的'/' print color.render_color('from: ','purple') + path path_list = path.split('/') path_list.pop(0) # remove the begain space if level >= len(path_list): level = len(path_list) - 1 destination = des_pre + '/'.join(path_list[level:]) print color.render_color('to: ','green') + destination self.cloud.download(path, destination) self.get_files_count += 1
def swith_workspace(self, path): if path.startswith('/') and path.endswith('/'): dir_info = self.cloud.getinfo(path) if dir_info['file-type'] != 'folder': import color print color.render_color('Error: ','error') + path[:-1]+' is not a directory !' return else: print 'The directory path is not absolute path.' return self.WORKSPACE = path # 在每次切换工作目录后,就对当前目录下的文件建立缓存。 # 不用每次都要联网获取当前目录下的文件信息,提高性能。 self.get_file_list(path)
def action_mkdir(self, args): for directory in args.path: directory = self.abspath(directory) if args.parents: print 'recursive create the directory: %s' % color.render_color(directory,'blue') dir_list = directory.split('/')[1:-1] # 先检查第一级目录 parent_dir = '/' + dir_list[0] + '/' file_type = self.check(parent_dir) if not file_type: self.cloud.mkdir(parent_dir) # 如果目录只有一级直接返回 if len(dir_list) == 1: continue for dir_name in dir_list[1:]: parent_dir += dir_name + '/' file_type = self.check(parent_dir) if not file_type: #文件不存在 self.cloud.mkdir(parent_dir) else: self.cloud.mkdir(directory) else: print 'All the files to create success!' # refresh current workspace cache self.cloud.get_file_list(self.cloud.get_current_workspace())
def parse_args(self): client_name = color.render_color('upcloud','green') client_des = color.render_color(' Remote terminal management client for UpYun !', 'yellow') self.parser = argparse.ArgumentParser(prog=client_name, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=client_des) self.parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__) self.parser.add_argument('-b', '--bucket', required=True, type=str, help='The name of your bucket') self.parser.add_argument('-u', '--username', required=True, type=str, help='The operator\'s name of this bucket') self.parser.add_argument('-p', '--passwd', action='store_true',required=True, help='The operator\'s password of this bucket') self.parser.add_argument('-t', '--timeout',default=60, type=int, help='The HTTP request timeout time') self.parser.add_argument('-e', '--endpoint',default='auto',choices=["auto","telecom","cnc","ctt"], help='The network access point') self.args = self.parser.parse_args()
def show_file_list(self, flag=False, path='/'): '''when flag is True or Flase,print long info or short info. when flag is None, return a name list of current workspace. ''' if self.cloud.get_current_workspace() == path: info_list = self.cloud.filelist else: info_list = self.cloud.get_file_list(path,False) dir_num = 0 file_num = 0 name_list = [] names = [] color_format = '%s '+color.render_color('%-6s','purple')+' %9s '+color.render_color('%-s','blue') normal_format = '%s '+color.render_color('%-6s','green')+' %9s '+color.render_color('%-s','yellow') # sort bye file name info_list = sorted(info_list, key=lambda info_list : info_list[self.sort_flag], reverse=self.reverse) for info in info_list: info_time = datetime.fromtimestamp(int(info['time'])) info_type = info['type'] info_size = self.readable(info['size']) info_name = info['name'] info_format = normal_format if info['type'] == 'F': info_type = '<dir>' dir_num += 1 info_format = color_format info_size = '' else: info_type = '<file>' file_num += 1 if flag: print info_format % (info_time, info_type, info_size, info_name) names.append(info_name) name_list.append({info_name:info_type}) name_dir_format = color.render_color('%s\n', 'blue') name_file_format = color.render_color('%s\n', 'yellow') if not flag: for name in name_list: file_name,file_type = name.popitem() name_format = name_dir_format if file_type == '<dir>' else name_file_format if flag != None: print name_format % file_name, print '' count_format = color.render_color('\n%d directories', 'purple') + ',' + color.render_color(' %d files', 'green') print count_format % (dir_num, file_num) return names
def do_shell(self, args): """Run shell command. command begain with '!'. \n""" command = args.split() # handle the empty line if not command: return if command[0] == 'cd': try: if len(command) == 1: os.chdir(self.current_local_workspace) else: os.chdir(os.path.abspath(command[1])) print os.path.abspath('.') except OSError as e: print color.render_color('Error: ','error') , e else: shell_cmd = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE) print shell_cmd.communicate()[0]
def recursive_rm(self,path): file_type = self.check(path) if not file_type: msg = 'file not exits !' self.show_error(msg) return else: print '\n','='*45 print color.render_color(path,'path')+': ' file_list = self.show_file_list(True,path) print 'removing '+color.render_color(path,'blue') +': ' for file_name in file_list: sub_path = path + file_name+'/' if self.check(sub_path) == 'folder': self.recursive_rm(sub_path) self.cloud.remove(sub_path) else: self.cloud.remove(sub_path) else: print 'sucess!'
def action_put(self, args): source_list = [] destination = self.abspath(args.destination) # 预先处理路径,解决使用 . 或 .. 时多返回一级目录的问题。 for path in args.source: if path == '*': path = '.' source_list.append(os.path.abspath(path)) level = args.level print 'level:',level self.put_files_count = 0 self.put_dirs_count = 0 self.put_local_files(source_list, destination, level) put_count_format = color.render_color('%s directories, ','purple') + color.render_color('%s files','green') if self.put_files_count == 0: print 'The upload folder is empty. Did not upload any file !' return print 'All files uploaded successfully! \n' + \ 'count: '+put_count_format % (self.put_dirs_count, self.put_files_count)
def action_get(self, args): source_list = args.source destination = os.path.abspath(args.destination) if not os.path.exists(destination): print color.render_color('Error: ','error') + 'The local folder does not exist !' flag = raw_input('Do you want to create it now?(y/n):') if flag == 'y': os.makedirs(destination) else: return level = args.level print 'level:',level self.get_files_count = 0 self.get_dirs_count = 0 self.get_upyun_files(source_list, destination, level) if self.get_files_count == 0: print 'The download folder is empty. Did not download any file !' return get_count_format = color.render_color('%s directories, ','purple') + color.render_color('%s files','green') print 'All files download successfully! \n' + \ 'count: '+get_count_format % (self.get_dirs_count, self.get_files_count)
def action_ls(self, args): if type(args.path) is str: path_list = [args.path] else: path_list = args.path # refresh the cache of current workspace if args.refresh: self.cloud.get_file_list(self.cloud.get_current_workspace()) self.sort_flag = args.sort self.reverse = args.reverse if '*' in path_list: path_list = self.show_file_list(None,self.cloud.get_current_workspace()) for path in path_list: path = self.abspath(path) if args.directory: if args.long: self.show_file_info(True, path) else: self.show_file_info(False, path) else: if args.long: if self.check(path) == 'folder': print color.render_color(path,'path')+':' self.show_file_list(True, path) else: self.show_file_info(True, path) else: if self.check(path) == 'folder': print color.render_color(path,'path')+':' self.show_file_list(False, path) else: self.show_file_info(False, path)
def show_error(self, msg=None, error='Error'): print color.render_color(error+': ','error')+msg