ssh-copy-id revision 248613
1180740Sdes#!/bin/sh
2180740Sdes
3248613Sdes# Copyright (c) 1999-2013 Philip Hands <phil@hands.com>
4248613Sdes#               2013 Martin Kletzander <mkletzan@redhat.com>
5248613Sdes#               2010 Adeodato =?iso-8859-1?Q?Sim=F3?= <asp16@alu.ua.es>
6248613Sdes#               2010 Eric Moret <eric.moret@gmail.com>
7248613Sdes#               2009 Xr <xr@i-jeuxvideo.com>
8248613Sdes#               2007 Justin Pryzby <justinpryzby@users.sourceforge.net>
9248613Sdes#               2004 Reini Urban <rurban@x-ray.at>
10248613Sdes#               2003 Colin Watson <cjwatson@debian.org>
11248613Sdes# All rights reserved.
12248613Sdes#
13248613Sdes# Redistribution and use in source and binary forms, with or without
14248613Sdes# modification, are permitted provided that the following conditions
15248613Sdes# are met:
16248613Sdes# 1. Redistributions of source code must retain the above copyright
17248613Sdes#    notice, this list of conditions and the following disclaimer.
18248613Sdes# 2. Redistributions in binary form must reproduce the above copyright
19248613Sdes#    notice, this list of conditions and the following disclaimer in the
20248613Sdes#    documentation and/or other materials provided with the distribution.
21248613Sdes#
22248613Sdes# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23248613Sdes# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24248613Sdes# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25248613Sdes# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26248613Sdes# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27248613Sdes# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28248613Sdes# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29248613Sdes# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30248613Sdes# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31248613Sdes# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32180740Sdes
33248613Sdes# Shell script to install your public key(s) on a remote machine
34248613Sdes# See the ssh-copy-id(1) man page for details
35180740Sdes
36248613Sdes# check that we have something mildly sane as our shell, or try to find something better
37248613Sdesif false ^ printf "%s: WARNING: ancient shell, hunting for a more modern one... " "$0"
38248613Sdesthen
39248613Sdes  SANE_SH=${SANE_SH:-/usr/bin/ksh}
40248613Sdes  if printf 'true ^ false\n' | "$SANE_SH"
41248613Sdes  then
42248613Sdes    printf "'%s' seems viable.\n" "$SANE_SH"
43248613Sdes    exec "$SANE_SH" "$0" "$@"
44248613Sdes  else
45248613Sdes    cat <<-EOF
46248613Sdes	oh dear.
47248613Sdes
48248613Sdes	  If you have a more recent shell available, that supports \$(...) etc.
49248613Sdes	  please try setting the environment variable SANE_SH to the path of that
50248613Sdes	  shell, and then retry running this script. If that works, please report
51248613Sdes	  a bug describing your setup, and the shell you used to make it work.
52248613Sdes
53248613Sdes	EOF
54248613Sdes    printf "%s: ERROR: Less dimwitted shell required.\n" "$0"
55248613Sdes    exit 1
56180740Sdes  fi
57248613Sdesfi
58248613Sdes
59248613SdesDEFAULT_PUB_ID_FILE=$(ls -t ${HOME}/.ssh/id*.pub 2>/dev/null | grep -v -- '-cert.pub$' | head -n 1)
60248613Sdes
61248613Sdesusage () {
62248613Sdes  printf 'Usage: %s [-h|-?|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname\n' "$0" >&2
63248613Sdes  exit 1
64248613Sdes}
65248613Sdes
66248613Sdes# escape any single quotes in an argument
67248613Sdesquote() {
68248613Sdes  printf "%s\n" "$1" | sed -e "s/'/'\\\\''/g"
69248613Sdes}
70248613Sdes
71248613Sdesuse_id_file() {
72248613Sdes  local L_ID_FILE="$1"
73248613Sdes
74248613Sdes  if expr "$L_ID_FILE" : ".*\.pub$" >/dev/null ; then
75248613Sdes    PUB_ID_FILE="$L_ID_FILE"
76248613Sdes  else
77248613Sdes    PUB_ID_FILE="$L_ID_FILE.pub"
78180740Sdes  fi
79248613Sdes
80248613Sdes  PRIV_ID_FILE=$(dirname "$PUB_ID_FILE")/$(basename "$PUB_ID_FILE" .pub)
81248613Sdes
82248613Sdes  # check that the files are readable
83248613Sdes  for f in $PUB_ID_FILE $PRIV_ID_FILE ; do
84248613Sdes    ErrMSG=$( { : < $f ; } 2>&1 ) || {
85248613Sdes      printf "\n%s: ERROR: failed to open ID file '%s': %s\n\n" "$0" "$f" "$(printf "%s\n" "$ErrMSG" | sed -e 's/.*: *//')"
86248613Sdes      exit 1
87248613Sdes    }
88248613Sdes  done
89248613Sdes  GET_ID="cat \"$PUB_ID_FILE\""
90248613Sdes}
91248613Sdes
92248613Sdesif [ -n "$SSH_AUTH_SOCK" ] && ssh-add -L >/dev/null 2>&1 ; then
93248613Sdes  GET_ID="ssh-add -L"
94180740Sdesfi
95180740Sdes
96248613Sdeswhile test "$#" -gt 0
97248613Sdesdo
98248613Sdes  [ "${SEEN_OPT_I}" ] && expr "$1" : "[-]i" >/dev/null && {
99248613Sdes        printf "\n%s: ERROR: -i option must not be specified more than once\n\n" "$0"
100248613Sdes        usage
101248613Sdes  }
102248613Sdes
103248613Sdes  OPT= OPTARG=
104248613Sdes  # implement something like getopt to avoid Solaris pain
105248613Sdes  case "$1" in
106248613Sdes    -i?*|-o?*|-p?*)
107248613Sdes      OPT="$(printf -- "$1"|cut -c1-2)"
108248613Sdes      OPTARG="$(printf -- "$1"|cut -c3-)"
109248613Sdes      shift
110248613Sdes      ;;
111248613Sdes    -o|-p)
112248613Sdes      OPT="$1"
113248613Sdes      OPTARG="$2"
114248613Sdes      shift 2
115248613Sdes      ;;
116248613Sdes    -i)
117248613Sdes      OPT="$1"
118248613Sdes      test "$#" -le 2 || expr "$2" : "[-]" >/dev/null || {
119248613Sdes        OPTARG="$2"
120248613Sdes        shift
121248613Sdes      }
122248613Sdes      shift
123248613Sdes      ;;
124248613Sdes    -n|-h|-\?)
125248613Sdes      OPT="$1"
126248613Sdes      OPTARG=
127248613Sdes      shift
128248613Sdes      ;;
129248613Sdes    --)
130248613Sdes      shift
131248613Sdes      while test "$#" -gt 0
132248613Sdes      do
133248613Sdes        SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
134248613Sdes        shift
135248613Sdes      done
136248613Sdes      break
137248613Sdes      ;;
138248613Sdes    -*)
139248613Sdes      printf "\n%s: ERROR: invalid option (%s)\n\n" "$0" "$1"
140248613Sdes      usage
141248613Sdes      ;;
142248613Sdes    *)
143248613Sdes      SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
144248613Sdes      shift
145248613Sdes      continue
146248613Sdes      ;;
147248613Sdes  esac
148248613Sdes
149248613Sdes  case "$OPT" in
150248613Sdes    -i)
151248613Sdes      SEEN_OPT_I="yes"
152248613Sdes      use_id_file "${OPTARG:-$DEFAULT_PUB_ID_FILE}"
153248613Sdes      ;;
154248613Sdes    -o|-p)
155248613Sdes      SSH_OPTS="${SSH_OPTS:+$SSH_OPTS }$OPT '$(quote "$OPTARG")'"
156248613Sdes      ;;
157248613Sdes    -n)
158248613Sdes      DRY_RUN=1
159248613Sdes      ;;
160248613Sdes    -h|-\?)
161248613Sdes      usage
162248613Sdes      ;;
163248613Sdes  esac
164248613Sdesdone 
165248613Sdes
166248613Sdeseval set -- "$SAVEARGS"
167248613Sdes
168248613Sdesif [ $# != 1 ] ; then
169248613Sdes  printf '%s: ERROR: Too many arguments.  Expecting a target hostname, got: %s\n\n' "$0" "$SAVEARGS" >&2
170248613Sdes  usage
171180740Sdesfi
172180740Sdes
173248613Sdes# drop trailing colon
174248613SdesUSER_HOST=$(printf "%s\n" "$1" | sed 's/:$//')
175248613Sdes# tack the hostname onto SSH_OPTS
176248613SdesSSH_OPTS="${SSH_OPTS:+$SSH_OPTS }'$(quote "$USER_HOST")'"
177248613Sdes# and populate "$@" for later use (only way to get proper quoting of options)
178248613Sdeseval set -- "$SSH_OPTS"
179248613Sdes
180248613Sdesif [ -z "$(eval $GET_ID)" ] && [ -r "${PUB_ID_FILE:=$DEFAULT_PUB_ID_FILE}" ] ; then
181248613Sdes  use_id_file "$PUB_ID_FILE"
182180740Sdesfi
183180740Sdes
184248613Sdesif [ -z "$(eval $GET_ID)" ] ; then
185248613Sdes  printf '%s: ERROR: No identities found\n' "$0" >&2
186180740Sdes  exit 1
187180740Sdesfi
188180740Sdes
189248613Sdes# populate_new_ids() uses several global variables ($USER_HOST, $SSH_OPTS ...)
190248613Sdes# and has the side effect of setting $NEW_IDS
191248613Sdespopulate_new_ids() {
192248613Sdes  local L_SUCCESS="$1"
193180740Sdes
194248613Sdes  # repopulate "$@" inside this function 
195248613Sdes  eval set -- "$SSH_OPTS"
196214979Sdes
197248613Sdes  umask 0177
198248613Sdes  local L_TMP_ID_FILE=$(mktemp ~/.ssh/ssh-copy-id_id.XXXXXXXXXX)
199248613Sdes  trap "rm -f $L_TMP_ID_FILE*" EXIT TERM INT QUIT
200248613Sdes  printf '%s: INFO: attempting to log in with the new key(s), to filter out any that are already installed\n' "$0" >&2
201248613Sdes  NEW_IDS=$(
202248613Sdes    eval $GET_ID | {
203248613Sdes      while read ID ; do
204248613Sdes        printf '%s\n' "$ID" > $L_TMP_ID_FILE
205180740Sdes
206248613Sdes        # the next line assumes $PRIV_ID_FILE only set if using a single id file - this
207248613Sdes        # assumption will break if we implement the possibility of multiple -i options.
208248613Sdes        # The point being that if file based, ssh needs the private key, which it cannot
209248613Sdes        # find if only given the contents of the .pub file in an unrelated tmpfile
210248613Sdes        ssh -i "${PRIV_ID_FILE:-$L_TMP_ID_FILE}" \
211248613Sdes            -o PreferredAuthentications=publickey \
212248613Sdes            -o IdentitiesOnly=yes "$@" exit 2>$L_TMP_ID_FILE.stderr </dev/null
213248613Sdes        if [ "$?" = "$L_SUCCESS" ] ; then
214248613Sdes          : > $L_TMP_ID_FILE
215248613Sdes        else
216248613Sdes          grep 'Permission denied' $L_TMP_ID_FILE.stderr >/dev/null || {
217248613Sdes            sed -e 's/^/ERROR: /' <$L_TMP_ID_FILE.stderr >$L_TMP_ID_FILE
218248613Sdes            cat >/dev/null #consume the other keys, causing loop to end
219248613Sdes          }
220248613Sdes        fi
221180740Sdes
222248613Sdes        cat $L_TMP_ID_FILE
223248613Sdes      done
224248613Sdes    }
225248613Sdes  )
226248613Sdes  rm -f $L_TMP_ID_FILE* && trap - EXIT TERM INT QUIT
227180740Sdes
228248613Sdes  if expr "$NEW_IDS" : "^ERROR: " >/dev/null ; then
229248613Sdes    printf '\n%s: %s\n\n' "$0" "$NEW_IDS" >&2
230248613Sdes    exit 1
231248613Sdes  fi
232248613Sdes  if [ -z "$NEW_IDS" ] ; then
233248613Sdes    printf '\n%s: WARNING: All keys were skipped because they already exist on the remote system.\n\n' "$0" >&2
234248613Sdes    exit 0
235248613Sdes  fi
236248613Sdes  printf '%s: INFO: %d key(s) remain to be installed -- if you are prompted now it is to install the new keys\n' "$0" "$(printf '%s\n' "$NEW_IDS" | wc -l)" >&2
237248613Sdes}
238214979Sdes
239248613SdesREMOTE_VERSION=$(ssh -v -o PreferredAuthentications=',' "$@" 2>&1 |
240248613Sdes                 sed -ne 's/.*remote software version //p')
241248613Sdes
242248613Sdescase "$REMOTE_VERSION" in
243248613Sdes  NetScreen*)
244248613Sdes    populate_new_ids 1
245248613Sdes    for KEY in $(printf "%s" "$NEW_IDS" | cut -d' ' -f2) ; do
246248613Sdes      KEY_NO=$(($KEY_NO + 1))
247248613Sdes      printf "%s\n" "$KEY" | grep ssh-dss >/dev/null || {
248248613Sdes         printf '%s: WARNING: Non-dsa key (#%d) skipped (NetScreen only supports DSA keys)\n' "$0" "$KEY_NO" >&2
249248613Sdes         continue
250248613Sdes      }
251248613Sdes      [ "$DRY_RUN" ] || printf 'set ssh pka-dsa key %s\nsave\nexit\n' "$KEY" | ssh -T "$@" >/dev/null 2>&1
252248613Sdes      if [ $? = 255 ] ; then
253248613Sdes        printf '%s: ERROR: installation of key #%d failed (please report a bug describing what caused this, so that we can make this message useful)\n' "$0" "$KEY_NO" >&2
254248613Sdes      else
255248613Sdes        ADDED=$(($ADDED + 1))
256248613Sdes      fi
257248613Sdes    done
258248613Sdes    if [ -z "$ADDED" ] ; then
259248613Sdes      exit 1
260248613Sdes    fi
261248613Sdes    ;;
262248613Sdes  *)
263248613Sdes    # Assuming that the remote host treats ~/.ssh/authorized_keys as one might expect
264248613Sdes    populate_new_ids 0
265248613Sdes    [ "$DRY_RUN" ] || printf '%s\n' "$NEW_IDS" | ssh "$@" "
266248613Sdes		umask 077 ;
267248613Sdes		mkdir -p .ssh && cat >> .ssh/authorized_keys || exit 1 ;
268248613Sdes		if type restorecon >/dev/null 2>&1 ; then restorecon -F .ssh .ssh/authorized_keys ; fi" \
269248613Sdes      || exit 1
270248613Sdes    ADDED=$(printf '%s\n' "$NEW_IDS" | wc -l)
271248613Sdes    ;;
272248613Sdesesac
273248613Sdes
274248613Sdesif [ "$DRY_RUN" ] ; then
275248613Sdes  cat <<-EOF
276248613Sdes	=-=-=-=-=-=-=-=
277248613Sdes	Would have added the following key(s):
278248613Sdes
279248613Sdes	$NEW_IDS
280248613Sdes	=-=-=-=-=-=-=-=
281248613Sdes	EOF
282248613Sdeselse
283248613Sdes  cat <<-EOF
284248613Sdes
285248613Sdes	Number of key(s) added: $ADDED
286248613Sdes
287248613Sdes	Now try logging into the machine, with:   "ssh $SSH_OPTS"
288248613Sdes	and check to make sure that only the key(s) you wanted were added.
289248613Sdes
290248613Sdes	EOF
291248613Sdesfi
292248613Sdes
293248613Sdes# =-=-=-=
294