我正在尝试使用 pyroute2 IPDB 功能监视内核网络接口(链接)向上或向下事件。从回调函数中获取接口索引信息时会看到异常。但是在“msg”中有一个索引字段。我根据此参考 http://docs.pyroute2.org/ipdb.html 编码。任何解决异常的想法。
#!/usr/bin/python
import pyroute2
# Create Instance of IPDB
ipdb = pyroute2.IPDB()
action = 'RTM_NEWLINK'
def my_call_back(ipdb, msg, action):
index = msg['index']
print msg
print index
ipdb.register_callback(my_call_back, mode='post')
while(True):
pass
厚望: root @ VirtualBox:/ home / #python notification.py
{'index': 2, 'family': 0, '__align': (), 'header': {'pid': 0, 'length': 1276, 'flags': 0, 'error': None, 'type': 16, 'sequence_number': 0}, 'flags': 4098, 'ifi_type': 1, 'event': 'RTM_NEWLINK', 'change': 1, 'attrs': [('IFLA_IFNAME', 'eth0'), ('IFLA_TXQLEN', 1000), ('IFLA_OPERSTATE', 'DOWN'), ('IFLA_LINKMODE', 0), ('IFLA_MTU', 1500), ('IFLA_GROUP', 0), ('IFLA_PROMISCUITY', 0), ('IFLA_NUM_TX_QUEUES', 1), ('IFLA_GSO_MAX_SEGS', 65535), ('IFLA_GSO_MAX_SIZE', 65536), ('IFLA_NUM_RX_QUEUES', 1), ('IFLA_CARRIER', 0), ('IFLA_QDISC', 'pfifo_fast'), ('IFLA_CARRIER_CHANGES', 21), ('IFLA_PROTO_DOWN', 0), ('IFLA_MAP', {'dma': 0, 'base_addr': 0, 'irq': 0, 'mem_end': 0, 'port': 0, 'mem_start': 0}), ('IFLA_ADDRESS', '08:00:27:5f:7d:3e'), ('IFLA_BROADCAST', 'ff:ff:ff:ff:ff:ff'))
2
Exception in thread IPDB callback 140583224088768:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/pyroute2/ipdb/main.py", line 968, in safe
callback(*argv, **kwarg)
File "notification.py", line 11, in my_call_back
index = msg['index']
KeyError: 'index'
Exception in thread IPDB callback 140583224088768:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/pyroute2/ipdb/main.py", line 968, in safe
callback(*argv, **kwarg)
File "notification.py", line 11, in my_call_back
index = msg['index']
KeyError: 'index'
测试
ifconfig <interface name> up/down
ifconfig eth0 down
ifconfig eth0 up
答案 0 :(得分:1)
当链接建立或关闭时,有多个内核消息从内核传递到回调函数。有些消息没有&#34;索引&#34;由于已发现关键错误而导致的字段。以下修改的功能应解决
def my_call_back(ipdb, msg, action):
if 'index' in msg:
index = msg['index']
interface = ipdb.interfaces[index]
print interface