返回列表 发帖

获取主机名和IP

Windows获取主机名和IP

#coding=utf-8

import socket,uuid

#获取主机名
hostname = socket.gethostname()

#获取IP
ip = socket.gethostbyname(hostname)

#获取Mac地址
def get_mac_address():
        mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
        return ":".join([mac[e:e+2] for e in range(0,11,2)])

print("主机名:",hostname)
print("IP:",ip)
print("Mac地址:",get_mac_address())




###################################

Linux获取主机名和IP

#coding=utf-8

import socket,uuid,os

#获取主机名
hostname = socket.gethostname()

#获取IP
ip = os.popen("ifconfig | grep -i bcast |awk '{print $2}' |cut -d: -f 2").read()#返回的数据多了个换行符
ip = ip.strip('\n')#去掉换行符

#获取Mac地址
def get_mac_address():
        mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
        return ":".join([mac[e:e+2] for e in range(0,11,2)])

print("主机名:",hostname)
print("IP:",ip)
print("Mac地址:",get_mac_address())

返回列表