# `pwnlib.filesystem` — Manipulating Files Locally and Over SSH

Provides a Python2-compatible `pathlib` interface for paths on the local filesystem (.Path) as well as on remote filesystems, via SSH (.SSHPath).

Handles file abstraction for local vs. remote (via ssh)

class pwnlib.filesystem.Path(*args, **kwargs)

  PurePath subclass that can make system calls.

  Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

  __init__(*args, **kwargs)
  static __new__(cls, *args, **kwargs)
  absolute()

    Return an absolute version of this path No normalization or symlink resolution is performed.

    Use resolve() to resolve symlinks and remove ‘..’ segments.

  as_uri()

    Return the path as a URI.

  chmod(mode, *, follow_symlinks=True)

    Change the permissions of the path, like os.chmod().

  expanduser()

    Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

  classmethod from_uri(uri)

    Return a new path from the given ‘file’ URI.

  glob(pattern, *, case_sensitive=None, recurse_symlinks=False)

    Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

  group(*, follow_symlinks=True)

    Return the group name of the file gid.

  hardlink_to(target)

    Make this path a hard link pointing to the same file as target.

    Note the order of arguments (self, target) is the reverse of os.link’s.

  is_junction()

    Whether this path is a junction.

  is_mount()

    Check if this path is a mount point

  iterdir()

    Yield path objects of the directory contents.

    The children are yielded in arbitrary order, and the special entries ‘.’ and ‘..’ are not included.

  mkdir(mode=511, parents=False, exist_ok=False)

    Create a new directory at this given path.

  open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

    Open the file pointed to by this path and return a file object, as the built-in open() function does.

  owner(*, follow_symlinks=True)

    Return the login name of the file owner.

  read_text(encoding=None, errors=None, newline=None)

    Open the file in text mode, read it, and close the file.

  readlink()

    Return the path to which the symbolic link points.

  rename(target)

    Rename this path to the target path.

    The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

    Returns the new Path instance pointing to the target path.

  replace(target)

    Rename this path to the target path, overwriting if that path exists.

    The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

    Returns the new Path instance pointing to the target path.

  resolve(strict=False)

    Make the path absolute, resolving all symlinks on the way and also normalizing it.

  rglob(pattern, *, case_sensitive=None, recurse_symlinks=False)

    Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

  rmdir()

    Remove this directory. The directory must be empty.

  stat(*, follow_symlinks=True)

    Return the result of the stat() system call on this path, like os.stat() does.

  symlink_to(target, target_is_directory=False)

    Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

  touch(mode=438, exist_ok=True)

    Create this file with the given access mode, if it doesn’t exist.

  unlink(missing_ok=False)

    Remove this file or link. If the path is a directory, use rmdir() instead.

  walk(top_down=True, on_error=None, follow_symlinks=False)

    Walk the directory tree from this directory, similar to os.walk().

  write_text(data, encoding=None, errors=None, newline=None)

    Open the file in text mode, write to it, and close the file.

