Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm not sure if sudo supports so, I want to execute a command, only if this command is configured as NOPASSWD, that is, if the command can be run without password, run it; Otherwise quit directly.

So far the only option seems to be listing all available commands with sudo -l and parse the output manually, that looked dirty.

Are there any alternatives?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Not very pretty, but short of parsing sudo -l as you're doing I don't know an alternative: simply run your command with the -n switch:

The -n (non-interactive) option prevents sudo from prompting the user for a password. If a password is required for the command to run, sudo will display an error message and exit.

Example:

me$ sudo -l 
User me may run the following commands on this host:
    (ALL) NOPASSWD: /usr/bin/vim
    (ALL) /usr/bin/nano
me$ sudo -n nano /etc/hosts
sudo: a password is required
me$ echo $?
1
me$ sudo -n vim /etc/hosts
# :q
me$ echo $?
0

Problem with this is that you can't tell directly from the exit code if sudo failed because it required a password, or if the command you ran failed. So you'll need to parse the output. (Fortunately the error message is static, so that shouldn't be too hard. Beware of localization though.)

share|improve this answer
    
+1 for localization! –  warl0ck Mar 31 '13 at 7:04
2  
I would like to add that allowing vim as root without password is horrible security-wise. –  David Kohen Mar 31 '13 at 9:07
    
Indeed. One can bring up a root shell with an instance of vim running as root by using the :sh command. Also, one could easily modify a root-owned script to start a root shell. Also be careful when running less as root, which allows users to bring up root shell prompts like so: :!sh. –  paraxor Mar 31 '13 at 13:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.