Have you ever set up a fresh Debian or Ubuntu server, only to be faced with a long checklist of essential post-installation tasks? Worry no more! In this tutorial, we will introduce a Bash script called DebPostInstall. Whether you're new to Linux or an experienced system administrator, the DebPostInstall script can help you automate essential post-installation tasks on a newly installed minimal Debian, or Ubuntu server.
By the end of this tutorial, you'll have a solid understanding of how to use the DebPostInstall script to quickly and efficiently set up a secure and well-configured Debian-based server. Let's get started!
Table of Contents
DebPostInstall: Debian and Ubuntu Post Install Bash Script
DebPostInstall is a simple Bash script to automate important post installation tasks in a newly installed minimal Debian or Ubuntu server.
The DebPostInstall script will do the following tasks:
- Creating a new user with sudo privileges.
- Adding a public SSH key for secure access.
- Disabling password authentication and root login for enhanced security.
- Setting up the Uncomplicated Firewall (UFW) to protect your server.
- Creating a swap file to optimize system performance.
- Configuring the timezone and time synchronization for accurate timekeeping.
Of course, you could manually do these tasks one by one. It is not big deal, but why bother? The DebPostInstall script will help you to automate these tasks.
Here's the contents of the script:
#!/usr/bin/env bash
# ------------------------------------------------------------------
# Script Name: DebPostInstall
# Description: A Bash Script to automate essential
# post-installation tasks on Debian and Ubuntu
# Website: https://gist.github.com/ostechnix
# Version: 1.0
# Usage: sudo ./debpostinstall.sh
# ------------------------------------------------------------------
# Update the system
echo "Updating the system..."
apt-get update && apt-get full-upgrade -y
apt-get autoremove -y && apt-get autoclean -y
# Install necessary packages
echo "Installing necessary packages..."
apt-get install -y sudo openssh-server ufw systemd-timesyncd vim htop net-tools curl wget git
# Prompt for username
read -p "Enter the username for the new user: " USERNAME
# Check if the user already exists
if id "$USERNAME" &>/dev/null; then
echo "User $USERNAME already exists. Skipping user creation."
else
# Prompt for password
read -s -p "Enter the password for the new user: " PASSWORD
echo
read -s -p "Confirm the password for the new user: " PASSWORD_CONFIRM
echo
# Check if passwords match
if [ "$PASSWORD" != "$PASSWORD_CONFIRM" ]; then
echo "Passwords do not match. Exiting."
exit 1
fi
# Add a new user account with sudo access and set the password
echo "Adding new user account..."
useradd -m -s /bin/bash -G sudo $USERNAME
echo "$USERNAME:$PASSWORD" | chpasswd
fi
# Prompt for public SSH key
read -p "Enter the public SSH key for the new user: " SSH_KEY
# Add a public SSH key for the new user account, avoiding duplicates
echo "Adding public SSH key..."
mkdir -p /home/$USERNAME/.ssh
if ! grep -qFx "$SSH_KEY" /home/$USERNAME/.ssh/authorized_keys; then
echo "$SSH_KEY" >> /home/$USERNAME/.ssh/authorized_keys
echo "SSH key added successfully."
else
echo "SSH key already exists in authorized_keys file."
fi
chmod 700 /home/$USERNAME/.ssh
chmod 600 /home/$USERNAME/.ssh/authorized_keys
chown -R $USERNAME:$USERNAME /home/$USERNAME/.ssh
# Disable password authentication to the server
echo "Disabling password authentication..."
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
systemctl restart sshd
# Deny root login to the server
echo "Denying root login..."
sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin no/' /etc/ssh/sshd_config
systemctl restart sshd
# Setup Uncomplicated Firewall (UFW)
echo "Setting up Uncomplicated Firewall (UFW)..."
ufw allow OpenSSH
ufw --force enable
# Create Swap file based on machine's installed memory
echo "Creating Swap file..."
TOTAL_MEM=$(free -m | awk '/^Mem:/{print $2}')
if [ "$TOTAL_MEM" -le 2048 ]; then
SWAP_SIZE=1024
elif [ "$TOTAL_MEM" -le 8192 ]; then
SWAP_SIZE=2048
else
SWAP_SIZE=4096
fi
dd if=/dev/zero of=/swapfile bs=1M count=$SWAP_SIZE
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' | tee -a /etc/fstab
# Setup the timezone for the server (Default value is "Asia/Kolkata")
echo "Setting up timezone..."
read -p "Enter the timezone for the server (default is Asia/Kolkata): " TIMEZONE
TIMEZONE=${TIMEZONE:-"Asia/Kolkata"}
timedatectl set-timezone $TIMEZONE
# Set up time synchronization with systemd-timesyncd
echo "Setting up time synchronization with systemd-timesyncd..."
systemctl enable systemd-timesyncd
systemctl start systemd-timesyncd
echo "Post-installation tasks completed successfully!"
This script is a work-in-progress. We may update it with more features from time to time. Please check back for updates. It is also free to use, modify and distribute. You can customize this script however you like.
Explanation of the Script
Let us breakdown the script and see what each part does.
1. Shebang (#!/usr/bin/env bash
):
- Specifies the script interpreter as
bash
.
2. Update the System:
apt-get update && apt-get full-upgrade -y
: Updates the package list and upgrades all installed packages.
3. Install Necessary Packages:
apt-get install -y sudo openssh-server ufw systemd-timesyncd vim htop net-tools curl wget git
: Installssudo
,openssh-server
,ufw
(Uncomplicated Firewall),systemd-timesyncd
,vim
,htop
,net-tools
,curl
,wget
, andgit
. You can add additional packages of your choice here.
4. Prompt for Username:
read -p "Enter the username for the new user: " USERNAME
: Prompts the user to enter a username.
5. Check if User Exists:
if id "$USERNAME" &>/dev/null; then ... else ... fi
: Checks if the user already exists. If the user exists, it skips user creation.
6. Prompt for Password:
read -s -p "Enter the password for the new user: " PASSWORD
: Prompts the user to enter a password without echoing it to the terminal.read -s -p "Confirm the password for the new user: " PASSWORD_CONFIRM
: Prompts the user to confirm the password.
7. Check if Passwords Match:
if [ "$PASSWORD" != "$PASSWORD_CONFIRM" ]; then ... fi
: Checks if the entered passwords match. If they don't, the script exits.
8. Add a New User Account with Sudo Access and Set the Password:
useradd -m -s /bin/bash -G sudo $USERNAME
: Creates a new user with a home directory,/bin/bash
as the shell, and adds the user to thesudo
group.echo "$USERNAME:$PASSWORD" | chpasswd
: Sets the password for the new user.
9. Prompt for Public SSH Key:
read -p "Enter the public SSH key for the new user: " SSH_KEY
: Prompts the user to enter a public SSH key.
10. Add a Public SSH Key for the New User Account, Avoiding Duplicates:
mkdir -p /home/$USERNAME/.ssh
: Creates the.ssh
directory if it doesn't exist.if ! grep -qFx "$SSH_KEY" /home/$USERNAME/.ssh/authorized_keys; then ... fi
: Checks if the SSH key already exists in theauthorized_keys
file. If it doesn't, it adds the key.chmod 700 /home/$USERNAME/.ssh
: Sets the permissions of the.ssh
directory to 700 (read, write, execute for the owner only).chmod 600 /home/$USERNAME/.ssh/authorized_keys
: Sets the permissions of theauthorized_keys
file to 600 (read, write for the owner only).chown -R $USERNAME:$USERNAME /home/$USERNAME/.ssh
: Sets the owner and group of the.ssh
directory and its contents to the new user.
11. Disable Password Authentication to the Server:
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
: Disables password authentication in the SSH configuration.systemctl restart sshd
: Restarts the SSH service to apply the changes.
12. Deny Root Login to the Server:
sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin no/' /etc/ssh/sshd_config
: Disables root login in the SSH configuration.systemctl restart sshd
: Restarts the SSH service to apply the changes.
13. Setup Uncomplicated Firewall (UFW):
ufw allow OpenSSH
: Allows SSH traffic through the firewall.ufw --force enable
: Enables the firewall.
14. Create Swap File Based on Machine's Installed Memory:
TOTAL_MEM=$(free -m | awk '/^Mem:/{print $2}')
: Gets the total installed memory.if [ "$TOTAL_MEM" -le 2048 ]; then ... elif [ "$TOTAL_MEM" -le 8192 ]; then ... else ... fi
: Determines the swap file size based on the installed memory.dd if=/dev/zero of=/swapfile bs=1M count=$SWAP_SIZE
: Creates the swap file.chmod 600 /swapfile
: Sets the permissions of the swap file to 600.mkswap /swapfile
: Initializes the swap file.swapon /swapfile
: Enables the swap file.echo '/swapfile none swap sw 0 0' | tee -a /etc/fstab
: Adds the swap file to/etc/fstab
to make it persistent across reboots.
15. Setup the Timezone for the Server (Default Value is "Asia/Kolkata"):
read -p "Enter the timezone for the server (default is Asia/Kolkata): " TIMEZONE
: Prompts the user to enter a timezone.TIMEZONE=${TIMEZONE:-"Asia/Kolkata"}
: Sets the default timezone to "Asia/Kolkata" if no timezone is provided.timedatectl set-timezone $TIMEZONE
: Sets the system timezone.
16. Set Up Time Synchronization with systemd-timesyncd:
systemctl enable systemd-timesyncd
: Enablessystemd-timesyncd
to start at boot.systemctl start systemd-timesyncd
: Startssystemd-timesyncd
.
17. Completion Message:
echo "Post-installation tasks completed successfully!"
: Prints a message indicating that the post-installation tasks are completed.
By understanding each part of the script, you can see how it automates the setup of a new user, SSH configuration, firewall, swap file, timezone, and time synchronization on a Debian-based system.
Automate Essential Post-installation Tasks in Debian or Ubuntu using DebPostInstall Script
Before using this script, you need to create SSH key on your local machine. To do so, run:
ssh-keygen -t ed25519 -a 200 -C "mail@example.com" -f ~/.ssh/id_ed25519
Replace the mail id with your own.
Once the key is generated, run the following command to display the contents of the public key file:
cat ~/.ssh/id_ed25519.pub
Select and copy the displayed key. You will need it later.
Next, log in to your Debian or Ubuntu server.
Copy the contents of the DebPostInstall script and save it to a file named debpostinstall.sh
(or any other name you prefer) and make it executable:
chmod +x debpostinstall.sh
Then, you can run the script using command:
sudo ./debpostinstall.sh
The script will begin to perform the post installation tasks on your Debian-based system. Keep an eye on the screen.
When it prompts you to enter the username, please do so.
Enter the username for the new user:
Then enter the key-phrase that copied earlier from your local machine.
Enter the public SSH key for the new user:
Enter your timezone. The default is Asia/Kolkata.
Enter the timezone for the server (default is Asia/Kolkata):
That's it. The script will do the rest. Sit back and relax!
Once script is completed, REBOOT your system.
Verify Post Installation Steps
To verify if the script is working correctly, you can perform several checks to ensure that each task has been completed successfully.
Log in to your Debian/Ubuntu server and do the following tasks one by one.
1. Verify New User Creation
getent passwd $USERNAME
This command should return the details of the newly created user.
2. Check Sudo Access:
groups $USERNAME
This command should show that the user is a member of the sudo
group.
3. Verify SSH Key Setup
ls -ld ~/.ssh/ ls -l ~/.ssh/authorized_keys
Ensure that the .ssh
directory and authorized_keys
file have the correct permissions (700 for the directory and 600 for the file).
4. Verify Password Authentication is Disabled
grep "PasswordAuthentication no" /etc/ssh/sshd_config
This command should return the line indicating that password authentication is disabled.
5. Verify Root Login is Disabled
grep "PermitRootLogin no" /etc/ssh/sshd_config
This command should return the line indicating that root login is disabled.
6. Verify UFW Setup
sudo ufw status
This command should show that the firewall is active and that SSH is allowed.
7. Verify Swap File Creation
sudo swapon --show
This command should list the swap file created by the script.
8. Check /etc/fstab
:
grep "/swapfile" /etc/fstab
This command should return the line indicating that the swap file is configured to be mounted at boot.
9. Verify Timezone Setup
timedatectl | grep "Time zone"
This command should show the correct timezone set by the script.
10. Verify Time Synchronization with systemd-timesyncd
sudo systemctl status systemd-timesyncd
This command should show that the service is active and running.
11. Check Time Synchronization:
timedatectl status | grep "System clock synchronized" timedatectl status | grep "NTP service"
This commands should show "yes" and "active" respectively.
Alternatively, you could simply run the following command:
timedatectl
This will show system date and time details and time synchronization details.
By running these commands, you can verify that each step of the script has been executed correctly and that the system is configured as expected.
If any of these checks fail, you may need to review the script and the system configuration to identify and resolve any issues.
Conclusion
Congratulations! You've successfully setup your Debian server using the DebPostInstall script. Using this script, you've automated several critical post-installation tasks, ensuring your server is secure, and ready for use.
The DebPostInstall script is an useful tool that can save you time and effort when setting up new servers. Feel free to customize the script to better suit your specific needs and environment.
If you have any questions or need further assistance, don't hesitate to reach out.
Related Read: