The process of adding many users to a new Linux system can get tedious, especially if it is involved. So, let’s replace the process with a simple shell script.

For this example, public keys are the only allowed login method. Password login is disabled, so the password is not set. The first step is to run set -e to stop the script on any errors. Next assign readable variable names, and check they aren’t null. Next the user is created, and as the user the public keys are setup.

The actual script this is based on is more complex, but this gives an example of what is possible.

!/bin/bash
# Stop on any errors
set -e

NEWUSER=$1
USERPUBKEY=$2

if [ -z "$NEWUSER" ]; then
        echo "Username required"
        exit 1;
fi

if [ -z "$USERPUBKEY" ]; then
        echo "Public key required - Enclose argument in quotes!"
        exit 1;
fi

#1.) Create a new user.
useradd -d /home/$NEWUSER -s /bin/bash -m $NEWUSER

#2.) Create a local public/private key pair as the user.
su - -c "ssh-keygen -q -t rsa -f ~/.ssh/id_rsa -N ''" $NEWUSER

#3.) Create an authorized_keys file with their external public key,
su - -c "echo $USERPUBKEY > .ssh/authorized_keys" $NEWUSER

#4.) Adjust the authorized_keys permissions
su - -c "chmod 600 .ssh/authorized_keys" $NEWUSER

#5.) More steps?