Getting the name of the windows machine running the python script?

Basically, I have a couple of Windows computers on my network that will run a python script. The script must use a different set of configuration parameters, depending on which computer uses this script.

How do i get this computer name in python script?

Let's say the script worked on a computer called DARK-TOWER, I would like to write something like this:

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

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

+78
python windows networking
Apr 28 '09 at 20:49
source share
6 answers

It turned out that there are three options (including two already answered earlier):

 >>> import platform >>> import socket >>> import os >>> platform.node() 'DARK-TOWER' >>> socket.gethostname() 'DARK-TOWER' >>> os.environ['COMPUTERNAME'] 'DARK-TOWER' 
+134
Apr 28 '09 at 20:57
source share
 import socket socket.gethostname() 
+28
Apr 28 '09 at 20:53
source share
+17
Apr 28 '09 at 20:53
source share

As Eric Palakovich Carr said, you can use these three options.

I prefer to use 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 this when developing cross-pattern applications to be sure;)

+9
Jan 13 '16 at 17:29
source share

Since python scripts certainly work on a Windows system, you should use the Win32 API GetComputerName or GetComputerNameEx

You can get the full name of the DNS, or the name NETBIOS, or various things.

 import win32api win32api.GetComputerName() >>'MYNAME' 

Or:

 import win32api WIN32_ComputerNameDnsHostname = 1 win32api.GetComputerNameEx(WIN32_ComputerNameDnsHostname) >> u'MYNAME' 
+6
Apr 28 '09 at 20:52
source share

I put gethostname will work beautifully.

+3
Apr 28 '09 at 20:51
source share



All Articles