4

I sometimes need to run a script for hours at a time, during which some commands need sudo. However, if I don't check and reenter the sudo password periodically, I get the sudo: timed out reading password error which sometimes breaks the whole thing. I don't want to use sudo myscript.sh since some of the commands should be run without sudo.

I'd like the sudo cached password to persist for the script for the whole duration of the script without changing the rest of the system (sudo persistence only for this 1 script).

Is there a way to make sudo last for the whole duration of the script and only for the 1 script?

1 Answers1

1

Possibility: run the script with sudo myscript.sh. Inside the script run commands that should be run without sudo this way:

sudo -u "$SUDO_USER" foo args

(maybe with proper logic in case the entire script is ever run without sudo). The root user does not need to authenticate for sudo, and as such is not required to enter a password to run a command as another user.

Depending on how big the script is (how much you need to change it) and how you feel about running the whole thing with sudo you may like or not like the idea. In your current approach non-elevated code is the default, lines with sudo being explicit exceptions. My approach turns this upside down. You need to be more careful when creating and testing the script. I admit this is not the best practice; still it solves the problem of expiring sudo.

Personally I would use this solution for a long running script that is not too complicated (simple loop, few commands). I would think twice before rebuilding a complicated script though.


Another approach is to periodically update the cached credentials in the background. By default these are per tty (see tty_tickets). Proceed like this:

sudo -v                              # to enter your password once
while sleep 300; do sudo -v; done &  # adjust the interval if needed
myscript.sh

Don't forget to kill the background job when no longer needed. The script itself can start such job; then you will probably want some traps in the script to kill the job automatically when the script terminates.