How can I use ssh to cat to a file in a remote Linux directory if the directory doesn't exist yet?

I'm trying to send the public id_rsa.pub file from my Mac to the ~/.ssh/authorized_keys directory in my home directory at Linux servers so I can then access without logging in each time.

From my Mac Terminal I'm using this command:

cat ~/.ssh/id_rsa.pub | ssh username@remoteserver 'cat >> ~/.ssh/authorized_keys'

This works if the remote ~/.ssh directory already exists, but doesn't otherwise. In that case I have to first login to the remote server, create the .ssh directory, then logout, and then run the above command. After that I can ssh to the remote server without logging in.

I need to do this for a few dozen servers, so I was wondering if there was a way of modifying the above command to create the remote .ssh directory if it wasn't already present.

Thanks,

doug


Use ssh-copy-id

In general ssh-copy-id takes care of nonexistent directory or file. Use it if you can; do not reinvent the wheel.


Without ssh-copy-id (for whatever reason)

On the remote side you run commands in a shell. Run more commands. Make sure the extra commands don't consume stdin before cat does (use </dev/null if needed). Here neither cd nor mkdir uses stdin, so this should work:

cat ~/.ssh/id_rsa.pub | ssh username@remoteserver '
   cd ~/ || exit
   mkdir -pm 700 .ssh
   cat >> .ssh/authorized_keys
   chmod 600 .ssh/authorized_keys
'

Notes:

  • -p makes mkdir not complain if ./.ssh already exists as a directory.
  • -m 700 sets the right mode from the very beginning.

The code can be improved. My main point is you are not limited to a single cat.