- Posted on
- • Artificial Intelligence
25 Artificial Intelligence Bash Scripts Every Linux Admin Should Know
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
25 Artificial Intelligence Bash Scripts Every Linux Admin Should Know
If you’re a Linux admin, you’re drowning in logs, alerts, and “what now?” moments. The good news: you already have the perfect automation surface—your shell. With a few tiny Bash wrappers and an AI endpoint (cloud or local), you can turn raw system output into actionable insight, shave hours off triage, and cut through noise.
This post shows you how to wire AI into everyday admin tasks using nothing but Bash, curl, and jq—plus a few optional tools. You’ll get ready-to-use scripts, why they work, and how to install the needed packages via apt, dnf, and zypper.
Value: Reduce manual toil, explain failures fast, generate safer fixes, and elevate routine ops into decision-ready summaries.
Problem: Logs are verbose; incidents are chaotic; context switching is expensive. AI can synthesize, explain, prioritize, and propose next steps—on demand—from your terminal.
Why this works (and why now)
OpenAI-compatible HTTP APIs exist for both cloud and local models. If you can curl JSON, you can use AI from Bash.
Local options (e.g., servers that expose OpenAI-compatible endpoints) let you keep data on-box or on-VPC.
Small, composable shell scripts plug AI directly into journalctl, ps, tcpdump, git, and your existing tooling.
Caution: Be mindful of data sensitivity and compliance. For production logs or secrets, prefer local models or a trusted endpoint.
Prerequisites
Install the common tools you’ll use in the examples.
- Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y curl jq bc ffmpeg tesseract-ocr smartmontools python3 python3-pip
- Fedora/RHEL/CentOS (dnf):
sudo dnf install -y curl jq bc tesseract smartmontools python3 python3-pip
# ffmpeg may require RPM Fusion on Fedora:
# sudo dnf install -y https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm
# sudo dnf install -y ffmpeg
- openSUSE (zypper):
sudo zypper refresh
sudo zypper install -y curl jq bc tesseract smartmontools python3 python3-pip
# ffmpeg may require Packman on some versions; once enabled:
# sudo zypper install -y ffmpeg
Optional notes:
Tesseract language data may require an extra package on some distros (e.g., tesseract-langpack-eng on Fedora).
ffmpeg packaging varies by distro; enable the appropriate multimedia repo if not found.
Configure your AI endpoint
Set environment variables for any OpenAI-compatible endpoint (cloud or local). Add these to your shell profile or CI secret store:
export AI_API_BASE="https://api.openai.com/v1" # or your local/server base exposing OpenAI-compatible routes
export AI_API_KEY="YOUR_TOKEN" # API key or token
export AI_MODEL="gpt-4o-mini" # or a local model name served via a compatible API
To keep prompts manageable, create a tiny helper you can source in your scripts:
# ~/bin/ai.sh
#!/usr/bin/env bash
set -euo pipefail
: "${AI_API_BASE:=https://api.openai.com/v1}"
: "${AI_MODEL:=gpt-4o-mini}"
: "${AI_API_KEY:?Missing AI_API_KEY}"
ai_chat() {
# Usage: ai_chat "Your prompt here"
local prompt="${1:-}"
if [[ -z "$prompt" ]]; then
echo "Usage: ai_chat 'prompt...'" >&2
return 2
fi
curl -sS "$AI_API_BASE/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AI_API_KEY" \
-d "$(jq -n --arg m "$AI_MODEL" --arg p "$prompt" \
'{model:$m, messages:[{role:"user",content:$p}], temperature:0.2}')" \
| jq -r '.choices[0].message.content'
}
Make it executable and add to PATH:
chmod +x ~/bin/ai.sh
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
Then in any script:
source ~/bin/ai.sh
4 real-world, actionable examples
These go deeper with rationale, usage, and gotchas. After them, you’ll find the full list of 25 scripts.
1) Daily SSH/auth summary (spot brute-force and oddities fast)
Why: Quickly see who tried to get in, who succeeded, and what’s unusual—without paging through thousands of lines.
#!/usr/bin/env bash
# ssh-summary.sh
set -euo pipefail
source ~/bin/ai.sh
SINCE="${1:-24 hours ago}"
# Pull recent SSH-related logs across common sources
LOG="$( { journalctl -u ssh --since "$SINCE" -o short-iso --no-pager 2>/dev/null \
|| journalctl -t sshd --since "$SINCE" -o short-iso --no-pager 2>/dev/null \
|| grep -aE 'sshd' /var/log/auth.log 2>/dev/null; } | tail -n 4000)"
PROMPT=$'You are a Linux security assistant. Summarize SSH activity from the logs below:\n- Bullet points\n- Show top failed usernames and source IPs\n- Call out successful logins\n- Flag anomalies and geo-odd IPs if obvious\n- Propose 2–3 concrete defenses (fail2ban rules, firewall, key-only auth)\n\nLogs:\n'"$LOG"
ai_chat "$PROMPT"
Tip: Restrict to last N lines to keep token size sensible. Run via cron daily and mail the output.
2) Explain any error (fast root cause and exact commands to verify)
Why: Translate cryptic kernel, systemd, or app errors into next actions.
#!/usr/bin/env bash
# explain.sh
set -euo pipefail
source ~/bin/ai.sh
if [[ $# -eq 0 ]]; then
echo "Usage: $0 'paste error message or command output'" >&2
exit 2
fi
ai_chat "Explain like I'm an SRE with 5 minutes. Include likely causes, diagnostic commands to confirm, and safe fixes:\n$*"
Usage:
dmesg | tail -n 50 | sed -n '1,200p' | xargs -0 2>/dev/null
./explain.sh "$(dmesg | tail -n 50)"
3) Auto-draft an incident report from the last 15 minutes
Why: When pager goes off, you need a clean, structured summary quickly.
#!/usr/bin/env bash
# incident-draft.sh
set -euo pipefail
source ~/bin/ai.sh
LOG="$(journalctl -p 3 --since '15 min ago' -o short-iso --no-pager | tail -n 300)"
PROMPT=$'Create a concise incident report with:\n- Title\n- Start time and detection method\n- Impact scope (what, who)\n- Key errors (quote a few lines)\n- Likely root cause hypotheses\n- Immediate mitigations\n- Next actions and owners\n\nLogs:\n'"$LOG"
ai_chat "$PROMPT"
Pipe to your ticket system or save to a file for quick edits.
4) OCR a screenshot or server console photo and summarize
Why: Convert screenshots or KVM console images into text and get a summary or fix.
Requires tesseract and optionally ffmpeg (for video frames).
#!/usr/bin/env bash
# ocr-summarize.sh image_or_frame.jpg
set -euo pipefail
source ~/bin/ai.sh
FILE="${1:?Usage: $0 file.(png|jpg)}"
TEXT="$(tesseract "$FILE" stdout 2>/dev/null | head -c 50000)"
ai_chat "Summarize the error(s) found in this OCR text, and propose likely fixes:\n$TEXT"
For a short clip, you could grab a representative frame with ffmpeg, then OCR it.
The full list: 25 AI-powered Bash scripts for admins
Each of these can be implemented with the ai_chat helper. Many are single functions you can drop into an ops toolkit.
1) SSH/auth daily summary
See ssh-summary.sh above.
2) Explain any error
See explain.sh above.
3) Incident report draft
See incident-draft.sh above.
4) OCR + summarize
See ocr-summarize.sh above.
5) Anomaly detection for today’s SSH failures vs. baseline
ssh_anomaly.sh: Compare today’s fail counts with a rolling avg.
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
TODAY_FAILS="$(journalctl -t sshd --since 'today' --no-pager | grep -c 'Failed password' || true)"
BASELINE="${HOME}/.ssh_fail_baseline"
AVG=0; COUNT=0
[[ -f "$BASELINE" ]] && { read -r AVG COUNT < <(awk '{s+=$1; n+=1} END{if(n){print s/n,n}else{print 0,0}}' "$BASELINE"); }
echo "$TODAY_FAILS" >> "$BASELINE"
ai_chat "SSH failure anomaly check. Today: $TODAY_FAILS; baseline avg: $AVG over $COUNT days. Are we anomalous? Briefly justify and propose next steps."
6) Suggest firewall rules from repeated offenders
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
IPS="$(journalctl -t sshd --since '24 hours ago' --no-pager | awk '/Failed password/ {print $NF}' | sort | uniq -c | sort -nr | head -n 10)"
ai_chat "Given these top offending IPs (count IP):\n$IPS\nPropose nftables/ufw rules to throttle or block responsibly. Show commands and rollback."
7) Sudoers risk review
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
CONF="$(sudo cat /etc/sudoers /etc/sudoers.d/* 2>/dev/null | sed 's/\t/ /g' | sed -n '1,1200p')"
ai_chat "Assess sudoers risk. Identify NOPASSWD, broad wildcards, command escapes, env_keep. List concrete remediations.\n$CONF"
8) Explain SELinux AVC denials and fixes
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
LOG="$(journalctl -t setroubleshoot --since '2 hours ago' -o short-iso --no-pager | tail -n 200)"
ai_chat "Explain these SELinux denials and provide exact semanage/setsebool fixes, including why they’re safe/unsafe:\n$LOG"
9) dmesg hardware fault summary
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
K="$(dmesg --ctime | egrep -i 'I/O error|SMART|ata|nvme|ecc|thermal|overheat|xfs|ext4|btrfs' | tail -n 400)"
ai_chat "Summarize storage/thermal/fs faults from dmesg. Prioritize actions: backup now? run smartctl? RMA? Provide commands.\n$K"
10) Boot/postmortem timeline from journalctl
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
LOG="$(journalctl -b -1 -o short-iso --no-pager | tail -n 800)"
ai_chat "Create a boot timeline of the previous boot (critical warnings, service failures, delays). Suggest boot optimization/remediation.\n$LOG"
11) CPU spike explainer from ps/top snapshot
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
SNAP="$(ps -eo pid,ppid,pcpu,pmem,comm --sort=-pcpu | head -n 20)"
ai_chat "Given this process snapshot, explain likely cause of CPU spike and 3 safe mitigation options with exact commands:\n$SNAP"
12) Memory leak triage cheat sheet
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
SNAP="$(free -h; echo; ps -eo pid,pmem,rss,comm --sort=-rss | head -n 20)"
ai_chat "Create a memory-leak triage plan using this snapshot. Include pmap/smaps, cgroups, and safe restarts.\n$SNAP"
13) SMART health summary (disks)
Requires smartmontools (installed above).
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
OUT="$(sudo smartctl -H -A /dev/sda 2>&1; echo; sudo smartctl -H -A /dev/nvme0 2>&1 || true)"
ai_chat "Summarize SMART health and predict failure risk. Provide backup urgency and exact follow-up tests.\n$OUT"
14) Web access-log anomaly detector (Nginx/Apache)
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
LOG="$(tail -n 5000 /var/log/nginx/access.log 2>/dev/null || tail -n 5000 /var/log/httpd/access_log 2>/dev/null || true)"
ai_chat "From these access logs, find anomalies (spikes, suspicious paths, status code patterns, user-agents). Recommend WAF rules.\n$LOG"
15) Git diff → meaningful commit message
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
DIFF="$(git diff --staged | sed -n '1,1500p')"
ai_chat "Write a clear, conventional commit message for this staged diff. Include short title and detailed body with rationale.\n$DIFF"
16) Turn a man page into a 10-line cheat sheet
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
CMD="${1:?Usage: $0 <command>}"
TEXT="$(man "$CMD" | col -b | head -c 8000)"
ai_chat "Produce a 10-line practical cheat sheet for '$CMD' with the most useful flags and examples:\n$TEXT"
17) Annotate crontab with natural-language explanations
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
CRON="$(crontab -l 2>/dev/null || true)"
ai_chat "Explain each of these crontab entries in plain English and spot dangerous overlaps or timings:\n$CRON"
18) Bash one-liner explainer (safety-first)
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
ai_chat "Explain what this Bash one-liner does, risks, and a safer alternative if needed:\n$*"
19) Safer rewrite for risky commands
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
ai_chat "Rewrite the following command to be safer (dry-run/--no-act, prompts, backups) and explain changes:\n$*"
20) SQL query explainer/optimizer (for on-box DB work)
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
SQL="$(cat "${1:-/dev/stdin}")"
ai_chat "Explain and optimize this SQL query. Suggest indexes and note risks:\n$SQL"
21) Kubernetes/YAML manifest sanity check
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
YAML="$(cat "${1:-/dev/stdin}" | head -c 15000)"
ai_chat "Review this Kubernetes YAML for common pitfalls (resource limits, probes, securityContext). Suggest improvements:\n$YAML"
22) iptables/nftables rule explainer and equivalence
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
RULES="$(sudo iptables-save 2>/dev/null || sudo nft list ruleset 2>/dev/null)"
ai_chat "Explain these firewall rules in plain English. Provide equivalent nftables (if iptables) or vice versa.\n$RULES"
23) Regex explainer (avoid misfires)
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
ai_chat "Explain and test this regex. Describe what it matches and edge cases:\n$*"
24) “Write me a jq” from natural language
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
REQ="${1:?Describe the JSON transform you want}"
ai_chat "Given this request, write a jq filter and an example. Only output the filter and a short example:\n$REQ"
25) Change-approval summary from config diffs
#!/usr/bin/env bash
set -euo pipefail; source ~/bin/ai.sh
DIFF="$(sudo git -C /etc diff -U1 | sed -n '1,1500p' || true)"
ai_chat "Summarize these /etc config changes for CAB approval: intent, risk, blast radius, and rollback steps.\n$DIFF"
Practical tips for reliability and safety
Scope and sample: Pipe only the last N lines or a targeted subset. Token limits are real.
Redact: Mask secrets before sending to any external endpoint.
Deterministic defaults: Use low temperature (0.0–0.3) for consistent outputs.
Local-first: For sensitive logs, use a local OpenAI-compatible server.
Logging: Keep AI outputs alongside raw evidence for audits.
Timeouts: Wrap curl with timeouts/retries for unattended jobs.
Conclusion and next steps (CTA)
You don’t need a platform overhaul to get AI into your ops. Start with: 1) Install curl and jq (plus tesseract/ffmpeg if needed). 2) Set AI_API_BASE, AI_API_KEY, and AI_MODEL. 3) Drop in ai.sh and pick 3 scripts above to pilot this week (e.g., SSH summary, explain error, incident draft).
From there, standardize prompts, add guardrails, and wire results into tickets or chat. Your shell is already your command center—now it’s intelligent.
If you found this useful, clone these snippets into a shared repo, open a PR with your own, and tag a teammate who still greps logs by hand.