Change Hostname
Description
The change_hostname function changes the system's hostname. It validates the new hostname, updates the necessary system files (/etc/hostname and /etc/hosts), and applies the hostname change immediately. A system reboot is recommended for all changes to fully take effect.
Function Signature:
def change_hostname(new_hostname: str):
Parameters
- new_hostname (
str): The new hostname to assign to the system.
Returns
- None
Example Usage
change_hostname('new-hostname')
Notes
- The hostname must be alphanumeric and no longer than 63 characters. If it does not meet these criteria, a
ValueErrorwill be raised. - The
/etc/hostnamefile is updated with the new hostname. - The
/etc/hostsfile is modified to update the loopback address (127.0.1.1) with the new hostname. - The hostname change is applied immediately using the
hostnamecommand. However, a system reboot is required for all changes to fully take effect.
Error Handling
- If the new hostname is invalid (non-alphanumeric or too long), a
ValueErrorwill be raised. - If any error occurs during the process of changing the hostname, the exception is caught and an error message is printed.