Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

After reading this question, I know that I have to do

sudo sh -c 'ls -hal /root/ > /root/test.out'

to avoid the "Permission denied" error.

But when I do

ssh hostname sudo sh -c 'ls -hal /root/ > /root/test.out'

from another machine, I get

bash: /root/test.out: Permission denied

Why? And how can I get this to work?

Edit: There is the line

Defaults:<username>    !requiretty

before

<username> ALL= NOPASSWD: ALL

in /etc/sudoers.

I can do

ssh remote-machine 'sudo ls /'

without any problem. So I don't think it is a tty problem. Adding -t does not solve the problem.

share|improve this question

1 Answer 1

up vote 6 down vote accepted

The problem is that the quotes are interpreted and stripped by the local shell, not the remote one; you need one extra level:

ssh host sudo sh -c '"ls -hal /root/ > /root/test.out"'

The local shell will consume one level of quoting - the single quotes get "used up" here, ssh will get the arguments host, sudo, sh, -c, and "ls -hal /root/ > /root/test.out".

The remote shell consumes the next layer - the double quotes - and calls sudo with sh, -c, and ls -hal /root/ > /root/test.out.

Finally, the sh instance (running as root) is called with -c and ls -hal /root/ > /root/test.out - and parses that single argument as a normal commandline, evaluating the redirection.

To watch all of this, on the target system, try running sudo strace -f -e execve -p $(cat /var/run/sshd.pid).

share|improve this answer

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.