-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-key.sh
executable file
·47 lines (40 loc) · 1.09 KB
/
add-key.sh
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
#!/bin/bash
. /etc/farmconfig
if [ "$3" = "" ]; then
echo "usage: $0 <user-name> <file/inline> <key-material>"
exit 1
elif ! [[ $1 =~ ^[a-zA-Z0-9._-]+$ ]]; then
echo "error: parameter 1 not conforming user name format"
exit 1
elif [ "$2" != "file" ] && [ "$2" != "inline" ]; then
echo "error: invalid mode (should be either \"file\" or \"inline\")"
exit 1
fi
user=$1
mode=$2
if [ "`getent passwd $user`" = "" ]; then
exit 0
fi
if [ "$mode" != "file" ]; then
keytext="$3"
elif [ -f $3 ]; then
keytext="`head -n1 $3`"
else
echo "error: key $3 not found"
exit 0
fi
if ! [[ "$keytext" =~ ^ssh-[a-zA-Z0-9/@\ .:+=_-]+$ ]]; then
echo "error: given key \"$keytext\" is incomplete or invalid"
exit 0
fi
home=`getent passwd $user |cut -d: -f6`
if [ ! -f $home/.ssh/authorized_keys ] || ! grep -q "$keytext" $home/.ssh/authorized_keys; then
comment="`echo "$keytext" |cut -d' ' -f3-`"
if [ "$comment" != "" ]; then
echo "installing ssh key $comment for user $user"
else
echo "installing ssh key ${keytext: -12} for user $user"
fi
mkdir -p $home/.ssh
echo "$keytext" >>$home/.ssh/authorized_keys
fi