diff options
author | Helmut Grohne <helmut@subdivi.de> | 2024-04-04 11:03:12 +0200 |
---|---|---|
committer | Helmut Grohne <helmut@subdivi.de> | 2024-04-04 11:03:12 +0200 |
commit | ccc087a1fe4447ed44d32d1a4ae61f4cf266c5a6 (patch) | |
tree | 407602beaa636bc7c465d6b6ab0206ede468669d | |
parent | 1e5ad493fee821f7f96423c03b436da15a4efe60 (diff) | |
download | python-linuxnamespaces-ccc087a1fe4447ed44d32d1a4ae61f4cf266c5a6.tar.gz |
add an example for unsharing a PID namespace
-rwxr-xr-x | examples/pidns.py | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/examples/pidns.py b/examples/pidns.py new file mode 100755 index 0000000..d926d87 --- /dev/null +++ b/examples/pidns.py @@ -0,0 +1,39 @@ +#!/usr/bin/python3 +# Copyright 2024 Helmut Grohne <helmut@subdivi.de> +# SPDX-License-Identifier: GPL-3 + +"""Create a pid namespace and provide a matching /proc view. As a consequence, +user and mount namespaces will be unshared as well. + +This is similar to unshare --user --pid --mount-proc. +""" + +import os +import signal +import sys + +if __file__.split("/")[-2:-1] == ["examples"]: + sys.path.insert(0, "/".join(__file__.split("/")[:-2])) + +import linuxnamespaces + + +def main() -> None: + namespaces = ( + linuxnamespaces.CloneFlags.NEWUSER + | linuxnamespaces.CloneFlags.NEWNS + | linuxnamespaces.CloneFlags.NEWPID + ) + linuxnamespaces.unshare_user_idmap_nohelper(0, 0, namespaces) + pid = os.fork() + if pid == 0: + linuxnamespaces.prctl_set_pdeathsig(signal.SIGTERM) + linuxnamespaces.populate_proc("/", "/", namespaces) + os.execlp(os.environ["SHELL"], os.environ["SHELL"]) + else: + _, status = os.waitpid(pid, 0) + sys.exit(os.waitstatus_to_exitcode(status)) + + +if __name__ == "__main__": + main() |