Restart/Shutdown your Linux machine using dbus

Ok. This is fairly trivial stuff for many of you, but what I found interesting is that the SystemBus lets you shutdown/restart/suspend/hibernate as an ordinary user. Of course, if you think of a desktop, that is a pretty basic expectation of what an ordinary end-user should be able to do.

But when I think about a server, the thought that people can bypass a sudo while doing a shutdown makes me uneasy. Of course then, dbus shouldn’t be running on a server. Or anything which needs dbus. That means NetworkManager, for one. Of course, servers don’t run NetworkManager. Silly me.

In any case, I got the idea from this post by Timo on python-tutor:

import dbus
bus = dbus.SystemBus()
bus_object = bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer")
bus_object.Shutdown(dbus_interface="org.freedesktop.Hal.Device.SystemPowerManagement")

Of course, I didn’t want to shutdown my netbook while trying out the code. So I tried replacing Shutdown with Suspend. That gave me some fairly confusing error message about some parameters being incorrect. Enough guessing. I decided to RTFM. So I found this [ubuntu wiki page](https://wiki.ubuntu.com/DebuggingGNOMEPowerManager#Sending Direct Suspend/Hibernate Commands).

So I corrected the code above to be instead:

bus_object.Suspend(0, dbus_interface="org.freedesktop.Hal.Device.SystemPowerManagement")

And it indeed put my netbook to sleep.

You don’t need to code in Python to do this. The wiki above gives you the one line command to do this from the console.

$ dbus-send --system --print-reply --dest="org.freedesktop.Hal" /org/freedesktop/Hal/devices/computer org.freedesktop.Hal.Device.SystemPowerManagement.Suspend int32:0
tech
Regular expressions in Python by example Evaluating Posterous #review #webapp