0

How can I check (in a safe way) if the current user has the permissions needed to shutdown the system on Unix & Linux?

I'm writing a script that needs to check to see if the current user has the permission needed to shutdown the system. But, of course, I want to determine this before actually attempting to shutdown the system.

Ideally, I'd like a solution that works on as many Unix & Linux distros as possible.

What can I execute in my script to check to see if the current user has permission to shutdown the system?

  • 1
    There isn't really a way to do this because there are so many different ways of elevating privileges (e.g. su, sudo, super, etc) AND many different ways to shut down a machine (the "standard" shutdown/reboot/halt/poweroff binaries, a copy of shutdown setuid root, systemctl, telinit to change run-level, a setuid copy of bash or some other shell, etc). You can prove that a user can (or can't) shutdown a machine in one particular way, but that doesn't tell you anything about whether they can/can't use another method. You'll have to check them all. Leaving "try it and test the exit code". – cas Oct 02 '22 at 03:26

1 Answers1

0

I can't tell if the -k option is available on all unixoid platforms, but you can give it a try and check the exit code. This may issue the warning to all terminals though.

$ shutdown -k -r now; echo $?
shutdown: you must be root to do that!
Usage:    shutdown [-akrhPHfFnc] [-t sec] time [warning message]
[...]
                  -k:      don't really shutdown, only warn.
[...]
1
$ sudo shutdown -k -r now; echo $?

Broadcast message from root@macalla (pts/2) (Mon Oct  3 11:25:09 2022):

The system is going down for reboot NOW!

Shutdown cancelled.
0
Murphy
  • 2,609
  • 1
  • 13
  • 21