Appending to a Remote File via SSH

Most LINUX users know how to copy and over­write a file from one server to anoth­er; but it can also be use­ful to direct­ly append to a file, with­out hav­ing to login to the remote server and make the changes man­u­al­ly. This does not appear to be pos­si­ble with the com­mon­ly used SCP util­i­ty; how­ev­er, there is a way to do this with SSH. Its actu­al­ly quite sim­ple.

Here’s the syn­tax:

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

So, let’s say you have an SSH pub­lic key that you want to add to a par­tic­u­lar server, or a num­ber of servers per­haps. Here is a com­mand you can use, at the com­mand line or in your scripts, to help accom­plish this task.

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

The end result of this, is that your RSA pub­lic key will be added to the end of the ~/.ssh/authorized_keys file on the tar­get 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 eas­i­ly be done with a bash for loop.

Here’s the syn­tax:

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

For exam­ple:

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;

1 thought on “Appending to a Remote File via SSH”

Leave a Reply

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