python 獲取本機環境資訊
阿新 • • 發佈:2018-12-21
一、函式
1.socket.gethostname():不帶任何引數,返回一個字串(主機名),通常不完整。比如csm.example.com 只會返回csm
2.socket.getfqdn():帶一個引數,返回完整主機名
二、程式碼
import sys,socket def getipaddrs(hostname): """Given a host name,perform a standard (forward) lookup and return a list of ip addressfor that host.""" result=socket.getaddrinfo(hostname,None,0,socket.SOCK_STREAM) return [x[4][0] for x in result] #calling gethostname() returns the name of the local machine hostname=socket.gethostname() print "hostname is:",hostname #try to get the fully qualified name: print "Fully_qualified name:",socket.getfqdn(hostname) try: print "IP address:", ", ".join(getipaddrs(hostname)) except socket.gaierror,e: print "error"
三、執行結果
[[email protected] testpython]# python host.py hostname is: csm Fully_qualified name: dragoneyes-PC.workgroup IP address: 192.168.155.9