vivion34 发表于 2018-8-16 06:04:25

python之netifaces模块

#!/usr/bin/python  
# encoding: utf-8
  
# -*- coding: utf8 -*-
  
"""
  
Create Date:      2016/12/26
  
Create Time:      17:53
  
show Windows or Linux network Nic status, such as MAC address, Gateway, IP address, etc
  
# python getNetworkStatus.py
  
Routing Gateway:               10.0.0.1
  
Routing NIC Name:            enp3s0
  
Routing NIC MAC Address:       10:c3:7b:61:22:02
  
Routing IP Address:            10.0.0.194
  
Routing IP Netmask:            255.255.255.0
  
"""
  
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']
  
routingNicName = netifaces.gateways()['default']
  

  
for interface in netifaces.interfaces():
  
    if interface == routingNicName:
  
      # print netifaces.ifaddresses(interface)
  
      routingNicMacAddr = netifaces.ifaddresses(interface)['addr']
  
      try:
  
            routingIPAddr = netifaces.ifaddresses(interface)['addr']
  
            # TODO(Guodong Ding) Note: On Windows, netmask maybe give a wrong result in 'netifaces' module.
  
            routingIPNetmask = netifaces.ifaddresses(interface)['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)
页: [1]
查看完整版本: python之netifaces模块