I regularly log in to boxen via SSH, and run update and so forth as root, using sudo
.
I appreciate that sudo
asks for password after a certain time, in case I walk away from terminals or such. But as I already have entered either login password, or SSH key phrase, I would prefer sudo
not to ask for a password for the first n minutes after a login, but behave as if sudo had been executed successfully immediately after login.
Is this possible to configure so that no password is required for first invocation after login?
To make an example of the desired behaviour
ssh [email protected]
[~]$ sudo somecommand
[~]$ #no password asked.
[~]$ sudo somecommand #n minutes later
[sudo] password for foo:
Here's an idea for how it could be done. NOTE: this is a hack; use only if the words passwordless sudo make your eyebrows want to crawl all the way up your skull.
The premise is: we cannot pass login credentials to
sudo
. So the question is how to have aNOPASSWD
sudo for only the first few minutes of a login. We can do that by starting the login shell inNOPASSWD
mode, and spawning a background process in.bashrc
which after some minutes undoes theNOPASSWD
.Of course the script itself must be started with
NOPASSWD
sudo, or we would be still be prompted for a password. And the script must reinstate theNOPASSWD
rule when the bash session ends, so thatNOPASSWD
is set for the next login.Here is the script
$HOME/nopasswd-sudo
that will do that:On its first run (which must done from the command-line, not from
.bashrc
), the script creates the file/etc/sudoers.d/nopasswd-sudo-$USER
containing aNOPASSWD
wildcard for the logged in$USER
:Then on every login it starts and waits in the background until the passwordless time is up, after which it removes the file, and the next
sudo
will require a password.After that it waits indefinitely (actually, up to 12h, to prevent lingering orphans that missed their parent's HUP signal), or until its parent, the login shell, ends. Just before it exits, its EXIT trap recreates the
NOPASSWD
file.Tip for the adventurous: remember to always keep a separate root shell open while you mess with login scripts or
sudo
rules. You wouldn't be the first to lock yourself out.