python之netifaces模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/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' ][netifaces.AF_INET][ 0 ]
routingNicName  =  netifaces.gateways()[ 'default' ][netifaces.AF_INET][ 1 ]
 
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)
1
windows执行的Routing NIC Name可能会出现C20B1496-F5CA-4670-A4FB-之类
1
2
https: //pypi .python.org /pypi/netifaces
用法



本文转自 yanconggod 51CTO博客,原文链接:http://blog.51cto.com/yanconggod/1886289

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值