Skip to content

Instantly share code, notes, and snippets.

@sn0rk64
Created February 21, 2022 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sn0rk64/9fb828190fc8dbcecae576edaf671883 to your computer and use it in GitHub Desktop.
Save sn0rk64/9fb828190fc8dbcecae576edaf671883 to your computer and use it in GitHub Desktop.
Creating a new user with an SSH key on Linux

Creating a new user with an SSH key on Linux

First, create a new user with useradd:

sudo useradd -m -d /home/username -s /bin/bash username

Next, set the user’s password:

passwd username

Then, copy the contents of the user’s public key into /home/username/.ssh/authorized_keys. This is a plain text file where you can paste one public key per line.

After that, set up the correct permissions for both the .ssh directory and the authorized_keys file:

# ensure the directory ir owned by the new user
chown -R username:username /home/username/.ssh

# make sure only the new user has permissions
chmod 700 /home/username/.ssh
chmod 600 /home/username/.ssh/authorized_keys

Last, if you want the new user to have sudo access, be sure to add them to the sudo group:

sudo usermod -a -G sudo username

If you don’t have a sudo group, you can manually edit the /etc/sudoers file.

@sn0rk64
Copy link
Author

sn0rk64 commented Mar 21, 2022

#!/bin/bash
set -e

if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit
fi

echo 'Type user info'
read -p 'Username: ' username
read -p 'Public Key: ' pubkey
sudo useradd -m -d /home/$username -s /bin/bash $username

passwd $username
mkdir /home/$username/.ssh
touch /home/$username/.ssh/authorized_keys
echo $pubkey > /home/$username/.ssh/authorized_keys
chown -R $username:$username /home/$username/.ssh
chmod 700 /home/$username/.ssh
chmod 600 /home/$username/.ssh/authorized_keys
sudo usermod -a -G sudo $username

echo "User ${username} was successfully created"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment