- Posted on
- • Artificial Intelligence
25 Artificial Intelligence Bash Scripts Every Sysadmin Should Know
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
25 Artificial Intelligence Bash Scripts Every Sysadmin Should Know
If you’ve ever been buried under a mountain of logs, alerts, and “just-one-more-quick-asks,” you know the grind. The upside: AI can help—without tearing you away from your beloved shell. With a few small helper functions, you can wire AI into everyday Bash to summarize logs, triage alerts, explain errors, draft runbooks, and more—while keeping everything in your terminal workflow, auditable, and version-controlled.
This article shows you how to set up a simple, secure AI helper for Bash and then walks through 5 practical scripts you can use today. At the end, you’ll also find 20 more ideas to round out your own “25 AI scripts” toolkit.
Why AI-in-Bash is worth your time
It meets you where you work: terminal-first, scriptable, reproducible.
Minimal dependencies: HTTP + JSON tools are often enough.
Works with cloud APIs or local LLMs (for privacy/offline needs).
Easy to wrap with cron/systemd/timers and ship as part of your ops toolkit.
Keeps human-in-the-loop by design—AI suggests, you decide.
Prerequisites
You’ll need curl and jq at minimum. Some examples also use nmap.
Debian/Ubuntu (apt):
sudo apt update && sudo apt install -y curl jq nmap
RHEL/CentOS/Fedora (dnf):
sudo dnf install -y curl jq nmap
openSUSE/SLES (zypper):
sudo zypper refresh && sudo zypper install -y curl jq nmap
Optional: a local model server (e.g., Ollama). Ollama provides an install script on its website. It’s not installed via apt/dnf/zypper by default; follow Ollama’s official instructions if you prefer a local model.
A tiny AI library for Bash
Drop this file somewhere in your $PATH (for example, ~/bin/ai-lib.sh) and source it from your scripts. It supports:
OpenAI-compatible chat completions (cloud; requires
OPENAI_API_KEY)Ollama (local; no API key; runs on
http://127.0.0.1:11434by default)
Set environment:
AI_PROVIDER=openaiorAI_PROVIDER=ollamaFor OpenAI:
OPENAI_API_KEY=...AI_MODEL=gpt-4o-mini(or the model you prefer)
For Ollama:
OLLAMA_MODEL=llama3(or your local model)
#!/usr/bin/env bash
# File: ai-lib.sh
set -euo pipefail
command -v curl >/dev/null 2>&1 || { echo "curl is required"; exit 1; }
command -v jq >/dev/null 2>&1 || { echo "jq is required"; exit 1; }
AI_PROVIDER="${AI_PROVIDER:-openai}"
ask_ai() {
# Usage: ask_ai "your prompt text"
local prompt="${1:-}"
if [[ -z "$prompt" ]]; then
echo "ask_ai: prompt required" >&2
return 1
fi
case "$AI_PROVIDER" in
openai)
local api_key="${OPENAI_API_KEY:-}"
local model="${AI_MODEL:-gpt-4o-mini}"
if [[ -z "$api_key" ]]; then
echo "OPENAI_API_KEY is not set" >&2
return 1
fi
curl -sS https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer ${api_key}" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg m "$model" --arg p "$prompt" \
'{model:$m,temperature:0.2,messages:[{role:"system",content:"You are a helpful Linux systems assistant."},{role:"user",content:$p}]}')" \
| jq -r '.choices[0].message.content // empty'
;;
ollama)
local model="${OLLAMA_MODEL:-llama3}"
curl -sS http://127.0.0.1:11434/api/generate \
-H "Content-Type: application/json" \
-d "$(jq -n --arg m "$model" --arg p "$prompt" --argjson s false \
'{model:$m,prompt:$p,stream:$s}')" \
| jq -r '.response // empty'
;;
*)
echo "Unsupported AI_PROVIDER: $AI_PROVIDER" >&2
return 1
;;
esac
}
Security tips:
Never send sensitive logs to a cloud endpoint without approval/redaction.
Prefer local models (e.g., Ollama) for private data.
Log prompts/responses to a secure audit location for review.
5 practical AI Bash scripts to start using today
These are ready-to-adapt scripts. Save them (e.g., into ~/bin/), mark executable (chmod +x), and run. Each one sources ai-lib.sh.
1) AI-powered log summarizer
Summarize the last N lines of a service’s logs to spot anomalies faster.
#!/usr/bin/env bash
# File: ai-log-summary.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
source "${SCRIPT_DIR}/ai-lib.sh"
SERVICE="${1:-}"
LINES="${2:-400}"
if [[ -z "$SERVICE" ]]; then
echo "Usage: $0 <systemd-unit-or-keyword> [lines]" >&2
exit 1
fi
# Collect logs
LOGS="$(journalctl -u "$SERVICE" -n "$LINES" --no-pager 2>/dev/null || journalctl -n "$LINES" --no-pager | grep -i "$SERVICE" || true)"
if [[ -z "$LOGS" ]]; then
echo "No logs found for '$SERVICE'." >&2
exit 0
fi
# Trim to avoid very large prompts
TRIMMED="$(echo "$LOGS" | tail -n "$LINES")"
PROMPT=$(cat <<'EOF'
You are assisting a Linux sysadmin. Given these recent service logs:
---
%s
---
1) Summarize key events and anomalies.
2) Identify likely root causes or patterns.
3) Suggest 3 focused next steps with concrete commands (do not execute them).
Only include actionable info; be concise.
EOF
)
printf -v FINAL_PROMPT "$PROMPT" "$TRIMMED"
ask_ai "$FINAL_PROMPT"
Usage:
AI_PROVIDER=openai OPENAI_API_KEY=... ./ai-log-summary.sh sshd 600or
AI_PROVIDER=ollama ./ai-log-summary.sh nginx
Tip: Wire this to a systemd timer to drop an hourly summary into a shared channel.
2) Alert triage and runbook hints
Plug this into your alert pipeline (stdin or file). It classifies severity, explains likely impact, and suggests next steps.
#!/usr/bin/env bash
# File: ai-alert-triage.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
source "${SCRIPT_DIR}/ai-lib.sh"
INPUT="$(cat -)"
if [[ -z "$INPUT" ]]; then
echo "Usage: produce alert text or JSON to stdin" >&2
exit 1
fi
PROMPT=$(cat <<'EOF'
You are assisting an on-call SRE. Here is an alert payload or text:
---
%s
---
Classify:
- Severity (P1-P5): and why.
- Blast radius and business impact.
- Likely root cause hints.
- 3 immediate steps to triage safely.
- 3 remediation ideas (with example commands; do not auto-execute).
- If noisy/false-positive is suspected, suggest alert tuning ideas.
Return in clear, short bullet points.
EOF
)
printf -v FINAL_PROMPT "$PROMPT" "$INPUT"
ask_ai "$FINAL_PROMPT"
Usage:
cat alert.json | AI_PROVIDER=openai OPENAI_API_KEY=... ./ai-alert-triage.shOr pipe text like
echo "High CPU on node X..." | AI_PROVIDER=ollama ./ai-alert-triage.sh
3) Explain an error and propose a safe fix
Wrap failing commands to get quick diagnoses and suggested fixes you can review before execution.
#!/usr/bin/env bash
# File: ai-explain-error.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
source "${SCRIPT_DIR}/ai-lib.sh"
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <command...>" >&2
exit 1
fi
set +e
OUTPUT="$("$@" 2>&1)"
EXIT_CODE=$?
set -e
PROMPT=$(cat <<'EOF'
You are helping a Linux sysadmin. A command failed with this output:
---
%s
---
1) Explain why it likely failed.
2) Propose up to 3 safe, minimal fixes (show example commands but do NOT run them).
3) Note any risks or data loss concerns.
Be precise and concise.
EOF
)
printf -v FINAL_PROMPT "$PROMPT" "$OUTPUT"
ask_ai "$FINAL_PROMPT"
exit "$EXIT_CODE"
Usage:
AI_PROVIDER=openai OPENAI_API_KEY=... ./ai-explain-error.sh rsync -a /src /dstAI_PROVIDER=ollama ./ai-explain-error.sh systemctl restart imaginary.service
4) Nmap to risk summary
Convert quick port scans into a human-readable risk summary and action list.
#!/usr/bin/env bash
# File: ai-nmap-risk.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
source "${SCRIPT_DIR}/ai-lib.sh"
TARGET="${1:-}"
if [[ -z "$TARGET" ]]; then
echo "Usage: $0 <host-or-cidr>" >&2
exit 1
fi
SCAN="$(nmap -sV --version-light -Pn --open "$TARGET" 2>/dev/null || true)"
PROMPT=$(cat <<'EOF'
You are a security-savvy sysadmin assistant. Analyze this nmap -sV output:
---
%s
---
Provide:
- Top 5 risks or misconfigurations (short bullets).
- Concrete remediation steps (commands/examples; do not execute).
- Services to monitor closely and why.
- Items safe to ignore (with rationale).
Keep it practical and terse.
EOF
)
printf -v FINAL_PROMPT "$PROMPT" "$SCAN"
ask_ai "$FINAL_PROMPT"
Usage:
AI_PROVIDER=ollama ./ai-nmap-risk.sh 192.168.1.0/24AI_PROVIDER=openai OPENAI_API_KEY=... ./ai-nmap-risk.sh example.com
Note: Ensure you’re authorized to scan the target.
5) Generate a parser for a weird log
When you encounter an unfamiliar log format, have AI propose an awk script that outputs CSV. Always review before you run.
#!/usr/bin/env bash
# File: ai-log-parser-gen.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
source "${SCRIPT_DIR}/ai-lib.sh"
SAMPLE_FILE="${1:-}"
if [[ -z "$SAMPLE_FILE" || ! -f "$SAMPLE_FILE" ]]; then
echo "Usage: $0 <sample-log-file>" >&2
exit 1
fi
SAMPLE="$(head -n 50 "$SAMPLE_FILE")"
PROMPT=$(cat <<'EOF'
You are helping parse an unfamiliar log. Given these sample lines:
---
%s
---
Task:
1) Propose a robust awk script that parses the lines and emits CSV with stable headers.
2) Handle common edge cases (missing fields, extra spaces).
3) Print only the final awk script (no commentary).
Fields should reflect what's visible in the sample.
EOF
)
printf -v FINAL_PROMPT "$PROMPT" "$SAMPLE"
SCRIPT_TEXT="$(ask_ai "$FINAL_PROMPT" || true)"
echo "Proposed awk script:"
echo "--------------------"
echo "$SCRIPT_TEXT"
echo "--------------------"
echo "Review carefully, then test like:"
echo " awk -f <(printf '%s\n' \"$SCRIPT_TEXT\") '$SAMPLE_FILE' | head"
Usage:
AI_PROVIDER=openai OPENAI_API_KEY=... ./ai-log-parser-gen.sh /var/log/custom.logAI_PROVIDER=ollama ./ai-log-parser-gen.sh ./samples/weird.log
Safety: Inspect the generated awk before use in production.
20 more AI-in-Bash ideas to round out your 25
Use the same ask_ai helper. These can be short one-liners or small scripts.
Draft a postmortem from incident notes.
Summarize a long
journalctlexcerpt into “what changed since last deploy.”Convert a noisy alert policy into a tuned version with rate limits and better thresholds.
Turn
diffoutput (config changes) into a customer-facing change log.Generate firewall rule explanations for auditors (from iptables/nftables dumps).
Suggest logrotate policies after inspecting current log growth.
Explain a complex
find | xargs | sed | awkpipeline in plain language.From
df -handdu -shsamples, suggest cleanup targets and policies.Propose systemd unit hardening (e.g.,
ProtectSystem=...,NoNewPrivileges=...) for a given unit file.Take a curl of an HTTP 500 page + server logs and propose triage steps.
Classify tickets into categories with recommended runbooks.
Create onboarding notes for a new service from its README and systemd units.
Generate Prometheus alert annotations that are actually helpful (links, checks).
From
toporpidstatoutput, suggest likely offenders and follow-up probes.Suggest backup verification steps and a test matrix based on your backup logs.
Propose SQL to summarize an app’s slow query log (works great with sqlite or MySQL samples).
Turn a Linux kernel oops into a readable summary with possible triggers.
Suggest SLO/SLI definitions after reviewing access logs and error rates.
Convert a list of endpoints into a periodic healthcheck script with retries and jitter.
Generate a minimal runbook from an application’s Grafana dashboard JSON.
Pro tip: build a small repo with these scripts, plus a Makefile and a .env (never commit secrets) so your team can adopt them quickly.
Privacy, safety, and good hygiene
Redact or anonymize sensitive data before sending to cloud models.
Prefer local LLMs for private logs or regulated environments.
Do not auto-execute AI-suggested commands; require human review.
Log prompts and outputs to a secure location for auditing.
Add rate limits and budget guards for API usage.
Conclusion and next steps
You don’t need a whole new platform to get value from AI. A few lines of Bash and a reliable model endpoint can supercharge triage, summarization, and documentation right where you work. Start with the 5 scripts here, then expand to your own “25” using the ideas list.
Next steps:
Install prerequisites: curl, jq, nmap (via apt/dnf/zypper as shown above).
Drop
ai-lib.shinto your toolbox and setAI_PROVIDER+ credentials if needed.Pick one high-friction task this week and wrap it with AI.
Share your best scripts with your team and standardize them with cron/systemd.
Your terminal just got smarter—keep it safe, auditable, and useful.