[sudo-users] Proper way to check if current user can sudo
Marc Cornellà
hello at mcornella.com
Sat Mar 26 14:47:57 MDT 2022
Hi everyone,
I'm reposting the query I made in the GitHub repository:
https://github.com/sudo-project/sudo/issues/130.
I'm trying to write a check to see if the user can run `sudo`, in a way
that is portable and compatible with old versions of `sudo`, and doesn't
ask the user for a password.
This is what I came up with, but can this be done better? I really hate
having to check for the correct wording in the error message, since that
seems to be very brittle.
user_can_sudo() {
# The following command has 3 parts:
#
# 1. Run `sudo` with `-v`. Does the following:
# • with privilege: asks for a password immediately.
# • without privilege: exits with error code 1 and prints the message:
# Sorry, user <username> may not run sudo on <hostname>
#
# 2. Pass `-n` to `sudo` to tell it to not ask for a password. If the
# password is not required, the command will finish with exit code 0.
# If one is required, sudo will exit with error code 1 and print the
# message:
# sudo: a password is required
#
# 3. Check for the words "may not run sudo" in the output to really tell
# whether the user has privileges or not. For that we have to make sure
# to run `sudo` in the default locale (with `LANG=`) so that the
message
# stays consistent regardless of the user's locale.
#
LANG= sudo -n -v 2>&1 | grep -q "may not run sudo"
}
Thanks,
Marc Cornellà
More information about the sudo-users
mailing list