Upload SSH keys to server for easier login

Bash script for uploading SSH keys to a server. If the key doesn’t have a password, it means passwordless login. Sweet.

# Upload SSH keys to server
function upload_ssh_keys () {
  if [ "$1" != "" ]
  then
    host=$1
    port=`echo -n $host | cut -d: -f 2`
    host=`echo -n $host | cut -d: -f 1`

    echo "Using $host as host"
    echo "Using $port as port"

    port_text=""
    if [ "$port" != "$host" ]
    then
      port_text=" -p $port"
    fi


    cat ~/.ssh/id_rsa.pub | ssh $port_text $host "mkdir -p .ssh; touch .ssh/authorized_keys; cat - >> .ssh/authorized_keys; chmod 700 .ssh; chmod 600 .ssh/authorized_keys"
    echo "Key(s) uploaded to $host $port_text"
  else
    echo "'$host' is no valid host. Try upload_ssh_keys user@hostname or upload_ssh_keys user@hostname:port"
  fi
}

Pair this with proper entries in `.ssh/config` and it’ll be even easier, like so:

Host [whatever-you-want-the-alias-to-be]
    User [USERNAME]
    Hostname [SERVER IP/HOSTNAME]

At bash, merely login like so:

$ ssh SERVERNAME

Leave a Reply

Your email address will not be published.
Required fields are marked.
Allowed HTML: <blockquote cite=""> <cite> <code> <em> <q cite=""> <strong> <span lang=""> <p>