6

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.

0

1 Answer 1

7

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).

1
  • what if I want to have $1 inside the quotes? Jan 9, 2016 at 1:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .