Real Time Shell Scripts

Real Time Shell Scripts

Disk Usage Check Script

Monitoring disk usage is a crucial task for system administrators to ensure that servers and systems are running smoothly without running out of space. Here’s a simple script that helps you check disk usage on your machine.

#!/bin/bash
THRESHOLD=80
# Check disk usage and print a warning if usage is above the threshold
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' |
while read output;
do
 usage=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
 partition=$(echo $output | awk '{ print $2 }')
if [ $usage -ge $THRESHOLD ]; then
 echo "Warning: Disk usage on $partition is at ${usage}%"
fi
done

Explanation

THRESHOLD: Sets the disk usage percentage threshold.

df -H: Lists disk usage in human-readable format.

grep -vE '^Filesystem|tmpfs|cdrom': Filters out unnecessary lines.

awk '{ print $5 " " $1 }': Extracts the usage percentage and partition name.

while read output: Iterates over each line of the filtered output.

usage=$(echo $output | awk '{ print $1}' | cut -d'%' -f1): Extracts the usage

percentage.

partition=$(echo $output | awk '{ print $2 }'): Extracts the partition name.

if [ $usage -ge $THRESHOLD ]; then: Checks if the usage exceeds the threshold.

echo "Warning: Disk usage on 𝑝𝑎𝑟𝑡𝑖𝑡𝑖𝑜𝑛𝑖𝑠𝑎𝑡{usage}%": Prints a warning message

Once you write the script make the file executable. Here, I am running this script and changing threshold level to 10 and below is the output.


Service Health Check Script - Nginx

A simple health check script can help you monitor the status of your any service and take action if it goes down. Here’s a basic guide to creating and using an Nginx health check script and make the service up immediately if it is down.

#!/bin/bash
SERVICE="nginx"
# Check if the service is running, if not, start it
if systemctl is-active --quiet $SERVICE; then
echo "$SERVICE is running"
else
echo "$SERVICE is not running"
sudo systemctl start $SERVICE
fi

Explanation

• SERVICE: The name of the service to check.

• systemctl is-active --quiet $SERVICE: Checks if the service is running.

• echo "$SERVICE is running": Prints a message if the service is running.

• systemctl start $SERVICE: Starts the service if it is not running.

Later, I manually stopped Nginx service (sudo systemctl stop nginx)and the script started Nginx service as you see in below screenshot


Network Connectivity Check Script

There are some scenario's where you want to check if your server is reachable or not and we want to track it in some file. To quickly diagnose and resolve connectivity problems, a simple network connectivity check script can be incredibly helpful.

#!/bin/bash
HOST="google.com"
# Output file
OUTPUT_FILE="/home/ubuntu/output.txt"
DATE=$(date +%Y-%m-%d_%H-%M-%S)
# Check if the host is reachable
if ping -c 1 $HOST &> /dev/null
then
echo "$HOST is reachable at $DATE" >> $OUTPUT_FILE
else
echo "$HOST is not reachable  at $DATE" >> $OUTPUT_FILE
fi
sleep 1
EXIT

Explanation

• HOST: The hostname to check or IP Address

• OUTPUT_FILE: The file to write the output to.

• DATE=$(date +%Y-%m-%d_%H-%M-%S) : Year-Month-Date-Hour-Minute-Second

• ping -c 1 $HOST &> /dev/null: Pings the host once, suppressing output.

• echo "$HOST is reachable" >> $OUTPUT_FILE: Writes to the output file if the host

is reachable.

• echo "$HOST is not reachable" >> $OUTPUT_FILE: Writes to the output file if the

host is not reachable.


Database Backup Script

Keeping regular backups of your database is crucial for data integrity and security. Let's walk through a straightforward script to back up a MySQL database using a bash script.

Install MySQL:

sudo apt install mysql-server -y
sudo systemctl start mysql
sudo mysql

Now that we are connected, we can set a password for the root account using the following command:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
exit

