Skip to content

Instantly share code, notes, and snippets.

@stringlytyped
Last active December 4, 2017 06:46
Show Gist options
  • Save stringlytyped/1c51bbd3c32c1edcea1c83fcb4d72205 to your computer and use it in GitHub Desktop.
Save stringlytyped/1c51bbd3c32c1edcea1c83fcb4d72205 to your computer and use it in GitHub Desktop.
Disable Root Access

Disable Root Access on a DigitalOcean Droplet

DigitalOcean droplets (aka VMs) are configured to use the system's root account directly when accessing them over SSH. This is different from AWS EC2's (arguably better) approach of creating a new user account (called "ec2-user") upon instance creation.

The script below will:

  1. create a new user account with root privileges,
  2. copy the authorized SSH keys from the root user, and
  3. disable SSH root login.

IMPORTANT: Be sure you've added your SSH keys to the root user's authorized_keys file before running this script, or you will be locked out of your droplet. If you added your SSH keys through DigitalOcean's web interface when creating the droplet, this has already been done for you.

This script has only been tested on Ubuntu 16.04. It should also work on Debian, but who knows. It probably won't work on other distributions.

To run this script, log into your droplet via SSH and enter the following:

bash <(curl -s https://gist.githubusercontent.com/stringlytyped/1c51bbd3c32c1edcea1c83fcb4d72205/raw/4d15d5fea163f173e11035559aee949bf3dcb6c1/disable_root.sh)

License: MIT

#!/bin/bash
echo "This script will disable SSH access to the root account and create a new sudo user to use instead."
echo "Please supply a username and password for the new user account."
read -p "Username: " username
read -sp "Password: " password
echo
adduser --disabled-login --gecos "" $username
echo "$username:$password" | chpasswd
usermod -aG sudo $username
mkdir /home/$username/.ssh
cp ~/.ssh/authorized_keys /home/$username/.ssh/authorized_keys
chown $username /home/$username/.ssh/authorized_keys
sed -i "s/PermitRootLogin yes/PermitRootLogin no/" /etc/ssh/sshd_config
systemctl reload sshd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment