home · contact · privacy
0524a35f21b632b39a583d67a9702b8430f7b6a8
[config] / all_new_2018 / init_user_and_keybased_login / init_user_and_keybased_login.sh
1 #!/bin/sh
2 # This script turns a fresh server with password-based root access to
3 # one of only key-based access and only to new non-root account plom.
4 #
5 # CAUTION: This is optimized for a *fresh* setup. It will overwrite any
6 # pre-existing ~/.ssh/authorized_keys of user plom with one that solely
7 # contains the local ~/.ssh/id_rsa.pub, and also any old
8 # /etc/ssh/sshd_config.
9 #
10 # Dependencies: ssh, scp, sshpass, ~/.ssh/id_rsa.pub
11 set -e
12
13 # Ensure we have a server name as argument.
14 if [ $# -eq 0 ]; then
15     echo "Need server as argument."
16     false
17 fi
18 server="$1"
19
20 # Ask for root password only once, sshpass will re-use it then often.
21 stty -echo
22 printf "Server root password: "
23 read PW_ROOT
24 stty echo
25 printf "\n"
26 export SSHPASS="$PW_ROOT"
27
28 # Create user plom, and his ~/.ssh/authorized_keys based on the local
29 # ~/.ssh/id_rsa.pub; ensure the result has proper permissions and
30 # ownerships. Then disable root and pw login, and restart ssh daemon.
31 #
32 # This could be a line or two shorter by using ssh-copy-id, but that
33 # would require setting a password for user plom otherwise not needed.
34 sshpass -e scp ~/.ssh/id_rsa.pub root@"$server":/tmp/authorized_keys
35 sshpass -e ssh root@"$server" \
36         'useradd -m plom && '\
37         'mkdir /home/plom/.ssh && '\
38         'chown plom:plom /tmp/authorized_keys && '\
39         'chmod u=rw,go= /tmp/authorized_keys && '\
40         'mv /tmp/authorized_keys /home/plom/.ssh/'
41 sshpass -e scp sshd_config root@"$server":/etc/ssh/sshd_config
42 sshpass -e ssh root@"$server" 'service ssh restart'