home · contact · privacy
Fix broken symlink script.
[config] / all_new_2018 / 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, properly
11 # configured sshd_config file in reach.
12 set -e
13
14 # Location auf a sshd_config with "PermitRootLogin no" and
15 # "PasswordAuthentication no".
16 system_path_sshd_config='/etc/ssh/sshd_config'
17 config_tree_prefix="${HOME}/config/all_new_2018/linkable_etc_files/server/"
18 local_path_sshd_config="${config_tree_prefix}""${system_path_sshd_config}"
19
20 # Ensure we have a server name as argument.
21 if [ $# -eq 0 ]; then
22     echo "Need server as argument."
23     false
24 fi
25 server="$1"
26
27 # Ask for root password only once, sshpass will re-use it then often.
28 stty -echo
29 printf "Server root password: "
30 read PW_ROOT
31 stty echo
32 printf "\n"
33 export SSHPASS="${PW_ROOT}"
34
35 # Create user plom, and his ~/.ssh/authorized_keys based on the local
36 # ~/.ssh/id_rsa.pub; ensure the result has proper permissions and
37 # ownerships. Then disable root and pw login by copying over the
38 # sshd_config and restart ssh daemon.
39 #
40 # This could be a line or two shorter by using ssh-copy-id, but that
41 # would require setting a password for user plom otherwise not needed.
42 sshpass -e scp ~/.ssh/id_rsa.pub root@"${server}":/tmp/authorized_keys
43 sshpass -e ssh root@"${server}" \
44         'useradd -m plom && '\
45         'mkdir /home/plom/.ssh && '\
46         'chown plom:plom /tmp/authorized_keys && '\
47         'chmod u=rw,go= /tmp/authorized_keys && '\
48         'mv /tmp/authorized_keys /home/plom/.ssh/'
49 sshpass -e scp "${local_path_sshd_config}" root@"${server}":"${system_path_sshd_config}"
50 sshpass -e ssh root@"${server}" 'service ssh restart'