def files_of_dir(f: paramiko.SFTPClient, remote_dir) -> list: all_file = [] file_list = f.listdir_attr(remote_dir) for file in file_list: file_name = remote_dir + "/" + file.filename if S_ISDIR(file.st_mode): all_file.extend(files_of_dir(f, file_name)) else: all_file.append(file_name) return all_file
def remove_files_from_directory(client: paramiko.SFTPClient, root): for i in client.listdir_attr(root): server_path = os.path.join(root, i.filename) if stat.S_ISDIR(i.st_mode): remove_files_from_directory(client, server_path) elif stat.S_ISREG(i.st_mode): client.remove(server_path) else: raise RuntimeError(f"Don't know what to do with {server_path}") print(f"Removed {server_path}") client.rmdir(root) print(f"Removed {root}")
def walk(client: paramiko.SFTPClient, dirpath: str, prefix: Optional[str] = None, sep: Optional[str] = '/') -> List[str]: """Recursively scan contents of a remote directory. Returns a list of tuples that contain the relative sub-directory path and the file name for all files. The sub-directory path for files in the ``dirpath`` is None. If ``dirpath`` does not reference a directory the result is None. Parameters ---------- client: paramiko.SFTPClient SFTP client. dirpath: string Path to a directory on the remote server. prefix: string, default=None Prefix path for the current (sub-)directory. sep: string, default='/' Path separator used by the remote file system. Returns ------- list of tuples of (string, string) """ result = list() try: for f in client.listdir_attr(dirpath): children = walk( client=client, dirpath=sep.join([dirpath, f.filename]), prefix=util.join(prefix, f.filename) if prefix else f.filename) if children is not None: # The file is a directory. result.extend(children) else: # Couldn't recursively explore the filename, i.e., it is not a # directory but a file. result.append( util.join(prefix, f.filename) if prefix else f.filename) except IOError: # An error is raised if the dirpath does not reference a valid # directory. return None return result