Setup Script for Ubuntu Server on DigitalOcean

Lately, I've been using DigitalOcean a lot in order to follow projects, such as setting up an Elasticsearch instance, and to play around with technology in general. Once you create different droplets on a weekly basis, you pretty quickly get the feeling that you are doing the same things over and over again.

Because I abhor manual labor, I created a simple script that helps me set up the server. Here it is:


echo "[*] Adding a new user"
echo "Please type in the username you want to add: "
read username

sudo adduser $username

echo "[*] Adding $username to the sudo group"
sudo usermod -aG sudo $username

echo "[*] Creating the .ssh directory"
sudo mkdir /home/$username/.ssh

echo "[*] Changing permissions on the .ssh directory"
sudo chmod 700 /home/$username/.ssh

echo "[*] Copying the SSH key to the user's home directory"
sudo cp ~/.ssh/authorized_keys /home/$username/.ssh/authorized_keys

echo "[*] Changing the file permissions and ownership on the authorized_keys file"
sudo chmod 600 /home/$username/.ssh/authorized_keys
sudo chown $username:$username /home/$username/.ssh
sudo chown $username:$username /home/$username/.ssh/authorized_keys

echo "[*] Getting our external IP address"

# Thanks, Cyberciti:
ipaddress=`ifconfig | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1 }'`

echo "[*] Setting up firewall."
while true
 read -r -p "Do you want to enable the firewall? [Y/n] " input
 case $input in
 sudo ufw allow OpenSSH && sudo ufw enable
 echo "Firewall remains deactivated."
 echo "Invalid input..."

echo "[*] Checking whether sshd setup allows for SSH access via password."
passwordauthentication=`cat /etc/ssh/sshd_config | grep 'PasswordAuthentication ' | awk ' { print $2 } '`
case "$passwordauthentication" in 
  y|Y ) echo "[*] Does not allow for password authentication. SSH config correctly set up. ";;
  n|N ) echo "[*] Allows for password authentication. Please change line 'PasswordAuthentication yes' in /etc/ssh/sshd_config to 'PasswordAuthentication no'";;
  * ) echo "invalid";;

echo "[*] Done with the setup. Try logging in the new user account directly using 'ssh $username@$ipaddress'"

The script assumes that you already have an SSH key set up for the root login. Typically, when you create a new droplet, it will let you automatically copy a key that you've used for a previous droplet.

Let me know if you have any things to change.

I will be posting it on Github soon as well.