Bash Script to Setup a New User

Metin Cakircali

1 min read

Setting up a new user account can be a tedious and time-consuming process, especially when you need to perform a series of repetitive tasks such as creating a directory structure, setting permissions, and configuring various system settings. If you are an IT professional or system administrator, you've likely found yourself following the same steps over and over again. I recently had to setup Linux VMs for a hackathon and training for an external project, and I automated the process of user setup via the following bash script:

#!/bin/bash
function create_new_user()
{
  if [[ $# -eq 0 ]]; then
    echo "Usage: $ create_new_user metin ssh-ed25519 AAAAC3...5ut3 metin@foo"
    return 1
  fi

  NEW_USER="$1"
  shift
  USER_SSH_PUBKEY="$*"

  if [[ "$USER_SSH_PUBKEY" != "ssh-"* ]]; then
    echo "Wrong ssh key."
    return 1
  fi

  # create user
  adduser "$NEW_USER" || return 1

  # create new random password
  RAND_PASS=$(tr -dc '.a-zA-Z0-9' < /dev/urandom | fold -w 12 | head -n 1)

  echo "new username: $NEW_USER, pass: $RAND_PASS"

  # set user's password
  echo "$NEW_USER":"$RAND_PASS" | chpasswd

  # uncomment to give user sudo rights; add user to wheel group
  # usermod -aG wheel "$NEW_USER"

  # setup user's ssh public key
  su - "$NEW_USER" -c "umask 022 ; mkdir .ssh ; echo $USER_SSH_PUBKEY >> .ssh/authorised_keys"
}

Usage

The script expects user_name and ssh_public_key as input arguments.

$ create_new_user metin ssh-ed25519 AAAAC3...5ut3 metin@foo

Groups

Create new group

groupadd <group_name>

Add user to group

usermod -aG <group_name> <user_name>

Set user's primary group

usermod –g <new_primary_group> <user_name>

Remove user from group

gpasswd -d <user_name> <group_name>

Users

Create normal user

useradd <user_name>

Create system user

For system users, their login is disabled (/usr/sbin/nologin, unless --shell). A home is created (unless --no-create-home). Also, --group option creates group with same ID.

adduser --system --no-create-home --group <user_name>