How to Use Python to Get the System Hostname

How can I use Python to get the system hostname?

Use socket and its gethostname() functionality. This will get the hostname of the computer where the Python interpreter is running:

import socket
print(socket.gethostname())

How to get fully qualified host name in Python?

Use the descriptively-named function socket.getfqdn():

>>> import socket   
>>> socket.getfqdn()
'phxdbx45.phx.host.com'

Getting name of windows computer running python script?

It turns out there are three options (including the two already answered earlier):

>>> import platform
>>> import socket
>>> import os
>>> platform.node()
'DARK-TOWER'
>>> socket.gethostname()
'DARK-TOWER'
>>> os.environ['COMPUTERNAME'] # WORK ONLY ON WINDOWS
'DARK-TOWER'

Python on Linux: get host name in /etc/hostname

First of all, all credit should go to m1k3y02, who gave me the hint in a comment. Now, for the sake of posterity I will give the correct answer: my Amazon EC2 has not been rebooted in a long time. I set the hostname in /etc/hostname but it did not reach the system, as evidenced by uname -n. So simply running /etc/init.d/hostname.sh did the trick. After that, socket.gethostname() worked as intended.

The lesson here: first see if the system gets it, and only after that blame the language.

Using Regex to define hostname

Since hostname will always come before the word you need to extract, you need

match = re.search(r'hostname\s+(\S+)', DEVICE_NAME)
if match:
print(match.group(1))

Note it is always better to check if a match occurred before accessing the group(1) value to avoid the AttributeError: 'NoneType' object has no attribute 'group' issue.

Note you do not need the re.M option as it only modifies the behavior of the ^ and $ anchors in the regex, and yours has neither.



Related Topics



Leave a reply



Submit