Adds user, generates keys, disables (local) password and generates a putty file. - E.g.: adduser.sh user123
#!/bin/bash
#
##
BDIR="/home"
##
#
set -e
NUSER="$1"
NHOME="${BDIR}/$1"
bold=$(tput bold)
normal=$(tput sgr0)
red=$(tput setf 4)
green=$(tput setf 2)
if ! [ -x "$(command -v puttygen)" ]; then
echo "${red}puttygen missing. Install putty-tools first!${normal}"
exit 1
fi
if [ -z "$NUSER" ]; then
echo "${red}No user set!${normal}"
exit 1
fi
if [ -d "$NHOME" ]; then
echo "${red}User or home already exists!${normal}"
exit 1
fi
read -s -p "Password for key (empty for none): " password1
echo ""
if [ -n "$password1" ]; then
read -s -p "Repeat password: " password2
echo ""
if [ "$password1" != "$password2" ]; then
echo "${red}Password missmatch!${normal}"
exit 1
fi
fi
NPASS=$(tr -dc _A-Z-a-z-0-9 </dev/urandom | head -c 32 ; echo '')
useradd "${NUSER}" -d "${NHOME}" -m -p "${NPASS}" -s /bin/bash
passwd -q -l "${NUSER}"
mkdir -p "${NHOME}/.ssh"
ssh-keygen -t rsa -b 4096 -f "${NHOME}/.ssh/id_rsa" -N "${password1}" -C "${NUSER}@$HOSTNAME"
echo "Generate PuTTy file:"
puttygen "${NHOME}/.ssh/id_rsa" -o "${NHOME}/.ssh/id_rsa.ppk"
cat "${NHOME}/.ssh/id_rsa.pub" >> "${NHOME}/.ssh/authorized_keys"
chown -R "${NUSER}:${NUSER}" "${NHOME}"
chmod 700 "${NHOME}/.ssh"
chmod 600 "${NHOME}/.ssh/authorized_keys" "${NHOME}/.ssh/id_rsa" "${NHOME}/.ssh/id_rsa.pub" "${NHOME}/.ssh/id_rsa.ppk"
echo "${bold}Putty PPK:${normal} ${green}${NHOME}/.ssh/id_rsa.ppk${normal}"
echo "Done adding ${bold}${NUSER}${normal} at ${bold}${NHOME}${normal}."