summaryrefslogtreecommitdiff
path: root/examples/chhostname.py
blob: bf174e619613742b8388bd9f5e735916dc040820 (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/python3
# Copyright 2024 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: GPL-3

"""Unshare a UTS (and user and mount) namespace and change the hostname."""

import os
import pathlib
import socket
import sys
import tempfile

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

import linuxnamespaces


def change_file(location: pathlib.Path, content: bytes | str) -> None:
    if isinstance(content, str):
        content = content.encode("ascii")
    try:
        st = location.stat()
    except FileNotFoundError as err:
        raise ValueError(
            f"cannot change non-existent file: {location!r}"
        ) from err
    if st.st_size == len(content) and location.read_bytes() == content:
        return
    with tempfile.NamedTemporaryFile() as tfile:
        tfile.write(content)
        # In Python >= 3.12, we should set delete_on_close=False rather than
        # closing the underlying file object behind tempfile's back.
        tfile.file.close()
        linuxnamespaces.bind_mount(tfile.name, location)


def main() -> None:
    hostname = sys.argv[1]
    linuxnamespaces.unshare_user_idmap(
        [linuxnamespaces.IDMapping.identity(os.getuid())],
        [linuxnamespaces.IDMapping.identity(os.getgid())],
        linuxnamespaces.CloneFlags.NEWUSER
        | linuxnamespaces.CloneFlags.NEWNS
        | linuxnamespaces.CloneFlags.NEWUTS,
    )
    socket.sethostname(hostname)
    etc = pathlib.Path("/etc")
    change_file(etc / "hostname", f"{hostname}\n")
    change_file(
        etc / "hosts",
        f"""127.0.0.1 {hostname} localhost
::1 {hostname} localhost
""",
    )
    os.execlp(os.environ["SHELL"], os.environ["SHELL"])


if __name__ == "__main__":
    main()