Linux Scripts For Administrator

 

System Administrator Scripts

  1. System Health Check Script
    Checks CPU, memory, disk, and load average.
    health_check.sh

  2. Automatic Updates Script
    Automates dnf update and emails logs.
    auto_update.sh

  3. User Account Expiry Check
    Lists users with expired or expiring passwords.
    check_user_expiry.sh

  4. Disk Usage Alert Script
    Sends email if disk usage exceeds threshold.
    disk_alert.sh

  5. Service Restart Monitor
    Checks if key services (like sshd, httpd) are down and restarts them.
    monitor_services.sh

  6. Log Rotation Checker
    Verifies if logs are being rotated correctly.
    check_logrotate.sh

  7. Backup Script
    Automates rsync or tar-based backups.
    daily_backup.sh

  8. System Info Report
    Generates a full system report for inventory or audit.
    system_info.sh


Network Administrator Scripts

  1. Ping Sweep Script
    Scans a subnet for live hosts.
    ping_sweep.sh

  2. Port Scanner
    Lightweight wrapper over nmap or ss.
    port_scan.sh

  3. Bandwidth Usage Monitor
    Uses vnstat or iftop to log usage.
    bandwidth_monitor.sh

  4. DNS Resolution Tester
    Checks DNS resolution across multiple servers.
    dns_test.sh

  5. Firewall Rules Audit
    Dumps current firewall rules for review.
    firewall_audit.sh

  6. VPN Connection Tester
    Verifies active VPN tunnels and latency.
    vpn_check.sh

  7. Network Interface Monitor
    Alerts on interface status change (e.g., eth0 down).
    interface_monitor.sh


Virtualization Engineer Scripts

  1. VM Inventory Script
    Lists all VMs with CPU, memory, and disk stats (KVM/libvirt).
    vm_inventory.sh

  2. Snapshot Management Script
    Automates creation/deletion of VM snapshots.
    manage_snapshots.sh

  3. Auto-Start VM on Boot
    Ensures critical VMs autostart on reboot.
    vm_autostart.sh

  4. Resource Usage Report for VMs
    Monitors resource usage per VM.
    vm_usage_report.sh

  5. VM Backup Script
    Automates full backup using virsh and qemu-img.
    vm_backup.sh

  6. VM Live Migration Script
    Simplifies migration between hypervisors.
    vm_migrate.sh

  7. Orphaned Disk Finder
    Detects unused virtual disks taking up space.
    orphan_disk_check.sh


Security Administrator Scripts

  1. Failed Login Attempt Logger
    Parses auth.log or journalctl to find failed logins.
    failed_login_report.sh

  2. User Activity Monitor
    Monitors login/logout times and user commands.
    user_activity_monitor.sh

  3. Open Ports Reporter
    Lists all open ports and matching services.
    open_ports.sh

  4. Security Patch Checker
    Checks for available security updates.
    security_updates.sh

  5. Audit File Permission Script
    Identifies files with 777 or dangerous permissions.
    permission_audit.sh

  6. Intrusion Detection Log Parser
    Parses logs from tools like fail2bansnort, or suricata.
    ids_log_parser.sh

  7. Cron Job Integrity Checker
    Detects unauthorized cron changes.
    cron_audit.sh

  8. Firewall Rule Validator
    Tests current rules against a baseline.
    firewall_baseline_check.sh

-

1. System Health Check Script (health_check.sh)

Checks CPU load, memory, disk usage, and load average.

#!/bin/bash

echo "System Health Report for: $(hostname)"
echo "Generated on: $(date)"
echo "-----------------------------"

# CPU Load
echo "CPU Load:"
uptime | awk -F'load average:' '{ print $2 }'

# Memory Usage
echo -e "\nMemory Usage:"
free -h

# Disk Usage
echo -e "\nDisk Usage:"
df -h | grep -vE '^Filesystem|tmpfs|cdrom'

# Load Average
echo -e "\nTop 5 CPU-consuming processes:"
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -6

2. Automatic Updates Script (auto_update.sh)

Performs updates using dnf and emails logs.

#!/bin/bash

LOGFILE="/var/log/auto_update.log"
EMAIL="admin@example.com"

echo "Starting system update at $(date)" > "$LOGFILE"
dnf upgrade -y >> "$LOGFILE" 2>&1

echo -e "\nUpdate completed at $(date)" >> "$LOGFILE"
mail -s "Fedora System Update Log" "$EMAIL" < "$LOGFILE"

Ensure mailx is installed and configured: sudo dnf install mailx


3. User Account Expiry Check (check_user_expiry.sh)

Lists users with password expiration info.

#!/bin/bash

echo "User Account Expiry Report"
echo "--------------------------"

for user in $(awk -F: '{ if ($3 >= 1000 && $3 < 65534) print $1 }' /etc/passwd); do
    chage -l "$user" | grep -E "Account expires|Password expires" | awk -v u="$user" '{ print u":", $0 }'
done

4. Disk Usage Alert Script (disk_alert.sh)

Emails alert if disk usage exceeds a threshold.

#!/bin/bash

THRESHOLD=80
EMAIL="admin@example.com"

df -H | grep -vE '^Filesystem|tmpfs|cdrom' | while read output; do
  usep=$(echo "$output" | awk '{ print $5 }' | sed 's/%//')
  partition=$(echo "$output" | awk '{ print $1 " (" $6 ")" }')
  if [ "$usep" -ge "$THRESHOLD" ]; then
    echo -e "Disk usage alert on $(hostname):\n\n$partition is at ${usep}%." | \
    mail -s "Disk Usage Alert: ${usep}%" "$EMAIL"
  fi
done

5. Service Restart Monitor (monitor_services.sh)

Restarts key services if they are down.

#!/bin/bash

SERVICES=("sshd" "httpd")
EMAIL="admin@example.com"

for service in "${SERVICES[@]}"; do
  if ! systemctl is-active --quiet "$service"; then
    echo "$service was down. Restarting it on $(hostname)" | \
    mail -s "$service Service Restarted" "$EMAIL"
    systemctl restart "$service"
  fi
done

6. Log Rotation Checker (check_logrotate.sh)

Checks if logrotate ran recently and shows status.

#!/bin/bash

echo "Checking logrotate status..."
LOG_FILE="/var/lib/logrotate/status"

if [ -f "$LOG_FILE" ]; then
    echo "Last logrotate run details:"
    grep -A 1 "logrotate state --" "$LOG_FILE"
else
    echo "Logrotate status file not found!"
fi

Optional: Add logrotate -d /etc/logrotate.conf to simulate and check upcoming rotation.


7. Backup Script (daily_backup.sh)

Uses rsync for a local backup.

#!/bin/bash

SOURCE="/home"
DEST="/backup/home"
LOG="/var/log/backup.log"
EMAIL="admin@example.com"

mkdir -p "$DEST"

echo "Starting backup at $(date)" > "$LOG"
rsync -aAXv --delete "$SOURCE" "$DEST" >> "$LOG" 2>&1
echo "Backup completed at $(date)" >> "$LOG"

mail -s "Daily Backup Log - $(hostname)" "$EMAIL" < "$LOG"

8. System Info Report (system_info.sh)

Gathers system hardware and software details.

#!/bin/bash

echo "System Info Report - $(hostname)"
echo "Generated on: $(date)"
echo "-----------------------------"

echo -e "\nOS Info:"
cat /etc/os-release

echo -e "\nKernel:"
uname -r

echo -e "\nCPU Info:"
lscpu | grep -E 'Model name|Socket|Thread|Core'

echo -e "\nMemory Info:"
free -h

echo -e "\nDisk Info:"
lsblk

echo -e "\nNetwork Interfaces:"
ip -br addr

echo -e "\nRunning Services:"
systemctl list-units --type=service --state=running


-


1. Ping Sweep Script (ping_sweep.sh)

Scans a subnet (e.g., 192.168.1.0/24) for live hosts.

#!/bin/bash

SUBNET="192.168.1"
echo "Scanning subnet $SUBNET.0/24..."

for i in {1..254}; do
  ping -c 1 -W 1 $SUBNET.$i &> /dev/null && echo "$SUBNET.$i is UP" &
done

wait
echo "Scan complete."

2. Port Scanner (port_scan.sh)

Lightweight wrapper for nmap or ss.

#!/bin/bash

TARGET=$1
PORTS=$2  # e.g., 22,80,443

if [[ -z "$TARGET" ]]; then
  echo "Usage: $0 <target-ip-or-hostname> [ports]"
  exit 1
fi

echo "Scanning ports on $TARGET..."

if command -v nmap &>/dev/null; then
  nmap -p "${PORTS:-1-1024}" "$TARGET"
else
  echo "nmap not installed. Showing local open ports using ss:"
  ss -tuln
fi

3. Bandwidth Usage Monitor (bandwidth_monitor.sh)

Uses vnstat to log real-time bandwidth usage.

#!/bin/bash

IFACE="eth0"

if ! command -v vnstat &> /dev/null; then
  echo "vnstat not installed. Installing..."
  sudo dnf install -y vnstat
  sudo systemctl enable --now vnstat
fi

echo "Monitoring bandwidth on interface $IFACE (press Ctrl+C to stop):"
vnstat -l -i $IFACE

Replace eth0 with your interface (check with ip a).


4. DNS Resolution Tester (dns_test.sh)

Tests DNS resolution using multiple DNS servers.

#!/bin/bash

DOMAIN="example.com"
SERVERS=("8.8.8.8" "1.1.1.1" "9.9.9.9")

for server in "${SERVERS[@]}"; do
  echo -n "Testing $DOMAIN with DNS server $server: "
  dig @"$server" "$DOMAIN" +short
done

5. Firewall Rules Audit (firewall_audit.sh)

Dumps current active firewall rules (firewalld-based Fedora system).

#!/bin/bash

echo "Active firewalld rules on $(hostname):"
echo "--------------------------------------"

sudo firewall-cmd --list-all-zones

echo -e "\nNAT/Forwarding Rules (iptables):"
sudo iptables -L -n -v

6. VPN Connection Tester (vpn_check.sh)

Detects if a VPN interface is active and pings a VPN gateway.

#!/bin/bash

VPN_IFACE="tun0"
VPN_HOST="10.8.0.1"  # Adjust for your VPN setup

if ip link show "$VPN_IFACE" &> /dev/null; then
  echo "VPN interface $VPN_IFACE is active."
  echo "Pinging VPN gateway ($VPN_HOST)..."
  ping -c 3 "$VPN_HOST"
else
  echo "VPN interface $VPN_IFACE not found. VPN may be down."
fi

Works for OpenVPN/Tailscale/WireGuard setups where tun0 or wg0 is the interface.


7. Network Interface Monitor (interface_monitor.sh)

Monitors an interface and alerts if it goes down.

#!/bin/bash

INTERFACE="eth0"
EMAIL="admin@example.com"

STATE=$(cat /sys/class/net/$INTERFACE/operstate)

if [ "$STATE" != "up" ]; then
  echo "ALERT: Interface $INTERFACE is DOWN on $(hostname) at $(date)" | \
  mail -s "Network Interface Down: $INTERFACE" "$EMAIL"
else
  echo "Interface $INTERFACE is UP."
fi

You can add this to a cron job every 5 minutes for ongoing monitoring.


-

-


๐Ÿงพ 1. VM Inventory Script (vm_inventory.sh)

๐Ÿงช Example 1: Basic inventory (CPU, Memory, Disk)

#!/bin/bash
echo "=== VM Inventory Report ==="
for vm in $(virsh list --all --name); do
  echo "VM: $vm"
  virsh dominfo "$vm" | grep -E 'CPU\(s\)|Max memory|Used memory|State'
  virsh domblklist "$vm" | awk 'NR>2 {print "Disk:", $1, $2}'
  echo "---------------------------"
done

๐Ÿงช Example 2: Output as CSV for auditing

#!/bin/bash
echo "VM,State,CPU(s),MaxMem(MB),UsedMem(MB),DiskPath"
for vm in $(virsh list --all --name); do
  state=$(virsh dominfo "$vm" | grep "State" | awk '{print $2}')
  cpus=$(virsh dominfo "$vm" | grep "CPU(s)" | awk '{print $2}')
  max_mem=$(virsh dominfo "$vm" | grep "Max memory" | awk '{print $3}')
  used_mem=$(virsh dominfo "$vm" | grep "Used memory" | awk '{print $3}')
  disk=$(virsh domblklist "$vm" | awk 'NR==3 {print $2}')
  echo "$vm,$state,$cpus,$max_mem,$used_mem,$disk"
done

๐Ÿ“ธ 2. Snapshot Management Script (manage_snapshots.sh)

๐Ÿงช Example 1: Create snapshot with timestamp

#!/bin/bash
VM=$1
SNAP="snap_$(date +%Y%m%d%H%M)"
virsh snapshot-create-as "$VM" "$SNAP" "Auto snapshot" --atomic

๐Ÿงช Example 2: Delete all snapshots older than 7 days

#!/bin/bash
VM=$1
for snap in $(virsh snapshot-list "$VM" --name); do
  date_str=$(virsh snapshot-info "$VM" --snapshotname "$snap" | grep "Creation Time" | awk '{print $3, $4}')
  snap_time=$(date -d "$date_str" +%s)
  if [ $(($(date +%s) - $snap_time)) -gt $((7*24*3600)) ]; then
    virsh snapshot-delete "$VM" --snapshotname "$snap"
    echo "Deleted snapshot $snap for $VM"
  fi
done

๐Ÿ”„ 3. Auto-Start VM on Boot (vm_autostart.sh)

๐Ÿงช Example 1: Enable autostart for selected VMs

#!/bin/bash
CRITICAL_VMS=("webserver" "dbserver")
for vm in "${CRITICAL_VMS[@]}"; do
  virsh autostart "$vm"
  echo "Autostart enabled for $vm"
done

๐Ÿงช Example 2: Disable autostart for all VMs

#!/bin/bash
for vm in $(virsh list --all --name); do
  virsh autostart "$vm" --disable
  echo "Autostart disabled for $vm"
done

๐Ÿ“Š 4. Resource Usage Report for VMs (vm_usage_report.sh)

๐Ÿงช Example 1: Show vCPU time and memory usage

#!/bin/bash
for vm in $(virsh list --name); do
  echo "VM: $vm"
  virsh domstats "$vm" --vcpu --balloon | grep -E 'vcpu.time|balloon.current'
done

๐Ÿงช Example 2: Generate resource summary in MB

#!/bin/bash
echo "VM,CPU_Usage(ms),Memory_Usage(MB)"
for vm in $(virsh list --name); do
  stats=$(virsh domstats "$vm" --vcpu --balloon)
  cpu=$(echo "$stats" | grep 'vcpu.time' | awk -F= '{print int($2/1000000)}')
  mem=$(echo "$stats" | grep 'balloon.current' | awk -F= '{print int($2/1024)}')
  echo "$vm,$cpu,$mem"
done

๐Ÿ’พ 5. VM Backup Script (vm_backup.sh)

๐Ÿงช Example 1: Backup VM disk using qemu-img

#!/bin/bash
VM=$1
DISK=$(virsh domblklist "$VM" | awk '/vda/ {print $2}')
BACKUP="/backups/$VM-$(date +%F).qcow2"
qemu-img convert -O qcow2 "$DISK" "$BACKUP"
echo "Backup stored at $BACKUP"

๐Ÿงช Example 2: Full VM backup (XML + disk)

#!/bin/bash
VM=$1
BACKUP_DIR="/backups/$VM"
mkdir -p "$BACKUP_DIR"
virsh dumpxml "$VM" > "$BACKUP_DIR/$VM.xml"
DISK=$(virsh domblklist "$VM" | awk '/vda/ {print $2}')
qemu-img convert -O qcow2 "$DISK" "$BACKUP_DIR/disk_$(date +%F).qcow2"
echo "Backup complete for $VM"

๐Ÿšš 6. VM Live Migration Script (vm_migrate.sh)

๐Ÿงช Example 1: Basic live migration

#!/bin/bash
VM=$1
DEST=$2
virsh migrate --live "$VM" qemu+ssh://$DEST/system

๐Ÿงช Example 2: Persistent migration (remove from source)

#!/bin/bash
VM=$1
DEST=$2
virsh migrate --live --persistent --undefinesource "$VM" qemu+ssh://$DEST/system

Ensure shared storage or use block migration with --copy-storage-all.


๐Ÿงน 7. Orphaned Disk Finder (orphan_disk_check.sh)

๐Ÿงช Example 1: Find .qcow2 not linked to VMs

#!/bin/bash
DISK_DIR="/var/lib/libvirt/images"
USED_DISKS=$(virsh list --all --name | xargs -I {} virsh domblklist {} | awk '{print $2}')
find "$DISK_DIR" -name "*.qcow2" | while read disk; do
  if ! grep -q "$disk" <<< "$USED_DISKS"; then
    echo "Orphaned: $disk"
  fi
done

๐Ÿงช Example 2: List orphan disks over 5GB

#!/bin/bash
DISK_DIR="/var/lib/libvirt/images"
USED=$(virsh list --all --name | xargs -I {} virsh domblklist {} | awk '{print $2}')
find "$DISK_DIR" -name "*.qcow2" -size +5G | while read disk; do
  if ! grep -q "$disk" <<< "$USED"; then
    echo "Orphaned large disk: $disk"
  fi
done

-


๐Ÿ” 1. Failed Login Attempt Logger (failed_login_report.sh)

Example 1: Using journalctl to Detect Failed SSH Logins

#!/bin/bash
# failed_login_report.sh

echo "Failed SSH Login Attempts:"
journalctl -u sshd.service | grep -iE "failed|invalid" | tail -n 20

This script uses journalctl to filter recent failed SSH login attempts by searching for keywords like "failed" or "invalid" in the sshd service logs.

Example 2: Parsing /var/log/auth.log for Failed Logins

#!/bin/bash
# failed_login_report.sh

echo "Failed Login Attempts:"
grep -iE "sshd.*Failed|Invalid|failure" /var/log/auth.log | tail -n 20

This script scans the /var/log/auth.log file for entries indicating failed login attempts, focusing on keywords such as "Failed", "Invalid", or "failure".


๐Ÿง‘‍๐Ÿ’ป 2. User Activity Monitor (user_activity_monitor.sh)

Example 1: Displaying Recent Logins and Logouts

#!/bin/bash
# user_activity_monitor.sh

echo "Recent User Logins and Logouts:"
last -n 10

This script utilizes the last command to show the last 10 logins and logouts on the system.

Example 2: Monitoring User Command Execution

#!/bin/bash
# user_activity_monitor.sh

echo "Recent User Commands:"
ausearch -m EXECVE -ts today

This script uses ausearch to find all executed commands for the current day, providing insights into user activities.


๐ŸŒ 3. Open Ports Reporter (open_ports.sh)

Example 1: Listing All Open Ports with ss

#!/bin/bash
# open_ports.sh

echo "Open Ports and Associated Services:"
ss -tuln

This script employs the ss command to list all open ports and the services associated with them.

Example 2: Using netstat to Display Listening Ports

#!/bin/bash
# open_ports.sh

echo "Listening Ports:"
netstat -tuln

This script uses netstat to display all listening ports on the system.


๐Ÿ›ก️ 4. Security Patch Checker (security_updates.sh)

Example 1: Checking for Available Security Updates

#!/bin/bash
# security_updates.sh

echo "Available Security Updates:"
dnf updateinfo list available security

This script utilizes dnf to list all available security updates for the system.

Example 2: Listing Installed Security Updates

#!/bin/bash
# security_updates.sh

echo "Installed Security Updates:"
dnf updateinfo list installed security

This script lists all security updates that have been installed on the system using dnf.


๐Ÿ” 5. Audit File Permission Script (permission_audit.sh)

Example 1: Finding Files with World-Writable Permissions

#!/bin/bash
# permission_audit.sh

echo "Files with World-Writable Permissions:"
find / -type f -perm -002 -exec ls -l {} \;

This script searches the entire filesystem for files that are world-writable, which can pose security risks.

Example 2: Identifying Files with Dangerous Permissions

#!/bin/bash
# permission_audit.sh

echo "Files with Dangerous Permissions:"
find / -type f -perm 0777 -exec ls -l {} \;

This script identifies files with permissions set to 0777, allowing all users full access.


๐Ÿ›ก️ 6. Intrusion Detection Log Parser (ids_log_parser.sh)

Example 1: Parsing Fail2Ban Logs for Banned IPs

#!/bin/bash
# ids_log_parser.sh

echo "Banned IPs by Fail2Ban:"
fail2ban-client status sshd | grep "Banned IP list"

This script uses fail2ban-client to display the list of IPs banned by Fail2Ban for the SSH service.

Example 2: Checking Suricata Alerts

#!/bin/bash
# ids_log_parser.sh

echo "Suricata Alerts:"
tail -n 20 /var/log/suricata/eve.json | jq '.alert'

This script extracts and displays the latest alerts from Suricata's JSON logs using jq.


7. Cron Job Integrity Checker (cron_audit.sh)

Example 1: Listing All User Cron Jobs

#!/bin/bash
# cron_audit.sh

echo "User Cron Jobs:"
crontab -l

This script lists the current user's cron jobs.

Example 2: Checking for Unauthorized Cron Jobs

#!/bin/bash
# cron_audit.sh

echo "Unauthorized Cron Jobs:"
grep -r "root" /var/spool/cron

This script searches for any cron jobs scheduled by the root user, which may indicate unauthorized tasks.


๐Ÿ”ฅ 8. Firewall Rule Validator (firewall_baseline_check.sh)

Example 1: Listing Active Firewall Rules

#!/bin/bash
# firewall_baseline_check.sh

echo "Active Firewall Rules:"
firewall-cmd --list-all

This script uses firewall-cmd to display all active firewall rules.

Example 2: Comparing Current Rules with a Baseline

#!/bin/bash
# firewall_baseline_check.sh

echo "Comparing Firewall Rules to Baseline:"
diff <(firewall-cmd --list-all) /path/to/baseline_rules.txt

This script compares the current firewall rules with a predefined baseline to identify any discrepancies.



Comments

Popular posts from this blog

Differences Between Ubuntu 24.04.2 LTS and Ubuntu 25.04

Kapardak Bhasma: A Comprehensive Review and use

Vanga Bhasma: A Traditional Ayurvedic Metallic Formulation and use