summaryrefslogtreecommitdiff
path: root/examples/netnsslirp.py
blob: 7a1a27ec7363da86f92f0ee74b9da3b002058fcb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/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 signal
import sys

if __file__.split("/")[-2:-1] == ["examples"]:
    sys.path.insert(0, "/".join(__file__.split("/")[:-2]))

import linuxnamespaces


def main() -> None:
    mainpid = os.getpid()
    if os.fork() == 0:
        linuxnamespaces.prctl_set_pdeathsig(signal.SIGTERM)
        os.execlp(
            "slirp4netns",
            "slirp4netns",
            "--configure",
            "--disable-host-loopback",
            "%d" % mainpid,
            "host0",
        )

    linuxnamespaces.unshare_user_idmap_nohelper(
        0,
        0,
        linuxnamespaces.CloneFlags.NEWUSER | linuxnamespaces.CloneFlags.NEWNET,
    )
    os.execlp(os.environ["SHELL"], os.environ["SHELL"])


if __name__ == "__main__":
    main()