美文网首页
2016-06-15

2016-06-15

作者: 周叶铨 | 来源:发表于2017-08-31 15:24 被阅读40次

    用dbus监控网口状态

    昨天弄明白了NetworkManager是挂到dbus上面的。
    所以理论上说,我们应该可以写一个dbus程序,监视网口的状态变化。

    Dbus这东西我一直没有仔细研究,趁着这个机会,我可以把各个概念梳理一下。
    我主要的参考文档是dbus python tutorial

    做测试的工具有qdbus, gdbus, 还有dbus-monitor。

    我觉得要论用户友好程度,qdbus首屈一指。它的输出层层递进,基本上不会给出一堆看不懂的东西。

    弄明白bus, object, interface, method, property, signal等等概念之后,再玩gdbus
    就很容易了。他的introspect功能很赞。而且man page里面给出了详尽的例子。

    昨天我发现了ifup/ifdown和ip link set xxx up/down对于NetworkManager来说是有一些区别的。
    我今天就要写一个python程序,能够监视在dbus上,在这两类事件发生的时候,把事件打印出来。

    程序如下:

    #!/usr/bin/env python
    import sys
    import dbus
    import dbus.mainloop.glib; dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    from gi.repository import GObject
    
    system_bus = dbus.SystemBus()
    
    def main():
        system_bus.add_signal_receiver(handle_dbus_event,
                                        bus_name="org.freedesktop.NetworkManager",
                                        sender_keyword = 'd_sender',
                                        destination_keyword = 'd_destination',
                                        interface_keyword = 'd_interface',
                                        member_keyword = 'd_member',
                                        path_keyword = 'd_path')
        loop = GObject.MainLoop()
        loop.run()
        return 0
    
    def handle_dbus_event(*args, **kwargs):
        path = kwargs['d_path']
        signal = kwargs['d_member']
        interface = kwargs['d_interface']
    
        if interface == 'org.freedesktop.NetworkManager.Device' and signal == 'StateChanged':
            states = { 0: "Unknown",
               10: "Unmanaged",
               20: "Unavailable",
               30: "Disconnected",
               40: "Prepare",
               50: "Config",
               60: "Need Auth",
               70: "IP Config",
               80: "IP Check",
               90: "Secondaries",
               100: "Activated",
               110: "Deactivating",
               120: "Failed" }
    
            new_state = states[args[0]]
            old_state = states[args[1]]
            reason = args[2]
            # get device name
            device_proxy = system_bus.get_object(bus_name="org.freedesktop.NetworkManager", object_path=path)
            device_name = device_proxy.Get("org.freedesktop.NetworkManager.Device", "Interface")
            print "State for {0} has changed from {1} to {2}, reason {3}".format(device_name, old_state, new_state, reason)
        if interface == 'org.freedesktop.NetworkManager.Device.Wired' and signal == 'PropertiesChanged':
           # ok, now we get a notification of wired property change
           properties = dict(args[0])
           for key in properties.keys():
               if str(key) == 'Carrier':
                   connected = bool(properties[key])
                   # get device name
                   device_proxy = system_bus.get_object(bus_name="org.freedesktop.NetworkManager", object_path=path)
                   device_name = device_proxy.Get("org.freedesktop.NetworkManager.Device", "Interface")
    
                   print "The device {0} gets link level connected: {1}".format(device_name, connected)
    
    if __name__ == '__main__':
        sys.exit(int(main() or 0))
    
    

    由于以前没有用python-dbus写过程序,刚开始写的时候有点磕磕碰碰。
    好在有这个代码作参考,另外我也下载了NetworkManager的代码,里面有些dbus python的例子。
    拼拼凑凑也就把程序弄出来了。

    根据这个程序的输出,我有一个意外发现,就是nmcli connection up enp0s8其实做的事情很多:

    State for enp0s8 has changed from Activated to Deactivating, reason 60
    State for enp0s8 has changed from Deactivating to Disconnected, reason 60
    State for enp0s8 has changed from Disconnected to Prepare, reason 0
    State for enp0s8 has changed from Prepare to Config, reason 0
    State for enp0s8 has changed from Config to IP Config, reason 0
    State for enp0s8 has changed from IP Config to IP Check, reason 0
    State for enp0s8 has changed from IP Check to Secondaries, reason 0
    State for enp0s8 has changed from Secondaries to Activated, reason 0
    

    也就是说,每次做nmcli connection up的时候,其实这个网口是被disconnect然后重新connect。

    相关文章

      网友评论

          本文标题:2016-06-15

          本文链接:https://www.haomeiwen.com/subject/fqmqjxtx.html