简体   繁体   中英

What's the best way to test if a user can sudo in Bash?

Reading the sudo man page, I see that the -v flag can be used to check if the user has sudo privileges in his workstation. I have a piece of script that needs to test it. If the user has not sudo privileges, it prints on screen:

Sorry, user tester may not run sudo on debian.

How can I suppress this message and just execute the rest of the code?

Try to append >/dev/null in your command. In case the message is printed in stderr then use 2>/dev/null or as advised in comments use &>/dev/null to redirect both stdout and stderr to null.

Depends on what you mean by "can user sudo"

Short answer:

If can_auto_sudo=$(sudo -l -n sudo &>/dev/null; echo $?) is 0, you can sudo as much as you want.

Long Answer

  • Do you need to test before or can you just handle error cases?
  • How much do you need to know, the sudoers real username is a valid piece of data to want, for example.
  • This question is often asking several different but related questions. So I will ask those more precisely and then answer for each.

1. Is this script being run using sudo?

[ $EUID -eq 0 ] || exit 1 [ $EUID -eq 0 ] || exit 1 # Exit if not effectively root

2. Can this user run a specific command as root using sudo?

sudo -l /usr/bin/program &>/dev/null || exit 2 sudo -l /usr/bin/program &>/dev/null || exit 2 # Exit if it can't run this as sudo

3. Can this user run sudo without interacting?

sudo -l -n /usr/bin/program &>/dev/null || exit 3 sudo -l -n /usr/bin/program &>/dev/null || exit 3 # Exit if requires interaction

4. Can I check all that ahead of time?

`sudo -ll -U $USER # tells you which commands can be runs with sudo by user (have to parse yourself)

5. Script being run with sudo or actually root?

[[ "$(printenv SUDO_USER)" = "" ]] || echo "$SUDO_USER is sudoing!" && exit 5

Using sudo -l or --list As per the man page, sudo can be used with -l or --list to get the list of allowed and forbidden commands for any particular user.

The syntax would be: sudo -l [-AknS] [-a type] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command]

If we use sudo --list without any arguments, then it will print the list of allowed and forbidden commands for the user who is executing the sudo command

sudo --list

User root may run the following commands on client: (ALL) ALL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM