/cnc/img/bash-automation.png

Mastering System Automation with Bash

Welcome to System Automation in Bash: Part 1

Welcome to part one in this comprehensive series on automating tasks using Bash. This tutorial also includes a section on how to leverage the Windows Subsystem for Linux (WSL) for users who do not have a Linux system handy. Let’s dive right in!

Bash (Bourne Again SHell) is a shell and command language interpreter for the GNU (Linux) operating system. It’s widely used for its ability to control the operation of a system. Through Bash scripting, we can automate repetitive tasks, schedule jobs, and much more.

Setting Up Your Environment

If you’re a Windows user who doesn’t have access to a Linux terminal, don’t worry! Thanks to the Windows Subsystem for Linux (WSL), you can run Linux commands and enjoy the power of Bash scripting on your Windows PC.

Enabling WSL (Windows Subsystem for Linux)

To enable WSL, follow these steps:

  • Open the Start menu and search for “Turn Windows features on or off.”
  • Click on the search result to open the “Turn Windows features on or off” dialog.
  • Scroll down and locate “Windows Subsystem for Linux.”
  • Check the box next to “Windows Subsystem for Linux.”
  • Click “OK” to save the changes.
  • Reboot computer if instructed to do so

Download a Linux Distro (Recomend: Ubuntu) from the MS Store

After the installation and reboot are complete, you need to download a Linux distribution from the Microsoft Store. Open the Microsoft Store and search for your preferred Linux distribution (e.g., Ubuntu, Debian, Fedora). Click on the distribution, and then click the “Get” or “Install” button to download and install it.

bash
# Install WSL (Windows Subsystem for Linux)
wsl --install
# Verify WSL installation
wsl --set-default-version 2

This command sets WSL to use version 2, which provides improved performance and compatibility.

Once you’ve completed these steps, you’ll have the Windows - Subsystem for Linux up and running on your Windows PC. You can now execute Linux commands and leverage the power of Bash scripting to automate tasks and manage your system efficiently.

For our tutorial, we’re using an Ubuntu image to access bash. To initiate you’re bash system once the above steps are complete, simply type bash into a terminal window.

Basic System Automation with Bash

Bash scripting provides powerful tools for system automation. Here, we’ll look at a few examples of how you can leverage these capabilities for task automation, including monitoring system processes, automating backups, and managing user accounts.

Monitoring System Processes

System administrators often need to ensure that certain processes are always running. The following script monitors the status of the Nginx process and starts it if it’s not running.

bash
##!/bin/bash
# Check if nginx process is running
if pgrep "nginx" > /dev/null
then
# If running, print message
echo "nginx is running."
else
# If not running, start the service
echo "nginx is not running. Starting nginx..."
service nginx start
fi

Automating Backups

Regular backups are essential for recovering data in case of a system failure. This script creates a compressed backup of a directory and appends the current date to the backup file’s name.

bash
#!/bin/bash
# Get the current date
DATE=$(date +%Y-%m-%d)
# Define backup directory
BACKUP_DIR="/path/to/backup"
# Create a compressed backup of the directory
tar -czf $BACKUP_DIR/backup-$DATE.tar.gz /your/directory

Managing User Accounts

Creating and managing user accounts is a common task for system administrators. This script creates a new user and sets a password for the account.

bash
#!/bin/bash
# Add new user with home directory and bash shell
useradd -m -s /bin/bash newuser
# Set password for new user
echo 'newuser:password' | chpasswd

Diving into the Deep End: Advanced System Automation

In this section, we’ll explore some of the more complex scenarios that Bash can help us navigate, such as automating system updates, network monitoring, and log analysis.

Automating System Updates and Software Installation

Keeping the system and its software up-to-date is crucial for security and performance. This script updates the system and installs a list of specified software packages. If a package is already installed, it won’t be installed again.

bash
#!/bin/bash
# Update system
echo "Updating system..."
apt-get update -y
apt-get upgrade -y
# Define packages to be installed
packages=(
"nginx"
"mysql-server"
"php"
)
# Install packages
echo "Installing packages..."
for package in "${packages[@]}"
do
# Check if package is already installed
if dpkg -l | grep -q ${package}; then
echo "${package} is already installed"
else
# Install the package
apt-get install -y ${package}
fi
done

Network Monitoring

Ensuring that network services are up and running is another essential task. This script pings a specified host continuously. If the host doesn’t respond to the ping, the script sends an email alert. This can be handy for monitoring remote servers or services.

bash
#!/bin/bash
# Define host and recipient email
HOST="8.8.8.8"
EMAIL="your-email@example.com"
# Ping the host and send an email if it's down
while true; do
if ! ping -c1 ${HOST} > /dev/null; then
echo "${HOST} is down. Sending email..."
echo "${HOST} is down" | mail -s "Host Unreachable" ${EMAIL}
fi
sleep 5
done

Log Analysis and Alerting

Logs are a valuable resource when troubleshooting issues or detecting suspicious activities. This script watches a log file for a specific pattern. When the pattern is found, an email alert is sent. This can be used, for example, to monitor access logs for unauthorized login attempts.

bash
#!/bin/bash
# Define log file and pattern
LOG="/var/log/auth.log"
PATTERN="Failed password"
# Define recipient email
EMAIL="your-email@example.com"
# Monitor the log file
tail -F $LOG | while read LINE; do
if [[ "$LINE" == *"$PATTERN"* ]]; then
# If pattern is found, send an email
echo "$LINE" | mail -s "Alert: Detected $PATTERN" $EMAIL
fi
done

Conclusion of Part 1

With these examples, you should have a good idea of the power of Bash for system automation. Whether it’s basic tasks like monitoring processes or advanced tasks like network monitoring and log analysis, Bash can make your life a lot easier. Happy scripting!