I've made a simple bash script that need to keep it's super-user privileges throughout the script. Unfortunately, but understandable the script looses its sudo
-eleveted permissions when the sleep
occurs. Not good for me:
sudo echo "I am sudo!" # Asks for passwords
sleep(60)
sudo echo "I am sudo!" # Need to enter password again.
I thought about replacing the sleep
with a while-loop that keeps the sudo alive, but I am pretty sure that there's better options available to make the sudo
-permissions stay throughout the script?
Thanks
Working strictly within a script (and not editing the sudoers file or calling the script via
sudo ./script.sh
), here's what I think the cleanest method is.Basically, this defines a pair of functions for enabling and disabling sudo mode. Calling
startsudo
before running your sudo-using code authenticates with sudo, forks a background sudo-refreshing loop, saves the loop's PID, and sets a signal trap to stop sudo mode when Ctrl+C is pressed. Callingstopsudo
kills the loop, clears the signal trap, and invalidates the earlier authentication with sudo.After copying these functions into your script, use them like this.
I would like to thank @karl for the simplicity of inlining the sudo-refreshing loop and @sehe for pointing out that a signal trap should be used to kill the loop if it isn't killed normally. Both of these ideas improved my btrfs backup script, which uses a sudo-refreshing loop to avoid re-prompting the user after a subvolume's backup takes longer than sudo's timeout.
Get root privileges once for all:
You can adjust this timeout by adding to /etc/sudoers
But it is much easier to run
The flexibility of sudo is widely under-estimated. This leads to very poor practices (like the
sudo su -
canon-ball surgery method).A much better method is to specificly allow the commands you intend to allow without use of a password:
You can optionally do this for specific users from specific hosts running as specific admin users. You can even prevent users from passing shell escapes as parameters. You can make sudo prevent the launched program to execute further applications dynamically etc. etc. You will want to read the man-page for sudoers (and be sure to read the procedures for editing this special file!).
Here is a small taste of things, (from here):
Here's a workaround:
This my way: