Restart/Shutdown Your Linux Machine Using Dbus

Ok. This is fairly trivial stuff for many of you, but what I found interesting is that 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.

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.

BTW, 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s