Quickly pushing your public SSH key to a server

I find myself needing to do this on a regular basis, so here’s a handy snippet for adding your public SSH key to a server’s authorized_keys file, assuming your public key is at “~/.ssh/id_rsa.pub” (the default).

ssh user@host "echo '`cat ~/.ssh/id_rsa.pub`' >> ~/.ssh/authorized_keys"

…or pop this in your ~/.profile file:

function push-key {
  ssh $1 "echo '`cat ~/.ssh/id_rsa.pub`' >> ~/.ssh/authorized_keys"

and run the following when you need to push your key to a server:

push-key user@host

Edit: Christopher mentions in the comments that you could use ssh-copy-id which is great on systems that support it, however it’s not available by default in OSX.

Published by


Hi, I am the Managing Director of SonicIQ Limited in the UK. I have been working in the web development industry since 1999 and have been running SonicIQ since 2001. Currently Ruby On Rails is my preferred development platform. I am experienced in designing with web standards, HTML5, CSS3 and Javascript.

5 thoughts on “Quickly pushing your public SSH key to a server”

  1. @kenny True, however I take my .profile wherever I go so for the sake of a one-liner I’d rather just use the simple bash function.

  2. I don’t have my key(s) necessarily in that file; also, for the first time that won’t work without .ssh already existing; a snippet from my script:

    # you can add extra options with $SSH_OPTS...
    # -o 'protocol 1'

    #cat $HOME/.ssh/id_dsa.pub \
    ssh-add -L \
    | ssh $SSH_OPTS $remote \
    "umask 077; [ -d .ssh ] || mkdir .ssh; cd .ssh; cat >> authorized_keys2; ls -l authorized_keys2"

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>