24
loading...
This website collects cookies to deliver better user experience
gethostname()
, using which we can easily find the hostname of a given machine. gethostname()
doesn’t accept any parameters, but it returns the current hostname of the machine in string format.# import the socket module in Python
import socket
# Print the hostname of the given system using gethostname() method
print("The hostname of the current system is ",socket.gethostname())
The hostname of the current system is ItsMyCode
platform.node()
function doesn’t accept any parameters, but it returns the current hostname of the machine in string format.# import the platform module in Python
import platform
# Print the hostname of the given system using platform.node() method
print("The hostname of the current system is ",platform.node())
The hostname of the current system is ItsMyCode
# import the os module in Python
import os
# Print the current system details using os.uname() method
print("The current system details are is ", os.uname())
# Print the hostname of the given system using os.uname() method
print("The current system's hostname is ", os.uname()[1])
('The current system details are is ', ('Linux', 'd5624dfa0f42', '3.10.0-1160.25.1.el7.x86_64', '#1 SMP Wed Apr 28 21:49:45 UTC 2021', 'x86_64'))
('The current system hostname is ', 'd5624dfa0f42')
os.uname()
method is supported in only a few operating systems, and if you get AttributeError: module ‘os’ has no attribute ‘uname’, ** then try the below approach **os.getenv()
# import the os module in Python
import os
# Print the hostname of the given system using os.getenv() method
print("The hostname of the current system is ",os.getenv('COMPUTERNAME', 'defaultValue'))
The hostname of the current system is ItsMyCode
os.getenv('HOSTNAME')
don’t always work in cron jobs as WSDL, HTTP HOSTNAME isn’t set. So better to use the socket way in order to get the hostname of a given system.