-
Notifications
You must be signed in to change notification settings - Fork 34
/
ssh-key-init
executable file
·64 lines (58 loc) · 1.88 KB
/
ssh-key-init
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
#!/bin/bash
usage() {
bin=$(basename $0)
echo >&2 "Usage: $bin [-r] [-c comment] [file]"
echo >&2 " or: $bin [-r] [-c comment] -m machine"
echo >&2
echo >&2 'Init new ed25519 ssh key using'
echo >&2 ' ssh-keygen without asking any stupid questions.'
echo >&2 'Default path is ~/.ssh/id_ed25519, under /var/lib/machines/... with -m.'
echo >&2 'Recursively creates dir for the thing with -m700.'
echo >&2 'Will refuse to overwrite files unless -r is specified.'
exit ${1:-0}
}
[[ "$1" = -h || "$1" = --help ]] && usage
replace= machine= comment=
while getopts "hrmc:" opt
do case "$opt" in
h) usage 0;;
r) replace=t;;
m) machine=t;;
c) comment=$OPTARG;;
*) echo >&2 -e "ERROR: Invalid option: -$OPTARG\n"; usage 1;;
esac; done
shift $((OPTIND-1))
p="$1"
[[ -n "$p" ]] || p="$HOME"/.ssh/id_ed25519
[[ -z "$machine" ]] || p=/var/lib/machines/"$p"/root/.ssh/id_ed25519
if [[ -z "$replace" && -e "$p" ]]; then
echo >&2 "ERROR: Specified key file already exists (use -r to replace): $p"
echo >&2
usage 1
fi
# Create directory components using uid/gid from the existsing part of the path
p_dir=$(dirname "$p")
[[ -e "$p_dir" ]] || {
[[ "$p_dir" =~ ^/ ]] || p_dir="$PWD/$p_dir"
IFS='/' read -ra p_dir_arr <<< "$p_dir"
p_dir= last_uid=0 last_gid=0
for c in "${p_dir_arr[@]}"; do
[[ -n "$c" ]] || continue
p_dir+=/"$c"
read uid gid < <(stat --dereference --format='%u %g' "$p_dir" 2>/dev/null)
if [[ $? -eq 0 ]]
then last_uid=$uid last_gid=$gid
else mkdir -m700 "$p_dir" && chown "${last_uid}:${last_gid}" "$p_dir" || exit 1
fi
done
}
read uid gid < <(stat --dereference --format='%u %g' "$p_dir" 2>/dev/null)
[[ $? -eq 0 ]] || exit 1
[[ -z "$replace" ]] || rm -f "$p"
ssh-keygen -q -t ed25519 -N '' -C "$comment" -f "$p" </dev/null
[[ $? -eq 0 && -e "$p" ]] || {
echo >&2
echo >&2 'ERROR: ssh-keygen has failed to create keyfile'
exit 1
}
chown "${uid}:${gid}" "$p"{,.pub} || exit 1