Getting Notified on “Ethernet cable plugged in” ev

2019-05-22 14:33发布

问题:

I am writing a Python Application running on linux. I want to be able to register and be notified by the system if a network cable is plugged in/ out.

I am already using pyUdev (python bindings for libUdev) in order to get notified for USB plug in events. However, because the network eth0 module (for example) always remains loaded (regardless of the cable being plugged in) , I dont get the information I require. It only works for if up/down events.

I have read a lot of posts on Windows WMI providing this functionality but none on linux. Am I looking in the right direction?

A python way of doing this (a python library) would be ideal as I want to integrate this with my program.

回答1:

There are many ways to get the "UP" status of a network interface via polling, ranging from simply parsing ifconfig output, to reading the status of /proc/net/... pseudo-files.

However, for a way to be notified (i.e. not poll yourself) for such events, your best option on Ubuntu is to use the netplug package. It's not installed by default, you need to: sudo apt-get install netplug

Some documentation is here: http://manpages.ubuntu.com/manpages/lucid/man8/netplugd.8.html

To set it up you need to tweak /etc/netplug/netplugd.conf and /etc/netplug/netplug scripts. For an example of those config files check out the section "Configuring netplug" at http://natisbad.org/dyn-net/index.html

With /etc/netplug/netplug you can have your own python script called when the network goes down/up, so you can generate your kind of event for your application.



回答2:

Have you looked into netplugd command, I am not sure if a python wrapper exists but it should not be hard to parse the output