SSH passwordless login: ssh-copy-id

To log on to a remote machine without the need to enter a password each time, you need to copy your SSH public key to the remote machine and add it to the .ssh/authorized_keys file. First, generate a keypair using ssh-keygen, then use this script to copy your key to the remote host:

#!/bin/sh

# Shell script to install your public key on a remote machine
# Takes the remote machine name as an argument.
# Obviously, the remote machine must accept password authentication,
# or one of the other keys in your ssh-agent, for this to work.

ID_FILE="${HOME}/.ssh/id_rsa.pub"

if [ "-i" = "$1" ]; then
  shift
  # check if we have 2 parameters left, if so the first is the new ID file
  if [ -n "$2" ]; then
    if expr "$1" : ".*\.pub" > /dev/null ; then
      ID_FILE="$1"
    else
      ID_FILE="$1.pub"
    fi
    shift         # and this should leave $1 as the target name
  fi
else
  if [ x$SSH_AUTH_SOCK != x ] && ssh-add -L >/dev/null 2>&1; then
    GET_ID="$GET_ID ssh-add -L"
  fi
fi

if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
  GET_ID="cat ${ID_FILE}"
fi

if [ -z "`eval $GET_ID`" ]; then
  echo "$0: ERROR: No identities found" >&2
  exit 1
fi

if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
  exit 1
fi

{ eval "$GET_ID" ; } | ssh ${1%:} "umask 077; test -d .ssh || 
mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1

cat < 

Mac OS users can copy this script to /usr/bin to and make it executable (chmod +x ssh-copy-id) to make it accessible system-wide.


Posted

in

by

Tags:

Comments

One response to “SSH passwordless login: ssh-copy-id”

  1. You can also use the following one-liner in absence of “ssh-copy-id”:

    ssh remoteuser@remotehost “echo $(cat locateion_of_your_id_rsa.pub) >> /home/remoteuser/.ssh/authorized_keys”

    To generate keys, use “ssh-keygen” as suggested above to get “id_rsa.pub”.