How to temporarily disable sudo credentials timestamp timeout?

I think your best bet is a (backgrounded) busy-wait loop that refreshes the sudo timestamp, which you then kill when you no longer need sudo privileges. Here's a sample script; it runs sleep 6 instead of your two-hour command2 and runs visible /bin/echo commands instead of command1 and command2:

#!/bin/sh
sudo /bin/echo command 1
while :; do sudo -v; sleep 1; done &
infiloop=$!
sleep 6
sudo /bin/echo command 3
kill "$infiloop"

For your actual script, I would recommend a looser loop:

#!/bin/sh
sudo command1
while :; do sudo -v; sleep 59; done &
infiloop=$!
command2
sudo command3
kill "$infiloop"

Adjust the sleep 59 to taste, depending on the existing timestamp_timeout setting in sudoers; I chose 59 just to demonstrate a choice you could make if the timestamp timeout was 60 seconds.


I must be missing something here, because the solution seems very obvious to me.

I don't want to run command2 as root, so I won't run the script itself with sudo.

But you can run the whole script with sudo without running command 2 as root if you change the script:

#!/bin/bash
command1
sudo -u ${SUDO_USER:-$USER} command2
command3

Tags:

Scripting

Sudo