-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathssh-gen-copy-key
executable file
·78 lines (69 loc) · 1.93 KB
/
ssh-gen-copy-key
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env bash
bbbs_user_name=borg
bbbs_user_home=$(getent passwd "$bbbs_user_name" | cut -d: -f6)
usage() {
echo "usage: $0 [-h|--help] [-g|--generate] -k|--key-name host_key_name [-c|--copy -u|--user user_to_add_key] -- ssh_arguments"
exit
}
if [ $# = 0 ] ; then
usage
fi
while [ "$#" -gt 0 ]
do
case "$1" in
-g|--generate)
DO_GEN=1
shift 1
;;
-c|--copy)
DO_COPY=1
shift 1
;;
-u|--user)
COPY_USER="$2"
shift 2
;;
-k|--key-name)
KEY_NAME="$2"
shift 2
;;
-h|--help)
usage
;;
--)
shift
break
;;
-*)
printf "\n%s: ERROR: invalid option (%s)\n\n" "$0" "$1"
usage
;;
esac
done
#eval set -- "$SSH_ARGS"
# https://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash
if [ -z ${KEY_NAME:+x} -o '(' ! -z ${COPY_USER:+x} -a -z ${@:+x} ')' ]; then
printf '%s: ERROR: Missing arguments.\n\n' >&2
usage
fi
pushd "$bbbs_user_home" > /dev/null
if [ ${DO_GEN:-0} -eq 1 ]; then
echo "-- Generating key pair"
# https://security.stackexchange.com/questions/50878/ecdsa-vs-ecdh-vs-ed25519-vs-curve25519
#ssh-keygen -b 4096 -C "Borg server ($(hostname))"
ssh-keygen -t ed25519 -N '' -C "Borg server ($(hostname --fqdn))" -f "ssh/key_${KEY_NAME}"
chown --recursive --reference "$bbbs_user_home" "ssh/"
fi
if [ ${DO_COPY:-0} -eq 1 ]; then
echo "-- Adding public key to authorized_keys on client (for user $COPY_USER)"
# https://github.com/andrewpile/ssh-copy-id/blob/master/ssh-copy-id
cat "ssh/key_${KEY_NAME}.pub" | ssh -F "${bbbs_user_home}/ssh/config" -o UserKnownHostsFile="${bbbs_user_home}/ssh/known_hosts" "$@" -- \
"umask 077 ;" \
"if [ ! -d ~$COPY_USER ]; then echo 'Home for $COPY_USER not found'; exit 1; fi;" \
"cd ~$COPY_USER; test -d .ssh || mkdir .ssh ;" \
"cat >> .ssh/authorized_keys ;" \
"chown --recursive --reference ~$COPY_USER .ssh ;" \
"echo Ok"
chown --recursive --reference "$bbbs_user_home" "ssh/known_hosts"
fi
popd > /dev/null