Checking sudo in Bash (script with if statements)
Asked Answered
I

3

18

I've been working with bash for not more than 6 hours, and now I'm trying to create a menu that allows you to do some "fun" stuff :D.

My problem is with the if statement that check if you're in sudo mode. I want to have 3 conditions:

  1. If I execute the script with sudo mode, I'll be able to enter the path of the folder to be copied.
  2. If I execute the script without sudo mode, it'll ask me to insert the password, if I do that correctly the script will show me the echo and read op that allows me to write the path of the folder to be copied.
  3. The same as the point 2, but if I fail the authentication the application will be closed automatically.

Create a copy

2)
    if [ "$EUID" -ne 0 ]
      then 
            echo "Checking if you are in sudo mode..."
            echo "Error, please insert your password:"
            sudo ls /root
            if [ "$EUID" -ne 0 ]
                then
                    echo -e "\nCould not authenticate the user."
                    echo -e "For security reasons the application will be closed."
                    exit    
            else
                echo "==============================================================="
                echo -e "ALL COPIES HAVE A DEFAULT ROUTE: /home/patryk/Desktop/a/"
                echo "==============================================================="
                echo -e "Enter the path of the folder to be copied: "
                read origin
                rsync -avzh $origin /home/patryk/Desktop/a/`date-I`
            fi
    else
        echo "==============================================================="
        echo -e "ALL COPIES HAVE A DEFAULT ROUTE: /home/patryk/Desktop/a/"
        echo "==============================================================="
        echo -e "Enter the path of the folder to be copied: "
        read origin
        rsync -avzh $origin /home/patryk/Desktop/a/`date -I`    
    fi;;    
Izzo answered 18/3, 2017 at 14:48 Comment(8)
Welcome to SO, please show your coding efforts.Kempis
Yeah, sorry :D.Izzo
did you try elif statement?Lamartine
I was about to put it, but I didn't. I'm with this for about 5 hours...Izzo
As an aside, your prolific use of echo -e seems misdirected. You should probably consider switching to printf instead.Spiegeleisen
Your EUID will be switched back to your own after sudo finishes. It affects only the command you run under sudo, not the remainder of your script. See also #37587311Spiegeleisen
You should use double quotes around "$origin" unless you are completely sure that its value cannot ever contain any shell metacharacters. See #10067766Spiegeleisen
Thanks for the help :)Izzo
G
24

If you have sudo credentials caching enabled (that is, after a successful sudo, you don't have to enter the password again for subsequent sudos) you could use the following trick:

Execute sudo true and check the return status. If the correct password was entered, the exit code will always be 0. Otherwise the exit code will be different.

if [[ "$EUID" = 0 ]]; then
    echo "(1) already root"
else
    sudo -k # make sure to ask for password on next sudo ✱
    if sudo true; then
        echo "(2) correct password"
    else
        echo "(3) wrong password"
        exit 1
    fi
fi
# Do your sudo stuff here. Password will not be asked again due to caching.

✱ Assuming a standard configuration, where you have to enter your password at least sometimes when using sudo. If your user is configured for passwordless sudo (see NOPASSWD in/etc/sudoers) then this won't work.

Gobang answered 18/3, 2017 at 16:23 Comment(5)
This doesn't work if the user is in the sudo group but is not actively running this script as sudo. I have a user in sudo group - this always returns true - is sudo - whether or not I run using sudo. Bash. Ubuntu 20.04 @Brian Fitzgerald 's pgrep script does work.Halfassed
@Halfassed Are you sure the user being in a group is the actual problem. I cannot reproduce what you described. Store #! /bin/bash + above script in a executable file, then run sudo docker run -it --rm -v /path/to/script.sh:/script.sh ubuntu:20.04 bash -c 'apt update; apt install sudo; useradd --groups root joe; su joe -c bash' then enter /script.sh. The user joe is asked for the password, even though they are in group root.Gobang
Maybe the actual reason lies somewhere else (e.g. setuid, or passwordless sudo through sudoers file?). If you send a reproducible docker command, I can have a look at it again.Gobang
Turns out the server does have passwordless sudo set up. If that is the case then the following is the most likely to work in all cases: if pgrep -s 0 '^sudo$' > /dev/null ; then echo "You have sudo permissions" else echo "Not sudo - running as user " fi Halfassed
@Halfassed Thank you for the reply. No need to repost Brian Fitzgerald's as a comment though. Also note: You are looking for something slightly different than what was asked in this question. OP asked for »2. If I execute the script without sudo mode, it'll ask me to insert the password« which Fitzgerald's answer doesn't do either. Not sure if you could instruct sudo to ask for a password, even if NOPASSWD is configured in /etc/sudoers.Gobang
K
1

Script

if pgrep -s 0 '^sudo$' > /dev/null ; then
    echo 'Hello Sudo'
else
    echo 'Hello Chestnut'
fi

Notes

  • pgrep checks for existence of processes that match a regular expression
  • regex '^sudo$' matches 'sudo' exactly
  • -s 0 limits the search to one's own session
  • "if" branches depending on the return code of pgrep
Keri answered 13/7, 2023 at 16:24 Comment(0)
M
0

I think what you really want to do is to check whether your script runs as root or not. If security considerations are not super duper important you could just throw this at the beginning of your script:

if [ "$USER" != "root" ]
then
    echo "Please run this as root or with sudo"
    exit 2
fi

This will work and also cover the case where sudo is used to run command as another user (who is not root)

Manicure answered 3/9, 2022 at 6:21 Comment(1)
That's slightly different from the question, since a user account with sudo permissions will still have the user accounts name, not root. if [ "$EUID" -ne 0 ] seems to be the right approach to this. And just to note, best practice is to avoid using the root user!Proleg

© 2022 - 2024 — McMap. All rights reserved.