Using sudo Without A Password

If you add a NOPASSWD directive in your sudoers file then you can, as you’d expect from its name, use those commands without a password. This is a pretty useful trick that allows you to set up sudo entries that allow commands to be run with different privileges from cron without requiring the setuid flag. However twice this week I’ve seen a similar question asked on mailing lists and I thought I’d stick this entry up, hope google indexes it and saves me from ever seeing it again. Yeah right.

When you use sudo and authenticate it sets a short timeout period in which if you use sudo again it won’t ask for your password. This is typically a useful feature (for interactive use anyway) but a couple of people seem to follow a series of events that go something like this: sudo visudo (add the NOPASSWD line). sudo “command I want in cron.” “Oh look, it worked. Now let me add a cronjob.” The next day they (hopefully) notice it didn’t work and then ask on a mailing list. Which I’m on.

Now it seems obvious but people don’t seem to realise that the trial run is pointless, the timestamp is still valid from when they ran sudo visudo and so sudo WILL NOT PROMPT FOR THE PASSWORD. In order to run a real test you need to use sudo -k to invalidate the timestamp and then rerun the command.

As a closing note adding a sudo -k to your .logout/.bash_logout file can also be a smart thing to do on some systems.