I'm trying to run a command as root (via sudo) on a remote server, and capture stdout (but not stderr) into a file.

eg. Something like this:

ssh user@remote "cat /root/file.tar | gzip" > root-file.tar.gz

Except I need to be root on the remote:

ssh user@remote "sudo cat /root/file.tar | gzip" > root-file.tar.gz

root has no password and can't be logged in as, so I can't use su or ssh root@server.

When I try the above command, I get:

$ ssh user@remote "sudo cat /root/file.tar | gzip" > root-file.tar.gz
sudo: no tty present and no askpass program specified

I added -t so that ssh allocates a tty, but then root-file.tar.gz gets the output from sudo (and gzip, but I can --force), so I guess it's capturing remote stdout and stderr into local stdout:

$ ssh -t user@remote "sudo cat /root/file.tar | gzip" > root-file.tar.gz

$ cat root-file.tar.gz
gzip: compressed data not written to a terminal. Use -f to force compression.
For help, type: gzip -h
[sudo] password for user:

I've white-listed specific commands using NOPASSWD in sudoers, which works well for regularly-occurring scripts, but I find that I want to do this sort of thing occasionally with different arbitrary commands so I can't be forever adding NOPASSWD.

  • +1. But the root has no password line seems little misleading. Did you by any chance mean to say the root has no login prompt?
    – Ramesh
    Sep 29, 2014 at 14:23

1 Answer 1


You can pass the -S option[0] to sudo, so it can accept the password from stdin instead of requiring a tty.

This will probably cause your password to echo to the terminal, so try turning echo off yourself:

$ stty -echo; ssh user@remote "sudo cat /root/file.tar | gzip" > root-file.tar.gz
[sudo] password for user:

[0] From the manpage: The ‑S (stdin) option causes sudo to read the password from the standard input instead of the terminal device. The password must be followed by a newline character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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