Appending to a Remote File via SSH


Most LINUX users know how to copy and overwrite a file from one server to another; but it can also be useful to directly append to a file, without having to login to the remote server and make the changes manually. This does not appear to be possible with the commonly used SCP utility; however, there is a way to do this with SSH. Its actually quite simple.

Here’s the syntax:

cat localfile | ssh remoteuser@serveraddress "cat >> remotefile"

So, let’s say you have an SSH public key that you want to add to a particular server, or a number of servers perhaps. Here is a command you can use, at the command line or in your scripts, to help accomplish this task.

cat ~/.ssh/id_rsa.pub | ssh username@hostname.com "cat >> .ssh/authorized_keys"

The end result of this, is that your RSA public key will be added to the end of the ~/.ssh/authorized_keys file on the target server and you will then be able to login with SSH public/private key access.

Automating For a List of Servers

If you have a wide range of servers, to which you need to append a file, this can easily be done with a bash for loop.

Here’s the syntax:

for i in server1 server2 server3 server4; 
do 
    echo "sending file to $i";
    cat localfile | ssh -p portnumber user@$i "cat >> remotefile"; 
done;

For example:

for i in 192.168.1.101 192.168.1.102 192.168.1.103 192.168.1.104 192.168.1.105; 
do 
    echo "sending file to $i";
    cat ~/Desktop/id_rsa.pub | ssh -p 22 user@$i "cat >> .ssh/authorized_keys"; 
done;
,

2 responses to “Appending to a Remote File via SSH”

Leave a Reply

Your email address will not be published. Required fields are marked *