This script demonstrates security best practices for creating administrative users on Linux systems. By combining SSH key authentication with passwordless sudo access, you eliminate password-based vulnerabilities while maintaining convenient administrative access.

Why this approach is best practice:

  • Eliminates password attacks: No password means no brute force, dictionary, or credential stuffing attacks
  • Strong authentication: SSH keys provide cryptographically strong authentication (typically 2048+ bit RSA or Ed25519)
  • Audit trail: SSH key authentication provides better logging and accountability
  • Convenience: No need to type passwords for sudo operations during administrative tasks
  • Scalability: Easy to revoke access by removing the public key

Security considerations:

  • Ensure your private key is protected with a strong passphrase
  • Store private keys securely and never share them
  • Regularly rotate SSH keys
  • Consider using shorter-lived certificates instead of permanent keys for high-security environments

The Script

First set the USERNAME variable to the new user’s name:

lonewanderer@debian:~ USERNAME=newusername

Then run the following commands (all at once). They will:

  • Create the user account
  • create the .ssh directory in the new users home folder and set appropriate permissions
  • ask for the user’s public key and write it to the correct file
  • add the user to the drop-in sudo config for passwordless authentication
# create a new user without password, skipping interactive prompts
sudo adduser --disabled-password --gecos "" $USERNAME

# create ssh profile folder and set permissions
sudo mkdir -p /home/$USERNAME/.ssh
sudo chmod 700 /home/$USERNAME/.ssh

# prompt for public key
echo "Please paste the public key for $USERNAME:"
read -r PUBLIC_KEY

# add the public key to authorized_keys
echo "$PUBLIC_KEY" | sudo tee /home/$USERNAME/.ssh/authorized_keys > /dev/null

sudo chmod 600 /home/$USERNAME/.ssh/authorized_keys
sudo chown -R $USERNAME:$USERNAME /home/$USERNAME/.ssh

echo "$USERNAME ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/$USERNAME > /dev/null && sudo chmod 440 /etc/sudoers.d/$USERNAME

echo "User $USERNAME created successfully with SSH key authentication and passwordless sudo access."