Now login with your password as below

mysql -u root -p

Create Database

create database mydatabase ;
show databases ;

Now, we are good to write script - make sure to create folder mkdir -p /home/ubuntu/backup

#!/bin/bash
sudo mysqldump --user=root --password=password --all-databases > /home/ubuntu/backup/backup_$(date +%F.%H%M%S).sql


System Uptime Check Script

Knowing how long your system has been running can be crucial for system administrators and users alike. Whether you're monitoring server performance, diagnosing issues, or just curious, checking system uptime is a useful skill. Here’s a simple script to help you check your system’s uptime.

#!/bin/bash
# Print the system uptime
uptime -p

Explanation

• uptime -p: Prints the system uptime in a human-readable format.


Listening Ports Script

Network management can sometimes feel like juggling multiple balls at once. One essential task for any network administrator is monitoring the network's listening ports. This helps in identifying open ports that can be potential entry points for threats. To streamline this process, a simple script can be incredibly useful.

Installation

#Install net-tools:
sudo apt install net-tools

Script

#!/bin/bash
# List all listening ports and the associated services
netstat -tuln | grep LISTEN

Explanation

• netstat -tuln: Lists all TCP and UDP listening ports.

• grep LISTEN: Filters the output to show only listening ports.


Automatic Package Updates Script

Keeping your software up to date is crucial for security and performance. However, manually updating packages can be time-consuming and easy to overlook. Automating this process can save you time and ensure your system is always running the latest versions of your software. Here’s a simple guide to setting up an automatic package updates script.

#!/bin/bash
# Update system packages and clean up unnecessary packages
sudo apt update -y && sudo apt upgrade -y && sudo apt autoremove -y && sudo apt 
clean
echo "System packages updated and cleaned up"

Explanation

• apt update: Updates the package list.

• apt upgrade -y: Upgrades all installed packages.

• apt autoremove -y: Removes unnecessary packages.

• apt clean: Cleans up the package cache.

• echo "System packages updated and cleaned up": Outputs a message indicating

the completion of the update and cleanup.


HTTP Response Times Script

When building and maintaining websites, ensuring fast and reliable performance is crucial. One key aspect of this performance is the HTTP response time, which is the duration it takes for a server to respond to a request from a browser. Understanding and monitoring these response times can help identify and resolve potential bottlenecks. We'll explore a simple script to measure HTTP response times.

#!/bin/bash
URLS=("https://kshitijaa.hashnode.dev/" "https://www.linkedin.com/")
# Check HTTP response times for multiple URLs
for URL in "${URLS[@]}"; do
RESPONSE_TIME=$(curl -o /dev/null -s -w '%{time_total}\n' $URL)
echo "Response time for $URL: $RESPONSE_TIME seconds"
done

Explanation

• URLS: An array of URLs to check.

• for URL in "${URLS[@]}": Iterates over each URL.

• curl -o /dev/null -s -w '%{time_total}\n' $URL: Uses curl to fetch the URL and

measure the total response time.

• echo "Response time for $URL: $RESPONSE_TIME seconds": Prints the response

time for each URL.


Monitor System Processes and Memory Usage

Monitoring system processes and memory usage is crucial for maintaining the performance and stability of your computer. With a simple script, you can keep an eye on these vital statistics. Here, we’ll walk through creating a basic script to help you monitor your system’s performance.

#!/bin/bash
# Monitor system processes and their memory usage
ps aux --sort=-%mem | head -n 10

Explanation

• ps aux: Lists all running processes.

• --sort=-%mem: Sorts the processes by memory usage in descending order.

• head -n 10: Displays the top 10 processes by memory usage.


Thanks for spending your valuable time in learning to enhance your knowledge!😃🙏


Follow me on

Hashnode:kshitijaa.hashnode.dev

LinkedIn:linkedin.com/in/kshitija-bartakke-malwade-3..