class pwnlib.filesystem.SSHPath(*args, **kwargs)

  Represents a file that exists on a remote filesystem.

  See `ssh` for more information on how to set up an SSH connection. See `pathlib.Path` for documentation on what members and properties this object has.

  Parameters:

    - name (str) – Name of the file

    - ssh (ssh) – `ssh` object for manipulating remote files

  Note

  You can avoid having to supply `ssh=` on every `SSHPath` by setting `context.ssh_session`. In these examples we provide `ssh=` for clarity.

  Examples

  First, create an SSH connection to the server.

      >>> ssh_conn = ssh('travis', 'example.pwnme')

  Let’s use a temporary directory for our tests

      >>> _ = ssh_conn.set_working_directory()

  Next, you can create SSHPath objects to represent the paths to files on the remote system.

      >>> f = SSHPath('filename', ssh=ssh_conn)
      >>> f.touch()
      >>> f.exists()
      True
      >>> f.resolve().path # doctests: +ELLIPSIS
      '/tmp/.../filename'
      >>> f.write_text('asdf ❤️')
      >>> f.read_bytes()
      b'asdf \xe2\x9d\xa4\xef\xb8\x8f'

  `context.ssh_session` must be set to use the `SSHPath.mktemp()` or `SSHPath.mkdtemp()` methods.

      >>> context.ssh_session = ssh_conn
      >>> SSHPath.mktemp()
      SSHPath('...', ssh=ssh(user='travis', host='127.0.0.1'))

  __bytes__()

    Return the bytes representation of the path. This is only recommended to use under Unix.

  __eq__(other)

    Return self==value.

  __init__(path, ssh=None)
  __repr__()

    Return repr(self).

  __str__()

    Return the string representation of the path, suitable for passing to system calls.

  absolute()

    Return the absolute path to a file, preserving e.g. “../”. The current working directory is determined via the `ssh` member `ssh.cwd`.

    Example

        >>> f = SSHPath('absA/../absB/file', ssh=ssh_conn)
        >>> f.absolute().path
        '/.../absB/file'

  as_posix()

    Return the string representation of the path with forward (/) slashes.

  as_uri()

    Return the path as a URI.

  chmod(mode)

    Change the permissions of a file

        >>> f = SSHPath('chmod_me', ssh=ssh_conn)
        >>> f.touch() # E
        >>> '0o%o' % f.stat().st_mode
        '0o100664'
        >>> f.chmod(0o777)
        >>> '0o%o' % f.stat().st_mode
        '0o100777'

  exists()

    Returns True if the path exists

    Example

        >>> a = SSHPath('exists', ssh=ssh_conn)
        >>> a.exists()
        False
        >>> a.touch()
        >>> a.exists()
        True
        >>> a.unlink()
        >>> a.exists()
        False

  expanduser()

    Expands a path that starts with a tilde

    Example

        >>> f = SSHPath('~/my-file', ssh=ssh_conn)
        >>> f.path
        '~/my-file'
        >>> f.expanduser().path
        '/home/.../my-file'

  glob(pattern)

    Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

  group()

    Return the group name of the file gid.

  is_absolute()

    Returns whether a path is absolute or not.

        >>> f = SSHPath('hello/world/file.txt', ssh=ssh_conn)
        >>> f.is_absolute()
        False

        >>> f = SSHPath('/hello/world/file.txt', ssh=ssh_conn)
        >>> f.is_absolute()
        True

  is_block_device()

    Whether this path is a block device.

  is_char_device()

    Whether this path is a character device.

  is_dir()

    Returns True if the path exists and is a directory

    Example

        >>> f = SSHPath('is_dir', ssh=ssh_conn)
        >>> f.is_dir()
        False
        >>> f.touch()
        >>> f.is_dir()
        False
        >>> f.unlink()
        >>> f.mkdir()
        >>> f.is_dir()
        True

  is_fifo()

    Whether this path is a FIFO.

  is_file()

    Returns True if the path exists and is a file

    Example

        >>> f = SSHPath('is_file', ssh=ssh_conn)
        >>> f.is_file()
        False
        >>> f.touch()
        >>> f.is_file()
        True
        >>> f.unlink()
        >>> f.mkdir()
        >>> f.is_file()
        False

  is_relative_to(*other)

    Return True if the path is relative to another path or False.

  is_reserved()

    Return True if the path contains one of the special names reserved by the system, if any.

  is_socket()

    Whether this path is a socket.

  is_symlink()

    Whether this path is a symbolic link.

  iterdir()

    Iterates over the contents of the directory

        >>> directory = SSHPath('iterdir', ssh=ssh_conn)
        >>> directory.mkdir()
        >>> fileA = directory.joinpath('fileA')
        >>> fileA.touch()
        >>> fileB = directory.joinpath('fileB')
        >>> fileB.touch()
        >>> dirC = directory.joinpath('dirC')
        >>> dirC.mkdir()
        >>> [p.name for p in directory.iterdir()]
        ['dirC', 'fileA', 'fileB']

  joinpath(*args)

    Combine this path with one or several arguments.

        >>> f = SSHPath('hello', ssh=ssh_conn)
        >>> f.joinpath('world').path
        'hello/world'

  lchmod(**kw)

    Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

  match(path_pattern)

    Return True if this path matches the given pattern. If the pattern is relative, matching is done from the right; otherwise, the entire path is matched. The recursive wildcard ‘**’ is not supported by this method.

  mkdir(mode=511, parents=False, exist_ok=True)

    Make a directory at the specified path

        >>> f = SSHPath('dirname', ssh=ssh_conn)
        >>> f.mkdir()
        >>> f.exists()
        True

        >>> f = SSHPath('dirA/dirB/dirC', ssh=ssh_conn)
        >>> f.mkdir(parents=True)
        >>> ssh_conn.run(['ls', '-la', f.absolute().path], env={'LC_ALL': 'C.UTF-8'}).recvline()
        b'total 8\n'

  open(*a, **kw)

    Return a file-like object for this path.

    This currently seems to be broken in Paramiko.

        >>> f = SSHPath('filename', ssh=ssh_conn)
        >>> f.write_text('Hello')
        >>> fo = f.open(mode='r+')
        >>> fo
        <paramiko.sftp_file.SFTPFile object at ...>
        >>> fo.read('asdfasdf')
        b'Hello'

  owner()

    Return the login name of the file owner.

  read_bytes()

    Read bytes from the file at this path

        >>> f = SSHPath('/etc/passwd', ssh=ssh_conn)
        >>> f.read_bytes()[:10]
        b'root:x:0:0'

  read_text()

    Read text from the file at this path

        >>> f = SSHPath('/etc/passwd', ssh=ssh_conn)
        >>> f.read_text()[:10]
        'root:x:0:0'

  readlink()

    Return the path to which the symbolic link points.

  relative_to(*other)

    Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not related to the other path), raise ValueError.

    The walk_up parameter controls whether .. may be used to resolve the path.

  rename(target)

    Rename a file to the target path

    Example

        >>> a = SSHPath('rename_from', ssh=ssh_conn)
        >>> b = SSHPath('rename_to', ssh=ssh_conn)
        >>> a.touch()
        >>> b.exists()
        False
        >>> a.rename(b)
        >>> b.exists()
        True

  replace(target)

    Replace target file with file at this path

    Example

        >>> a = SSHPath('rename_from', ssh=ssh_conn)
        >>> a.write_text('A')
        >>> b = SSHPath('rename_to', ssh=ssh_conn)
        >>> b.write_text('B')
        >>> a.replace(b)
        >>> b.read_text()
        'A'

  resolve(strict=False)

    Return the absolute path to a file, resolving any ‘..’ or symlinks. The current working directory is determined via the `ssh` member `ssh.cwd`.

    Note

    The file must exist to call resolve().

    Examples

        >>> f = SSHPath('resA/resB/../resB/file', ssh=ssh_conn)

        >>> f.resolve().path
        Traceback (most recent call last):
        ...
        ValueError: Could not normalize path: '/.../resA/resB/file'

        >>> f.parent.absolute().mkdir(parents=True)
        >>> list(f.parent.iterdir())
        []

        >>> f.touch()
        >>> f.resolve()
        SSHPath('/.../resA/resB/file', ssh=ssh(user='...', host='127.0.0.1'))

  rglob(pattern)

    Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

  rmdir()

    Remove an existing directory.

    Example

        >>> f = SSHPath('rmdir_me', ssh=ssh_conn)
        >>> f.mkdir()
        >>> f.is_dir()
        True
        >>> f.rmdir()
        >>> f.exists()
        False

  samefile(other_path)

    Returns whether two files are the same

        >>> a = SSHPath('a', ssh=ssh_conn)
        >>> A = SSHPath('a', ssh=ssh_conn)
        >>> x = SSHPath('x', ssh=ssh_conn)

        >>> a.samefile(A)
        True
        >>> a.samefile(x)
        False

  stat()

    Returns the permissions and other information about the file

        >>> f = SSHPath('filename', ssh=ssh_conn)
        >>> f.touch()
        >>> stat = f.stat()
        >>> stat.st_size
        0
        >>> '%o' % stat.st_mode
        '...664'

  symlink_to(target)

    Create a symlink at this path to the provided target

    Example

        >>> a = SSHPath('link_name', ssh=ssh_conn)
        >>> b = SSHPath('link_target', ssh=ssh_conn)
        >>> a.symlink_to(b)
        >>> a.write_text("Hello")
        >>> b.read_text()
        'Hello'

  touch()

    Touch a file (i.e. make it exist)

        >>> f = SSHPath('touchme', ssh=ssh_conn)
        >>> f.exists()
        False
        >>> f.touch()
        >>> f.exists()
        True

  unlink(missing_ok=False)

    Remove an existing file.

    Example

        >>> f = SSHPath('unlink_me', ssh=ssh_conn)
        >>> f.exists()
        False
        >>> f.touch()
        >>> f.exists()
        True
        >>> f.unlink()
        >>> f.exists()
        False

    Note that unlink only works on files.

        >>> f.mkdir()
        >>> f.unlink()
        Traceback (most recent call last):
        ...
        ValueError: Cannot unlink SSHPath(...)): is not a file

  with_name(name)

    Return a new path with the file name changed

        >>> f = SSHPath('hello/world', ssh=ssh_conn)
        >>> f.path
        'hello/world'
        >>> f.with_name('asdf').path
        'hello/asdf'

  with_stem(name)

    Return a new path with the stem changed.

        >>> f = SSHPath('hello/world.tar.gz', ssh=ssh_conn)
        >>> f.with_stem('asdf').path
        'hello/asdf.tar.gz'

  with_suffix(suffix)

    Return a new path with the file suffix changed

        >>> f = SSHPath('hello/world.tar.gz', ssh=ssh_conn)
        >>> f.with_suffix('.tgz').path
        'hello/world.tgz'

  write_bytes(data)

    Write bytes to the file at this path

        >>> f = SSHPath('somefile', ssh=ssh_conn)
        >>> f.write_bytes(b'\x00HELLO\x00')
        >>> f.read_bytes()
        b'\x00HELLO\x00'

  write_text(data)

    Write text to the file at this path

        >>> f = SSHPath('somefile', ssh=ssh_conn)
        >>> f.write_text("HELLO 😭")
        >>> f.read_bytes()
        b'HELLO \xf0\x9f\x98\xad'
        >>> f.read_text()
        'HELLO 😭'

  __weakref__

    list of weak references to the object

  property anchor

    The concatenation of the drive and root, or ‘’.

  property cwd

    Return a new path pointing to the current working directory.

  property home

    Returns the home directory for the SSH connection

        >>> f = SSHPath('...', ssh=ssh_conn)
        >>> f.home
        SSHPath('/home/...', ssh=ssh(user='...', host='127.0.0.1'))

  property name

    Returns the name of the file.

        >>> f = SSHPath('hello', ssh=ssh_conn)
        >>> f.name
        'hello'

  property parent

    Return the parent of this path

        >>> f = SSHPath('hello/world/file.txt', ssh=ssh_conn)
        >>> f.parent.path
        'hello/world'

  property parents

    Return the parents of this path, as individual parts

        >>> f = SSHPath('hello/world/file.txt', ssh=ssh_conn)
        >>> list(p.path for p in f.parents)
        ['hello', 'world']

  property parts

    Return the individual parts of the path

        >>> f = SSHPath('hello/world.tar.gz', ssh=ssh_conn)
        >>> f.parts
        ['hello', 'world.tar.gz']

  property stem

    Returns the stem of a file without any extension

        >>> f = SSHPath('hello.tar.gz', ssh=ssh_conn)
        >>> f.stem
        'hello'

  property suffix

    Returns the suffix of the file.

        >>> f = SSHPath('hello.tar.gz', ssh=ssh_conn)
        >>> f.suffix
        '.gz'

  property suffixes

    Returns the suffixes of a file

        >>> f = SSHPath('hello.tar.gz', ssh=ssh_conn)
        >>> f.suffixes
        '.tar.gz'