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.SSHPath(path, ssh=None)[source]

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() # doctest: +ELLIPSIS
SSHPath('...', ssh=ssh(user='travis', host='127.0.0.1'))
__bytes__()[source]

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

__eq__(other)[source]

x.__eq__(y) <==> x==y

__init__(path, ssh=None)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

__repr__() <==> repr(x)[source]
__str__()[source]

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

absolute()[source]

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 # doctest: +ELLIPSIS
'/.../absB/file'
as_posix()[source]

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

as_uri()[source]

Return the path as a ‘file’ URI.

chmod(mode)[source]

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()[source]

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()[source]

Expands a path that starts with a tilde

Example

>>> f = SSHPath('~/my-file', ssh=ssh_conn)
>>> f.path
'~/my-file'
>>> f.expanduser().path # doctest: +ELLIPSIS
'/home/.../my-file'
glob(pattern)[source]

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

group()[source]

Return the group name of the file gid.

is_absolute()[source]

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()[source]

Whether this path is a block device.

is_char_device()[source]

Whether this path is a character device.

is_dir()[source]

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()[source]

Whether this path is a FIFO.

is_file()[source]

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_reserved()[source]

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

is_socket()[source]

Whether this path is a socket.

Whether this path is a symbolic link.

iterdir()[source]

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)[source]

Combine this path with one or several arguments.

>>> f = SSHPath('hello', ssh=ssh_conn)
>>> f.joinpath('world').path
'hello/world'
lchmod(**kw)[source]

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

match(path_pattern)[source]

Return True if this path matches the given pattern.

mkdir(mode=511, parents=False, exist_ok=True)[source]

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)[source]

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                      # doctest: +ELLIPSIS
<paramiko.sftp_file.SFTPFile object at ...>
>>> fo.read('asdfasdf')     # doctest: +SKIP
b'Hello'
owner()[source]

Return the login name of the file owner.

read_bytes()[source]

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()[source]

Read text from the file at this path

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

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

rename(target)[source]

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)[source]

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)[source]

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 # doctest: +ELLIPSIS
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() # doctest: +ELLIPSIS
SSHPath('/.../resA/resB/file', ssh=ssh(user='...', host='127.0.0.1'))
rglob(pattern)[source]

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

rmdir()[source]

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)[source]

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()[source]

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 # doctest: +ELLIPSIS
'...664'

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()[source]

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

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

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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__[source]

list of weak references to the object (if defined)

home[source]

Returns the home directory for the SSH connection

>>> f = SSHPath('...', ssh=ssh_conn)
>>> f.home # doctest: +ELLIPSIS
SSHPath('/home/...', ssh=ssh(user='...', host='127.0.0.1'))
name[source]

Returns the name of the file.

>>> f = SSHPath('hello', ssh=ssh_conn)
>>> f.name
'hello'
parent[source]

Return the parent of this path

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

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']
parts[source]

Return the individual parts of the path

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

Returns the stem of a file without any extension

>>> f = SSHPath('hello.tar.gz', ssh=ssh_conn)
>>> f.stem
'hello'
suffix[source]

Returns the suffix of the file.

>>> f = SSHPath('hello.tar.gz', ssh=ssh_conn)
>>> f.suffix
'.gz'
suffixes[source]

Returns the suffixes of a file

>>> f = SSHPath('hello.tar.gz', ssh=ssh_conn)
>>> f.suffixes
'.tar.gz'
class pwnlib.filesystem.Path[source]

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.

_raw_open(flags, mode=511)[source]

Open the file pointed by this path and return a file descriptor, as os.open() does.

absolute()[source]

Return an absolute version of this path. This function works even if the path doesn’t point to anything.

No normalization is done, i.e. all ‘.’ and ‘..’ will be kept along. Use resolve() to get the canonical path to a file.

chmod(mode)[source]

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

classmethod cwd()[source]

Return a new path pointing to the current working directory (as returned by os.getcwd()).

exists()[source]

Whether this path exists.

expanduser()[source]

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

glob(pattern)[source]

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

group()[source]

Return the group name of the file gid.

classmethod home()[source]

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

is_block_device()[source]

Whether this path is a block device.

is_char_device()[source]

Whether this path is a character device.

is_dir()[source]

Whether this path is a directory.

is_fifo()[source]

Whether this path is a FIFO.

is_file()[source]

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()[source]

Check if this path is a POSIX mount point

is_socket()[source]

Whether this path is a socket.

Whether this path is a symbolic link.

iterdir()[source]

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

lchmod(mode)[source]

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

lstat()[source]

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

mkdir(mode=511, parents=False, exist_ok=False)[source]

Create a new directory at this given path.

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

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

owner()[source]

Return the login name of the file owner.

read_bytes()[source]

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

read_text(encoding=None, errors=None)[source]

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

rename(target)[source]

Rename this path to the given path.

replace(target)[source]

Rename this path to the given path, clobbering the existing destination if it exists.

resolve(strict=False)[source]

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).

rglob(pattern)[source]

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

rmdir()[source]

Remove this directory. The directory must be empty.

samefile(other_path)[source]

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

stat()[source]

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

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

touch(mode=438, exist_ok=True)[source]

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

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

write_bytes(data)[source]

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

write_text(data, encoding=None, errors=None)[source]

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