Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I want to check if a file exists [ -f /path/to/file ] using another user.

So, I added:

USER1        ALL=(USER2)     /bin/mkdir, /usr/bin/git, /bin/echo

to the sudoers file.

The problem is, when I try to execute

USER1:~$ sudo -u USER2 [ -f /path/to/file ] && echo "1"

I get the following:

Sorry, user USER1 is not allowed to execute '/usr/bin/[ -f /path/to/file ]' as USER2 on localhost.

So, the question here is: How do I enable that on the sudoers file?


Solution

I added /usr/bin/test to the sudoers file, and instead of going with this:

USER1:~$ sudo -u USER2 [ -f /path/to/file ] && echo "1"

I actually used:

USER1:~$ sudo -u USER2 /usr/bin/test -f /path/to/file && echo "1"
share|improve this question

1 Answer 1

up vote 3 down vote accepted

You're trying to execute /usr/bin/[ but haven't given the user permission to. There are two ways you could do this.

The first is to allow the user to execute /usr/bin/[ (which is the test program). This would allow the user to perform any kind of test on any file. You can also use test instead of [, which may be more obvious as to what's happening.

USER1   ALL=(USER2) /bin/mkdir, /usr/bin/git, /bin/echo, /usr/bin/[, /usr/bin/test

And then run:

sudo -u USER2 [ -f /path/to/file ] && echo "1"

or

sudo -u USER2 test -f /path/to/file && echo "1"

The second option is to write a wrapper script and allow the user to execute that. For example, with the following in /usr/local/bin/exists:

#!/bin/sh
set -e
[ -f "$1" ]

And this in /etc/sudoers:

USER1   ALL=(USER2) /bin/mkdir, /usr/bin/git, /bin/echo, /usr/local/bin/exists

The user could run:

sudo -u USER2 /usr/local/bin/exists /path/to/file && echo "1"
share|improve this answer
    
I tried option 1, and still the same error: Sorry, user USER1 is not allowed to execute '/usr/bin/[ -f /path/to/file ]' as USER2 on localhost.. And I want to avoid the second option, as I don't want to create another file to run that. There's any bits missing on the first option? I also tried /usr/bin/[ .* and it didn't work. –  dmmd Jun 20 '12 at 5:00
    
Although your answer didn't solve the problem, it pointed me to the right direction. If someone needs the final solution, please refer to the bottom of my question. –  dmmd Jun 20 '12 at 5:19
    
@jlcd Strange, it works for me. I've added that method to my answer. –  mgorven Jun 20 '12 at 5:38
    
Right, thanks :) –  dmmd Jun 20 '12 at 5:41

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.