/
ssh_auto.sh
executable file
·131 lines (93 loc) · 2.2 KB
/
ssh_auto.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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#! /bin/bash
usage()
{
cat << EOF
usage: $0 options
This script is built to populate ssh keys across a multi user environment.
OPTIONS:
-h Show this message
-m Script mode, accepts either 'test' or 'go'
-K Clear the known_hosts file
EOF
}
while getopts "h m:K" flag
do
case $flag in
h )
usage
exit 1
;;
m )
mode=$OPTARG
;;
K )
clearKnownHosts=1
;;
esac
done
if [[ -z $mode ]]
then
usage
exit 1
fi
sshAutoDir=$(dirname $0)
if [[ ! -f $sshAutoDir/authorized_keys ]]; then
usage
echo "Please copy authorized_keys.sample to authorized_keys, and edit"
exit 1
fi
if [[ ! -f $sshAutoDir/accounts_config ]]; then
usage
echo "Please copy accounts_config.sample to accounts_config, and edit"
exit 1
fi
acctArray=( `cat "$sshAutoDir/accounts_config"` )
echo "Starting key migration to user accounts:"
echo "---------------"
for acct in "${acctArray[@]}"
do
echo "Configuring $acct ..."
acctDir=/home/$acct
fullPath=$acctDir/.ssh/authorized_keys
dirWarn="Warning: user account directory not found, skipping!"
sshWarn="No .ssh folder found, one will be created.."
dirLocate="The user account directory has been located!"
if [[ $mode = "test" ]]; then
if [[ -d "$acctDir" ]]; then
echo $dirLocate
else
echo $dirWarn
fi
echo "cp authorized_keys $fullPath"
echo "chown $acct:$acct $fullPath"
echo "chmod 600 $fullPath"
if [[ $clearKnownHosts ]]; then
echo "> $acctDir/.ssh/known_hosts"
fi
elif [[ $mode = "go" ]]; then
if [[ -d "$acctDir" ]]; then
echo $dirLocate
if [[ ! -d "$acctDir/.ssh" ]]; then
echo $sshWarn
mkdir -p $acctDir/.ssh
chown $acct:$acct $acctDir/.ssh
chmod 700 $acctDir/.ssh
echo "Success"
fi
cp authorized_keys $fullPath
chown $acct:$acct $fullPath
chmod 600 $fullPath
if [[ $clearKnownHosts ]]; then
> $acctDir/.ssh/known_hosts
fi
else
echo $dirWarn
fi
else
usage
exit 1
fi
echo "$acct complete!"
echo "---------------"
done
echo "Process complete. You are now free to ssh about the server."