Getting name of windows computer running python script?

88,973

Solution 1

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

import socket
socket.gethostname()

Solution 3

From https://mail.python.org/pipermail/python-list/2006-April/397494.html

import os
os.getenv('COMPUTERNAME')

Solution 4

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

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'
Share:
88,973

Related videos on Youtube

Eric Palakovich Carr
Author by

Eric Palakovich Carr

Full stack developer with 17+ years experience creating web, mobile, and desktop software. Currently specializing in Python/Kotlin for the backend (primarily Django/Spring Boot), React for the frontend, and React Native for mobile (iOS and Android).

Updated on July 08, 2022

Comments

  • Eric Palakovich Carr
    Eric Palakovich Carr almost 2 years

    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?

  • Stephan202
    Stephan202 about 15 years
    Answering one's own question may be considered poor taste by some, but it is perfectly fine, as per the FAQ: stackoverflow.com/faq
  • nilamo
    nilamo about 15 years
    I don't think it's bad at all, since Eric was compiling a few different responses into a single resource, not to mention adding a new one (platform).
  • Jason S
    Jason S about 13 years
    ok, so this cries out for a follow-up: what's the difference between platform.node() and socket.gethostname() ? can they ever be different?
  • Peter Gibson
    Peter Gibson over 12 years
    This doesn't work for me on OS-X 10.6.8 using Python 2.7.2, it returns None. The other methods described do work however.
  • Daniel F
    Daniel F about 12 years
    @PeterGibson I had the same thing occurring to me on Ubuntu 12.04.
  • Peter Gibson
    Peter Gibson almost 12 years
    On posix systems, socket.gethostname() returns the libc gethostname(), while platform.node() returns platform.uname()[1] which is somewhat related to os.uname() which calls the libc uname()... It looks like they might end up in the same place, but they take quite different paths to get there and I wouldn't be relying on the value to be the same across different platforms.
  • joshin4colours
    joshin4colours over 11 years
    +1 for this being the best way to go. It's the most effective cross-platform call.
  • Kobor42
    Kobor42 over 10 years
    On one side it wasn't one second answer, on the other side you got 3 to 4 perfectly acceptable answers before you did yours.
  • Charles Plager
    Charles Plager over 8 years
    Just a bit cleaner: if n1==n2 or n2==n3: return n1 elif n2==n3: return n2 else: raise Exception("Computer names are not equal to each other")
  • MrNoob
    MrNoob almost 7 years
    Worth noting that os.environ['COMPUTERNAME'] will return all uppercase, whereas platform.node() and socket.gethostname() can return mixed case.
  • dexteritas
    dexteritas over 6 years
    @CharlesPlager It should be: if n1==n2 or n1==n3: return n1 elif n2==n3: return n2 else: raise Exception("Computer names are not equal to each other") (n1 instead of n2)
  • Charles Plager
    Charles Plager over 6 years
    @dexteritas: You are correct. (It won't let me edit it for whatever reason).
  • Matt Hancock
    Matt Hancock about 6 years
    Returns None for me on Ubuntu 16.04. Interestingly, HOSTNAME is a defined environment variable in bash, but both os.getenv('HOSTNAME') returns None also, while socket.gethostname() returns the correct string.
  • Bill
    Bill almost 6 years
    os.environ['COMPUTERNAME'] returns an error for me: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/billtubbs/anaconda/envs/py36/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'COMPUTERNAME'
  • DaFois
    DaFois over 4 years
    Please add always some explanation to the answer.
  • Séraphin
    Séraphin over 4 years
    os.environ['COMPUTERNAME'] not always working, This environment variable is not set on my computer running Ubuntu 18.04
  • wovano
    wovano about 4 years
    Besides, this answer is just a copy of a 10-year old highly-upvoted other answer.
  • busdriver
    busdriver over 3 years
    You could use os.getenv("COMPUTERNAME") which returns None instead of raising error if "COMPUTERNAME" does not exist in env.
  • Dmitry Dronov
    Dmitry Dronov over 3 years
    platform.node() is crossplatform too
  • Xxxo
    Xxxo over 2 years
    Computer name and host name are two different things. For example, when you are in a VPN, your host name is X and your computer name can be Y. This answer is not correct, since the question is about COMPUTER name and not host name.