How can I make sudo forget the password automatically after one command?

My problem is the following: I want to edit a file that is only readable by root. That’s why I use

sudo vim ~/thefile

I could type

sudo -K

after exiting vim, but I was hoping that there’s an option or something that makes sudo forget the password automatically. Of course I thought about editing the sudoers file and setting the timeout to 0, but I don’t want to change the settings in general. I also found nothing in the manpage…

Is there a way to do this?

If interesting: I’m using Ubuntu 12.04 and bash.

Asked By: caligula

||

See man sudoers; a timestamp_timeout setting is described there. Set it to 0 to make sudo always prompt for a password.

Answered By: 9000

There isn’t an option to sudo that will do exactly what you want, but you can make a shell function that will create a new command sudok, which will run the sudo command and then have sudo remove its cached credentials.

function sudok () { sudo "$@"; sudo -K; }

Add that line to your ~/.bashrc or ~/.bash_profile to make it permanent.

Answered By: Mark Plotnick

I’m pretty sure you just want sudo‘s little-k option,

sudo -k vim ~/thefile

which is documented to completely ignore your cachefile:

When used in conjunction with a command or an option that may require
a password, this option will cause sudo to ignore the user’s cached
credentials. As a result, sudo will prompt for a password (if one
is required by the security policy) and will not update the user’s
cached credentials.

Answered By: jthill
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.