问题描述
我正在编写在Linux上运行的Python应用程序。如果要插入/拔出网络电缆,我希望能够注册并被系统通知。
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.
我已经在使用(libUdev的python绑定)来获取通知USB插入事件。但是,由于网络eth0模块(例如)始终保持加载状态(无论是否插入电缆),我都无法获得所需的信息。它仅适用于上/下事件。
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.
我在Windows WMI上阅读了很多提供此功能的文章,但在Linux上却没有。
I have read a lot of posts on Windows WMI providing this functionality but none on linux. Am I looking in the right direction?
这样做的python方法(一个python库)将是理想的,因为我想将此与我的程序集成在一起。
A python way of doing this (a python library) would be ideal as I want to integrate this with my program.
推荐答案
有很多方法可以通过轮询来获取网络接口的 UP状态,其中包括简单地解析 ifconfig 输出,以读取/ proc / net / ...伪文件的状态。
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.
但是,通知的方式(即不要自行调查)此类事件,在Ubuntu上,最好的选择是使用 netplug 软件包。默认情况下未安装它,您需要:
sudo apt-get install netplug
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
某些文档在此处:
要进行设置,您需要调整/etc/netplug/netplugd.conf和/ etc / netplug / netplug脚本。有关这些配置文件的示例,请查看
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
使用/ etc / netplug / netplug,您可以在网络中断/启动时调用自己的python脚本,这样就可以为您的应用程序生成事件。
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.
这篇关于在“插入以太网电缆”时得到通知Linux中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!