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)[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.
Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object.
- static __new__(cls, *args, **kwargs)[source]
Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object.
- absolute()[source]
Return an absolute version of this path by prepending the current working directory. No normalization or symlink resolution is performed.
Use resolve() to get the canonical path to a file.
- exists(*, follow_symlinks=True)[source]
Whether this path exists.
This method normally follows symlinks; to check whether a symlink exists, add the argument follow_symlinks=False.
- expanduser()[source]
Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)
- glob(pattern, *, case_sensitive=None)[source]
Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.
- hardlink_to(target)[source]
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.
- classmethod home()[source]
Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).
- is_file()[source]
Whether this path is a regular file (also True for symlinks pointing to regular files).
- iterdir()[source]
Yield path objects of the directory contents.
The children are yielded in arbitrary order, and the special entries ‘.’ and ‘..’ are not included.
- 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.
- 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.
- 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 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)[source]
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)[source]
Make the path absolute, resolving all symlinks on the way and also normalizing it.
- rglob(pattern, *, case_sensitive=None)[source]
Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.
- samefile(other_path)[source]
Return whether other_path is the same or not as this file (as returned by os.path.samefile()).
- stat(*, follow_symlinks=True)[source]
Return the result of the stat() system call on this path, like os.stat() does.
- symlink_to(target, target_is_directory=False)[source]
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)[source]
Create this file with the given access mode, if it doesn’t exist.
- unlink(missing_ok=False)[source]
Remove this file or link. If the path is a directory, use rmdir() instead.
- class pwnlib.filesystem.SSHPath(*args, **kwargs)[source]
Represents a file that exists on a remote filesystem.
See
ssh
for more information on how to set up an SSH connection. Seepathlib.Path
for documentation on what members and properties this object has.Note
You can avoid having to supply
ssh=
on everySSHPath
by settingcontext.ssh_session
. In these examples we providessh=
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 theSSHPath.mktemp()
orSSHPath.mkdtemp()
methods.>>> context.ssh_session = ssh_conn >>> SSHPath.mktemp() SSHPath('...', ssh=ssh(user='travis', host='127.0.0.1'))
Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object.
- __bytes__()[source]
Return the bytes representation of the path. This is only recommended to use under Unix.
- __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
memberssh.cwd
.Example
>>> f = SSHPath('absA/../absB/file', ssh=ssh_conn) >>> f.absolute().path '/.../absB/file'
- 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 '/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.
- 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_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_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.
- 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.
- 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 <paramiko.sftp_file.SFTPFile object at ...> >>> fo.read('asdfasdf') b'Hello'
- 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 related to the other path), raise ValueError.
The walk_up parameter controls whether .. may be used to resolve the path.
- 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
memberssh.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)[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 '...664'
- symlink_to(target)[source]
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
- unlink(missing_ok=False)[source]
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 😭'
- property home[source]
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[source]
Returns the name of the file.
>>> f = SSHPath('hello', ssh=ssh_conn) >>> f.name 'hello'
- property parent[source]
Return the parent of this path
>>> f = SSHPath('hello/world/file.txt', ssh=ssh_conn) >>> f.parent.path 'hello/world'
- property 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']
- property parts[source]
Return the individual parts of the path
>>> f = SSHPath('hello/world.tar.gz', ssh=ssh_conn) >>> f.parts ['hello', 'world.tar.gz']
- property stem[source]
Returns the stem of a file without any extension
>>> f = SSHPath('hello.tar.gz', ssh=ssh_conn) >>> f.stem 'hello'