your programing

Python을 사용하여 시스템 호스트 이름을 얻으려면 어떻게해야합니까?

lovepro 2020. 10. 2. 23:04
반응형

Python을 사용하여 시스템 호스트 이름을 얻으려면 어떻게해야합니까?


로컬 네트워크 용 채팅 프로그램을 작성 중입니다. 컴퓨터를 식별하고 Python으로 사용자가 설정 한 컴퓨터 이름을 얻고 싶습니다.


사용 socketgethostname()기능. 이것은 hostname파이썬 인터프리터가 실행되는 컴퓨터를 가져올 것 입니다 :

import socket
print(socket.gethostname())

이 두 가지 모두 이식성이 뛰어납니다.

import platform
platform.node()

import socket
socket.gethostname()

HOST또는 HOSTNAME환경 변수를 사용하는 솔루션 은 이식 할 수 없습니다. 실행할 때 시스템에서 작동하더라도 cron과 같은 특수 환경에서 실행하면 작동하지 않을 수 있습니다.


어쨌든 os 모듈을로드 할 것이므로 다른 제안은 다음과 같습니다.

import os
myhost = os.uname()[1]

이건 어떤가요 :

import platform

h = platform.uname()[1]

실제로 모든 결과를보고 싶을 수 있습니다. platform.uname()


os.getenv('HOSTNAME')그리고 os.environ['HOSTNAME']항상 작동하지 않습니다. 크론 작업 및 WSDL에서 HTTP HOSTNAME이 설정되지 않았습니다. 대신 사용 :

import socket
socket.gethostbyaddr(socket.gethostname())[0]

/ etc / hosts 에 짧은 별칭을 정의 했더라도 항상 (Windows에서도) 완전한 호스트 이름을 반환 합니다 .

당신이 별명 정의 된 경우 / 등 / 호스트는 다음 socket.gethostname()별칭을 반환합니다. platform.uname()[1]같은 일을합니다.

위의 내용이 작동하지 않는 경우가 발생했습니다. 이것이 내가 지금 사용하고있는 것입니다.

import socket
if socket.gethostname().find('.')>=0:
    name=socket.gethostname()
else:
    name=socket.gethostbyaddr(socket.gethostname())[0]

먼저 gethostname을 호출하여 원래 솔루션을 사용하지 않는 경우 호스트 이름처럼 보이는 것을 반환하는지 확인합니다.


내가 맞다면 socket.gethostname 함수를 찾고 있습니다.

>> import socket
>> socket.gethostname()
'terminus'

socket.gethostname() 할 수있다


적어도 파이썬> = 3.3에서 :

필드 nodename를 사용하고 배열 인덱싱을 사용하지 않을 수 있습니다 .

os.uname().nodename

하지만, 심지어 문서 os.uname는 사용 제안socket.gethostname()


On some systems, the hostname is set in the environment. If that is the case for you, the os module can pull it out of the environment via os.getenv. For example, if HOSTNAME is the environment variable containing what you want, the following will get it:

import os
system_name = os.getenv('HOSTNAME')

Update: As noted in the comments, this doesn't always work, as not everyone's environment is set up this way. I believe that at the time I initially answered this I was using this solution as it was the first thing I'd found in a web search and it worked for me at the time. Due to the lack of portability I probably wouldn't use this now. However, I am leaving this answer for reference purposes. FWIW, it does eliminate the need for other imports if your environment has the system name and you are already importing the os module. Test it - if it doesn't work in all the environments in which you expect your program to operate, use one of the other solutions provided.


I needed the name of the PC to use in my PyLog conf file, and the socket library is not available, but os library is.

For Windows I used:

os.getenv('COMPUTERNAME', 'defaultValue')

Where defaultValue is a string to prevent None being returned


You have to execute this line of code

sock_name = socket.gethostname()

And then you can use the name to find the addr :

print(socket.gethostbyname(sock_name))

참고URL : https://stackoverflow.com/questions/4271740/how-can-i-use-python-to-get-the-system-hostname

반응형