1

I'm trying to write a script for Centos 6.8 where the user will not be root. There is no admin on the premises, so the script needs to be added to the sudoers (by adding a file to /etc/sudoers.d) by that same script.

It seems like the user should be prompted by the script for the root password, right? If not, what is the convention to get around this (other than having a second script to add to the sudoers when the user runs from root)?

I've tried something along the lines of this:

echo 'foobar ALL=(ALL:ALL) ALL' | sudo EDITOR='tee -a' visudo

and this:

ALL=NOPASSWD:/usr/bin/rsync" | (sudo su -c 'EDITOR="tee" visudo -f /etc/sudoers.d/rsync')

as suggested here, but these just give a continuation prompt.

My basic question is how to prompt for the password and use it to give the user permission to run the script.

The other option is to run the script as root, but I'd like to see if I can do it otherwise.

0

If you just want to prompt for a password to elevate privileges, then add

sudo -v

in the line before this. The script will stop, ask for the password, and continue once an acceptable password has been entered or exit if the password check fails.

Effectively:

#!/bin/bash

# Initiate sudo session
sudo -v
# Execute command; sudo session for tee is already active.
echo 'foobar ALL=(ALL:ALL) ALL' | sudo EDITOR='tee -a' visudo

If this is a long running script, consider making this a function that runs early on:

sudo -v
while true;
do
    sudo -n true
    sleep 60
    kill -0 "$$" || exit
done 2>/dev/null &

Your script will look something like this then:

#!/bin/bash

sudoChk () {
    sudo -v
    while true;
    do
        sudo -n true
        sleep 60
        kill -0 "$$" || exit
    done 2>/dev/null &
}

sudoChk
#...long running commands...
echo 'foobar ALL=(ALL:ALL) ALL' | sudo EDITOR='tee -a' visudo
exit 0

You may also be looking for:

sudo sh -c

instead of

sudo su -c

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.