Bash – sudo testing for credentials

bashpasswordsudo

I have a working bash script, that may run from 0 to 8-9 minutes. It requires sudo if it finds a problem and needs to change permissions/ownership on a file. I do not want to wait for the sudo prompt, as this might be a few minutes into the run, so I do sudo -v at the beginning of the script.

If I expect the script to take long, I often walk over to the cafeteria. So some time ago I included a trap handler, that calls a function, that does sudo -k to drop my credentials. This way pressing Ctrl+C does not leave someone with access to sudo while I am not back yet. I do also call that function at the end of the script, in case the script terminates before I am back.

If I already did a sudo command before calling the script, sudo -v, it doesn't ask me for my credentials. That is nice.
Depending on where I start I know the script is not going to take long, and I wait for it to finish. If I started it after having just done a sudo command, every time I end up without sudo credentials after it finishes.

I did check the return value of sudo -v. On exit 0, that doesn't tell me if the credentials were already there (from before running the script) or that the password was typed in correctly just before. That doesn't help me to know if I should run sudo -k at the end or not.

I thought about making two versions of the script, one with and one without sudo -v/sudo -k, but I don't think that is a nice solution and I am bound to select the wrong version at times.

Is there a better way to solve this? Am I missing something?

Best Answer

You can use sudo -nv 2> /dev/null to get an exit value of 0 when the credentials were there without being prompted for the password.

I have something like that for running fdisk and dropping the credentials if the were not there to begin with. Combined with catching Ctrl+C you would get something like (I am not a good bash programmer!):

#! /bin/bash
# this only removes credentials if logging in at the start was necessary

reset_sudo()
{
if [ $SUDOCREDCACHED != 0 ] ; then 
  # drop credentials if acquired in script
  sudo -k
fi
}

Ctrl_C()
{
  reset_sudo
  exit 0
}

sudo -nv 2> /dev/null
SUDOCREDCACHED=$?
if [ $SUDOCREDCACHED != 0 ] ; then 
  # acquire credentials
  sudo -v 
  if [ $? != 0 ] ; then 
    exit 1
  fi
fi

trap Ctrl_C SIGINT
### your stuff here ###
reset_sudo
Related Question