diff options
author | Helmut Grohne <helmut@subdivi.de> | 2024-01-19 13:09:28 +0100 |
---|---|---|
committer | Helmut Grohne <helmut@subdivi.de> | 2024-01-19 13:09:28 +0100 |
commit | ec0be44f5e34ed76f7f6f2eeb530682f2b096212 (patch) | |
tree | 7fcf69f8f7d32513bd29eeb72aa445b01825521b /examples | |
parent | 119d04f017c39307280bb88fcdeaaf6f31ee9c9d (diff) | |
download | python-linuxnamespaces-ec0be44f5e34ed76f7f6f2eeb530682f2b096212.tar.gz |
add example for a network namespace with slirp4netns
Diffstat (limited to 'examples')
-rwxr-xr-x | examples/netnsslirp.py | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/examples/netnsslirp.py b/examples/netnsslirp.py new file mode 100755 index 0000000..0818fba --- /dev/null +++ b/examples/netnsslirp.py @@ -0,0 +1,45 @@ +#!/usr/bin/python3 +# Copyright 2024 Helmut Grohne <helmut@subdivi.de> +# SPDX-License-Identifier: GPL-3 + +"""Construct a network namespace with a host0 interface backed by slirp4netns. +""" + +import os +import sys + +if __file__.split("/")[-2:-1] == ["examples"]: + sys.path.insert(0, "/".join(__file__.split("/")[:-2])) + +import linuxnamespaces + + +def main() -> None: + mainpid = os.getpid() + rfd, wfd = os.pipe() + if os.fork() == 0: + os.set_inheritable(rfd, True) + os.execlp( + "slirp4netns", + "slirp4netns", + "--exit-fd", + "%d" % rfd, + "--configure", + "--disable-host-loopback", + "%d" % mainpid, + "host0", + ) + + linuxnamespaces.unshare_user_idmap_nohelper( + 0, + 0, + linuxnamespaces.CloneFlags.NEWUSER | linuxnamespaces.CloneFlags.NEWNET, + ) + # Leave write end of --exit-fd behind as fd 252. + os.dup2(wfd, 252) + os.close(wfd) + os.execlp(os.environ["SHELL"], os.environ["SHELL"]) + + +if __name__ == "__main__": + main() |