How to remotely write to a file using SSH

I can copy a file to a remote Linux machine with no problem with

scp file user@host: /pathtowrite_file

However, I'm having difficulty writing to a file from one linux machine to another. Here is what I attempted:

echo 'Some Text' > /remotefile.txt | ssh user@remotehost

The notice that I get is

stdin: is not a tty

At any rate, the file on the remote machine does not reflect the text sent 'Some Text'.


Solution 1:

You can use the "cat" command to create the remote file.

echo 'Some Text' | ssh user@remotehost -T "cat > /remotefile.txt"

The -T disables pseudo-terminal allocation and stops you from getting the message,

Pseudo-terminal will not be allocated because stdin is not a terminal.

Solution 2:

A bit shorter than the other answer:

ssh user@remotehost "echo Some Text > /remotefile.txt"

Solution 3:

It's also possible to use dd to append to a file. Maybe a bit obscure but useful if output redirection on the remote host isn't possible.

cat ~/.ssh/id_rsa.pub | ssh [email protected] 'dd of=.ssh/authorized_keys oflag=append conv=notrunc'

This example appends your public key to the authorized_keys file on the remote host.

(Source: http://www.rsync.net/resources/howto/ssh_keys.html)

Solution 4:

This will take the contents of your clipboard on a Mac and append it to the end of a file remotely:

pbpaste | ssh [email protected] 'cat >> ~/.ssh/authorized_keys'

This allows you to write (append) to the end of a file on a remote host:

echo "Append string to file" | ssh [email protected] 'cat >> ~/.ssh/authorized_keys'

Solution 5:

If has to be used multiple times might be easier to use this code. With "sshpass" tool, ssh won't prompt you for a password for each invocation of the script. (unless you need to keep it secret, then better off not use it)

For more info about sshpass : https://stackoverflow.com/questions/12202587/automatically-enter-ssh-password-with-script

#!/bin/bash

SCRIPT="echo 'nameserver 8.8.8.8' > /etc/resolv.conf"        

if [ "$#" -ne 1 ]; then
        echo "Wrong number of arguments. usage: prog dest_machine"
else
        sshpass -p "root" ssh -o StrictHostKeyChecking=no root@"$1" "${SCRIPT}"
fi