# Edit the following variables to taste:
remote_username='my_remote_user'
remote_machine='remote.example.com'   # ip or fqdn
local_machine='12.0.0.1'    # ip or fqdn
local_ssh_dir='/home/my_local_user/.ssh'
remote_ssh_dir='/home/my_remote_user/.ssh'
output_key_file='id_rsa'
pub_key=$output_key_file'.pub'
auth_keys='authorized_keys2' # May need to be 'authorized_keys'
comment="$username@$local_machine"
passphrase=''  # for unattended rsync stuff, leave this blank


# Paste the stuff above into a BASH shell, then do the same
# with the commands, below.  Note that you can prepend each of
# the following commands with 'echo ' (without quotes) to see
# the command with the variables filled in.


# Generate the public/private key pair
ssh-keygen -q -N "$passphrase" -C "$comment" -f $local_ssh_dir/$output_key_file

# Make the .ssh dir on the remote machine if it doesn't already exist
ssh $remote_username@$remote_machine "mkdir $remote_ssh_dir; chmod 0700 $remote_ssh_dir"


# Append the public key to the remote machine's list of authorized keys
cat $local_ssh_dir/$pub_key | ssh $remote_username@$remote_machine "cat >> $remote_ssh_dir/$auth_keys && chmod 600 $remote_ssh_dir/$auth_keys"

# Test that it worked
ssh $remote_username@$remote_machine "tail -n 1 $remote_ssh_dir/$auth_keys"