catch system events with python

2k views Asked by At

My Problem is, that I want to catch system events in a python script. If a cable is plugged into the network device and the computer connects to this network, i want to handle this event, starting a function (Because in this moment the default gateway is changing, and i need to recognize this). Is there a module doing this?

i need something like:

if class.network_connect_event():
        do some stuff

This event handling has to work with windows and Unix system.

Thanks

Edit:

What i really need is some way to identify an usb network device. Its important for me to identify it when plugged in, and get its ip adress.

1

There are 1 answers

1
codeape On

You can probably do this by listening to dbus events.

Start experimenting by using dbus-monitor from the command line. Example from my laptop (Ubuntu) when I disconnect eth0:

$ dbus-monitor --system
...
... # lots of events scroll by, including the ones below
...
signal sender=:1.6 -> dest=(null destination) serial=1275 path=/org/freedesktop/NetworkManager/Devices/0; interface=org.freedesktop.NetworkManager.Device.Wired; member=PropertiesChanged
   array [
      dict entry(
         string "State"
         variant             uint32 70
      )  
   ]  
signal sender=:1.6 -> dest=(null destination) serial=1289 

path=/org/freedesktop/NetworkManager/ActiveConnection/1; interface=org.freedesktop.NetworkManager.Connection.Active; member=PropertiesChanged
   array [
      dict entry(
         string "Default"
         variant             boolean true
      )
      dict entry(
         string "State"
         variant             uint32 2
      )
   ]

You should be able to use the Python dbus bindings to listen to those events. I am not familiar with the details on how to do this, but there are tutorials.

EDIT:

Try this package: http://packages.python.org/python-networkmanager/ (disclaimer: I have not tried it).

EDIT 2:

I didn't notice that you need Windows and Unix. On Windows, you will have to find another way (since dbus is not used on Windows).