Getting name of windows computer running python script?

PythonWindowsNetworking

Python Problem Overview


I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script.

How would I get that computer name in the python script?

Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this:

>>> python.library.get_computer_name()
'DARK-TOWER'

Is there a standard or third party library I can use?

Python Solutions


Solution 1 - Python

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']
'DARK-TOWER'

Solution 2 - Python

import socket
socket.gethostname()

Solution 3 - Python

Solution 4 - Python

As Eric Palakovich Carr said you could use these three variants.

I prefer using them together:

def getpcname():
    n1 = platform.node()
    n2 = socket.gethostname()
    n3 = os.environ["COMPUTERNAME"]
    if n1 == n2 == n3:
        return n1
    elif n1 == n2:
        return n1
    elif n1 == n3:
        return n1
    elif n2 == n3:
        return n2
    else:
        raise Exception("Computernames are not equal to each other")

I prefer it when developing cross patform applications to be sure ;)

Solution 5 - Python

Since the python scrips are for sure running on a windows system, you should use the Win32 API GetComputerName or GetComputerNameEx

You can get the fully qualified DNS name, or NETBIOS name, or a variety of different things.

import win32api
win32api.GetComputerName()

>>'MYNAME'

Or:

import win32api
WIN32_ComputerNameDnsHostname = 1 
win32api.GetComputerNameEx(WIN32_ComputerNameDnsHostname)

>> u'MYNAME'

Solution 6 - Python

import socket
pc = socket.gethostname()
print pc

Solution 7 - Python

I bet gethostname will work beautifully.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEric Palakovich CarrView Question on Stackoverflow
Solution 1 - PythonEric Palakovich CarrView Answer on Stackoverflow
Solution 2 - PythonbrettkellyView Answer on Stackoverflow
Solution 3 - PythononeporterView Answer on Stackoverflow
Solution 4 - PythonFaminatorView Answer on Stackoverflow
Solution 5 - PythonBrian R. BondyView Answer on Stackoverflow
Solution 6 - PythonPedro MunizView Answer on Stackoverflow
Solution 7 - PythonPromitView Answer on Stackoverflow