Managing a Linux server manually can be time-consuming and error-prone. Automation with Bash scripts simplifies common tasks, ensuring consistency and efficiency. In this guide, we’ll walk through setting up a Linux server and automating routine operations.
Step 1: Setting Up Your Linux Server
Option 1: Local Virtual Machine
- Install VirtualBox or VMware.
- Download Ubuntu Server (recommended) or CentOS/RHEL.
- Allocate:
- 2 CPU cores
- 2GB RAM
- 20GB Storage
- Install the OS and configure SSH for remote access.
Option 2: Cloud Server
- Choose a cloud provider: AWS, Azure, GCP, Linode, or DigitalOcean.
- Create a virtual machine (EC2 instance for AWS).
- Use Ubuntu 22.04 LTS or Amazon Linux 2.
- Set up SSH access with a private key.
Step 2: Basic Server Configuration
1️⃣ Update & Upgrade Packages
sudo apt update && sudo apt upgrade -y # Ubuntu/Debian
sudo yum update -y # CentOS/Red Hat
2️⃣ Create a New User & Grant Sudo Privileges
sudo adduser devuser # Replace 'devuser' with your username
sudo usermod -aG sudo devuser # Grant sudo access
3️⃣ Set Up SSH Key Authentication
On your local machine:
ssh-keygen -t rsa -b 4096 # Generate SSH key
ssh-copy-id devuser@your-server-ip # Copy key to the server
Disable password authentication for better security:
sudo nano /etc/ssh/sshd_config
# Change "PasswordAuthentication yes" to "no"
sudo systemctl restart ssh
4️⃣ Set Up a Firewall (UFW)
sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status
Step 3: Automating Tasks Using Bash
1️⃣ Automate System Updates
Create a script:
nano update.sh
Add the following:
#!/bin/bash
sudo apt update && sudo apt upgrade -y
sudo apt autoremove -y
echo "System updated on $(date)" >> /var/log/update_log.txt
Make it executable:
chmod +x update.sh
Schedule it with cron:
crontab -e
Add this line to run it daily at midnight:
0 0 * * * /home/devuser/update.sh
2️⃣ Automate User Backup
Create a script:
nano backup_users.sh
Add:
#!/bin/bash
tar -czvf /backup/users_$(date +%F).tar.gz /home/
echo "Backup completed at $(date)" >> /var/log/backup_log.txt
Schedule it with cron to run every Sunday at 2 AM:
0 2 * * 0 /home/devuser/backup_users.sh
3️⃣ Automate Service Monitoring
Check if a service (e.g., Nginx) is running and restart if not:
nano check_nginx.sh
#!/bin/bash
if ! systemctl is-active --quiet nginx; then
sudo systemctl restart nginx
echo "Nginx restarted on $(date)" >> /var/log/nginx_restart.log
fi
Schedule it to check every 5 minutes:
*/5 * * * * /home/devuser/check_nginx.sh
Step 4: Testing & Verifying Automation
- Run scripts manually:
./update.sh
./backup_users.sh
./check_nginx.sh
- Check logs:
cat /var/log/update_log.txt
cat /var/log/backup_log.txt
cat /var/log/nginx_restart.log