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
Numpy Np.Apply_Along_Axis Function Speed Up
How to Parse Somewhat Wrong JSON with Python
How to Create an Incrementing Filename in Python
Plotting Networkx Graph with Node Labels Defaulting to Node Name
How to Invoke Pandas.Rolling.Apply with Parameters from Multiple Column
Truncate to Three Decimals in Python
How to Access a File's Properties on Windows
How Can Pyspark Be Called in Debug Mode
How to Open a Website with Urllib via Proxy in Python
Read a Small Random Sample from a Big CSV File into a Python Data Frame
Is Close() Necessary When Using Iterator on a Python File Object
Scraping Ajax Pages Using Python
How to Add Timezone into a Naive Datetime Instance in Python
Opencv Python Rotate Image by X Degrees Around Specific Point