How to pipe a remote file to stdout over scp or sftp?

34,244

Solution 1

Curl can display the file the same way cat would. No need to delete the file since it simply displayed the output unless you tell it to do otherwise.

curl -u username:password sftp://hostname/path/to/file.txt

If you use public key authentication:

curl -u username: --key ~/.ssh/id_rsa --pubkey sftp://hostname/path/to/file.txt

If you use the default locations, then --key and --pubkey can be omitted:

curl -u username: sftp://hostname/path/to/file.txt

The user name can also be a part of the URL, so the final result looks very close to the ssh command:

curl sftp://username@hostname/path/to/file.txt

Solution 2

For people who can run scp, you can do this:

scp remotehost:/path/to/remote/file /dev/stdout
Share:
34,244

Related videos on Youtube

Rob W
Author by

Rob W

Distro: ArchLinux Related SE accounts: - Stack Overflow - Ask ubuntu

Updated on September 18, 2022

Comments

  • Rob W
    Rob W almost 2 years

    Using ssh, it is easy to print the contents of a file using

    ssh host 'cat file.txt'
    

    When ssh is disabled, and only SFTP is enabled, running the previous command gives the following error:

    This service allows sftp connections only.

    To work-around this issue, I could create a temporary file using scp or sshfs (as shown below), but that looks really ugly. What is the proper way to print the contents of a remote file when SSH is disabled?

    mkdir tmpdir
    sshfs host: tmpdir
    cat tmpdir/file.txt
    fusermount -u tmpdir
    
    # This does not work! scp -v host:file.txt . shows
    # "Sink: This service allows sftp connections only."
    scp host:file.txt .
    cat file.txt
    rm file.txt
    
  • Rob W
    Rob W almost 10 years
    Thanks, exactly what I was looking for! I have edited your answer to expand on public-key authentication, it turns out that the syntax is very similar to the ssh/sshfs syntax. If the curl command fails with "curl: (51) SSL peer certificate or SSH remote key was not OK", just add the -k flag (--insecure).
  • Rob W
    Rob W almost 10 years
    Neither method works. The first one is equivalent to the one-liner sftp username@hostname:/path/to/file.txt /dev/stdout and results in "Couldn't write to "/dev/stdout": Illegal seek". The second command fails, and shows the error that is shown at the bottom of my question.
  • Kenster
    Kenster almost 10 years
    The SFTP form works fine for me. It may depend on what version of the ssh software you're using. Regarding scp, I did say "if scp works". You established in your question that the server was not permitting you to perform scp, so naturally the scp command would fail for you.
  • Rob W
    Rob W almost 10 years
    ssh -V gives OpenSSH_6.6.1p1, OpenSSL 1.0.1h 5 Jun 2014. scp fails because it uses ssh under the hood, and ssh is disabled (as a security measure, see e.g. serverfault.com/questions/354615/allow-sftp-but-disallow-ssh‌​)