致谢!
参考链接:
要点:避免因uuid获取全部MAC而导致每次开机随机改变的问题。
getNetworkStatus.py如下:
# coding:utf-8
"""
Covered on 2022-01-20
@author: Harden Qiu
# python getNetworkStatus.py
"""
import os
import sys
try:
import netifaces
except ImportError:
try:
command_to_execute = "pip install netifaces || easy_install netifaces"
os.system(command_to_execute)
except OSError:
print("Can NOT install netifaces, Aborted!")
sys.exit(1)
import netifaces
routingGateway = netifaces.gateways()['default'][netifaces.AF_INET][0]
routingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1]
def get_nic_info():
"""
show Windows or Linux network Nic status, such as MAC address, Gateway, IP address, etc
Routing Gateway: 192.168.xx.xx
Routing NIC Name: xxxx
Routing NIC MAC Address: 08:71:xx:xx:xx:xx
Routing IP Address: 192.168.xx.xx
Routing IP Netmask: 255.255.255.0
"""
routingNicMacAddr = ''
routingIPAddr = ''
routingIPNetmask = ''
for interface in netifaces.interfaces():
if interface == routingNicName:
# print netifaces.ifaddresses(interface)
routingNicMacAddr = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr']
try:
routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
# TODO(Guodong Ding) Note: On Windows, netmask maybe give a wrong result in 'netifaces' module.
routingIPNetmask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask']
except KeyError:
pass
# display_format = '%-30s %-20s'
# print(display_format % ("Routing Gateway:", routingGateway))
# print(display_format % ("Routing NIC Name:", routingNicName))
# print(display_format % ("Routing NIC MAC Address:", routingNicMacAddr))
# print(display_format % ("Routing IP Address:", routingIPAddr))
# print(display_format % ("Routing IP Netmask:", routingIPNetmask))
return routingGateway, routingNicName, routingNicMacAddr, routingIPAddr, routingIPNetmask
测试
# coding:utf-8
"""
Covered on 2022-01-20
@author: Harden Qiu
# python test.py
"""
from getNetworkStatus import get_nic_info
a, b, c, d, e = get_nic_info()
display_format = '%-30s %-20s'
print(display_format % ("Routing Gateway:", a))
print(display_format % ("Routing NIC Name:", b))
print(display_format % ("Routing NIC MAC Address:", c))
print(display_format % ("Routing IP Address:", d))
print(display_format % ("Routing IP Netmask:", e))
结果:
Routing Gateway: 192.168.xx.xx
Routing NIC Name: xxxx
Routing NIC MAC Address: 08:71:xx:xx:xx:xx
Routing IP Address: 192.168.xx.xx
Routing IP Netmask: 255.255.255.0