Hostname

class rmote.tools.hostname.Hostname[source]

Bases: Tool

Manage system hostname and /etc/hosts entries. Requires root for mutating operations.

get and hosts_entry work on any POSIX target. set writes the kernel interface /proc/sys/kernel/hostname and therefore needs Linux; on another system it refuses with NotImplementedError.

Change the hostname in a disposable container with its own UTS namespace:

>>> from rmote.tools import FileSystem
>>> remote = getfixture("debian_tool")
>>> remote(Hostname.set, "rmote-example")
True
>>> remote(Hostname.set, "rmote-example")
False
>>> remote(Hostname.get)
'rmote-example'
>>> remote(FileSystem.read_str, "/etc/hostname").strip()
'rmote-example'
>>> remote(Hostname.hosts_entry, "192.0.2.1", "web")
True
>>> remote(Hostname.hosts_entry, "192.0.2.1", "web")
False
static get()[source]

Return the current running hostname.

socket.gethostname reads the live value of the kernel, which is what /etc/hostname configures but does not necessarily hold. It answers on every target, so this method needs no Linux.

Return type:

Text

Returns:

The hostname string.

static hosts_entry(ip, *names)[source]

Ensure /etc/hosts has an entry mapping ip to names.

If a line for ip already exists with exactly the same hostnames (in the same order), this is a no-op. If it exists with different hostnames, the line is replaced in-place. If no line exists for ip, one is appended.

Comment lines and blank lines are left untouched.

Parameters:
  • ip (Text) – The IP address for the entry (IPv4 or IPv6).

  • *names (Text) – One or more hostnames to associate with ip.

Return type:

bool

Returns:

True if /etc/hosts was modified.

Raises:

ValueError – If no names are provided.

static set(name)[source]

Set the system hostname idempotently.

Applies the change immediately by writing to /proc/sys/kernel/hostname and persists it to /etc/hostname. No external commands are required.

Parameters:

name (Text) – The desired hostname.

Return type:

bool

Returns:

True if the hostname was changed, False if it was already set to name.

Raises:

NotImplementedError – The target is not Linux, so it has no /proc/sys/kernel/hostname to write.