- 1 year ago
Set hostname with Python
Comment
1 / 1
To set the hostname using Python, you can use the socket
module. Here's an example:
pythonimport socket
def set_hostname(new_hostname):
try:
# Set the hostname
socket.sethostname(new_hostname)
print(f"Hostname set to: {new_hostname}")
except OSError as e:
print(f"Failed to set hostname: {e}")
# Usage
new_hostname = "my-new-hostname"
set_hostname(new_hostname)
In this example, the set_hostname
function takes the new hostname as an argument and uses the socket.sethostname()
function to set the hostname. If there is any error in setting the hostname, an OSError
exception will be raised and caught, and an error message will be printed.
Make sure to run this code with administrative privileges as changing the hostname typically requires administrative rights.