June 15, 2011

rcat - Concatenate to a remote file

I have recently had the need to do something like "cat file1 >> file2", but where file2 sits on a remote machine. Most users can also think of the most common use case for this, when you have to concatenate your id_rsa.pub (public key) to the authorized_keys list on another machine. I came up with a small hack to do the same which uses rsync behind the scenes, here is how it looks :


#!/bin/bash
#script to remotely concatenate files.
#args -> rcat file1 file2 
#concatenates file1 to remote file file2
local_file=$1
username=`echo $2 | sed 's/:/\t/g' | awk '{print $1}' | sed 's/@/\t/g' | awk '{print $1}'`
remote_host=`echo $2 | sed 's/:/\t/g' | awk '{print $1}' | sed 's/@/\t/g' | awk '{print $2}'`
remote_file=`echo $2 | sed 's/:/\t/g' | awk '{print $2}'`
temp_folder="/tmp/$#/"
file_name=`echo $local_file  | sed 's/\// /g' | awk '{print $NF}'`
if [ -d $local_file ] ;
then
echo "Cannot cat a directory"
echo "Qutting"
exit
fi
rsync $local_file $username@$remote_host:$temp_folder/
ssh $username@$remote_host "cat $temp_folder/$file_name >> $remote_file && rm -rf $temp_folder/"
echo "done"
echo "rcat $local_file $username@$remote_host:$remote_file"

the bad thing about the script right now is that it will ask for authentication twice. But the good thing is that you need not manually sync the files and then concatenate them. The syntax for the remote file is similar to rsync, scp etc. 
rcat [local_file] [username]@[remote_host]:[remote_file]

[EDIT]
There is a utility "ssh-copy-id" to copy the public keys across systems.