How to turn off a Linux system without root or sudo

How to turn off a Linux system without root or sudo

If you need to know how to turn off modern Linux systems, which run systemd, without root or sudo programmatically (Python or Bash shown here) or from a command line. Without using deprecated approaches like HAL and/or ConsoleKit. Then read this my blog post.

SystemD + D-Bus + PolicyKit

This solution is simple and will work on current Linux systems that use systemd like Fedora, Debian, Ubuntu, Raspbian and others.

The described solution is the preferred way over the HAL (deprecated since 2009) or ConsoleKit (not actively maintained since 2013) solutions you can find all over the Internet and that are often not relevant to the current Linux systems.

1) Prepare PolicyKit permissions

As a root create & edit a polkit policy file:

/etc/polkit-1/localauthority/50-local.d/allow_all_users_to_shutdown.pkla

and add this policy that allows all users to power off the system:

[Allow all users to shutdown]
Identity=unix-user:*
Action=org.freedesktop.login1.power-off;org.freedesktop.login1.power-off-multiple-sessions
ResultActive=yes
ResultAny=yes

Reload daemons configuration:

$ sudo systemctl daemon-reload

2-a) Command-line / bash command:

$ dbus-send \
    --system \
    --print-reply \
    --dest=org.freedesktop.login1 \
    /org/freedesktop/login1 \
    "org.freedesktop.login1.Manager.PowerOff" \
    boolean:true

2-b) Python code:

import dbus

sys_bus = dbus.SystemBus()
ck_srv = sys_bus.get_object('org.freedesktop.login1',
                            '/org/freedesktop/login1')
ck_iface = dbus.Interface(ck_srv, 'org.freedesktop.login1.Manager')
ck_iface.get_dbus_method("PowerOff")(False)

Python code pro-tip:

Check if the current user has the ability to shut down the system:

can =  ck_iface.get_dbus_method("CanPowerOff")()
if not can:
    print("You cannot shutdown this system! "
          "(Update polkit policy to allow you org.freedesktop.login1.power-off)")

Links

Comments are closed.