Posted on
Artificial Intelligence

Artificial Intelligence Linux Case Studies

Author
  • User
    linuxbash
    Posts by this author
    Posts by this author

Artificial Intelligence on Linux: 4 Bash‑Friendly Case Studies You Can Reproduce Today

If you think AI only lives in the cloud or behind proprietary APIs, you’re leaving performance, privacy, and control on the table. Your Linux box—with nothing more than Bash, your package manager, and a few small models—can deliver practical AI that saves time and surfaces insights. In this post, we’ll walk through four reproducible case studies you can run locally across popular distros, complete with apt, dnf, and zypper install instructions.

What you’ll get:

  • Why Linux is a natural fit for AI workflows.

  • 4 real-world examples you can try today (with CPU-friendly models).

  • Copy/paste commands and scripts for quick wins.

  • Steps to automate with cron/systemd.

Why AI on Linux (and Bash) is the real deal

  • Reproducibility: Scripts and environments you can version, diff, and ship.

  • Privacy: Process sensitive logs, audio, and images locally—no third-party data leaks.

  • Cost and performance: Tiny or quantized models run well on commodity CPUs.

  • Composability: Bash is the glue; chain tools with pipes, cron, and systemd timers.


Case Study 1: Anomaly Detection in Auth Logs with Isolation Forest

Goal: Flag unusual SSH/auth activity (e.g., brute-force attempts) from journal logs using classic ML, then email a summary.

Prerequisites (choose your distro):

  • Debian/Ubuntu (apt)
sudo apt update
sudo apt install -y python3 python3-venv python3-pip cron mailutils
sudo systemctl enable --now cron
  • Fedora/RHEL (dnf)
sudo dnf install -y python3 python3-pip python3-virtualenv cronie mailx
sudo systemctl enable --now crond
  • openSUSE (zypper)
sudo zypper install -y python3 python3-pip python3-virtualenv cron mailx
sudo systemctl enable --now cron

Set up environment:

mkdir -p ~/ai-log-guard && cd ~/ai-log-guard
python3 -m venv .venv
source .venv/bin/activate
pip install scikit-learn

Grab log lines and detect anomalies. Save as detect_anomalies.py:

#!/usr/bin/env python3
import sys
from sklearn.ensemble import IsolationForest
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

lines = [l.strip() for l in sys.stdin if l.strip()]
if not lines:
    sys.exit(0)

# Vectorize message text
vec = TfidfVectorizer(max_features=5000)
X = vec.fit_transform(lines)

# Fit Isolation Forest
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=42)
pred = iso.fit_predict(X)  # -1 = anomaly, 1 = normal
scores = iso.decision_function(X)

# Collect anomalies with severity score
anoms = [(lines[i], scores[i]) for i, p in enumerate(pred) if p == -1]
# Sort by most anomalous (lower score = more anomalous)
anoms.sort(key=lambda t: t[1])

if anoms:
    print("Anomalous auth/journal entries (most suspicious first):\n")
    for msg, s in anoms[:50]:
        print(f"[score={s:.4f}] {msg}")

Run on-demand (journalctl output only message text via -o cat):

journalctl -u ssh.service -S "24 hours ago" -o cat \
  | python3 detect_anomalies.py

Automate with cron to email results if any anomalies are found (replace email):

( crontab -l 2>/dev/null; echo '*/30 * * * * journalctl -u ssh.service -S "-30 min" -o cat | /home/$USER/ai-log-guard/.venv/bin/python3 /home/$USER/ai-log-guard/detect_anomalies.py | grep -q . && (journalctl -u ssh.service -S "-30 min" -o cat | /home/'"$USER"'/ai-log-guard/.venv/bin/python3 /home/'"$USER"'/ai-log-guard/detect_anomalies.py | mail -s "SSH anomaly report" you@example.com)'; ) | crontab -

Tip: Tune contamination to set how sensitive the detector is.


Case Study 2: CPU‑Only Image Classification from a Webcam with ONNX Runtime

Goal: Capture a single frame from your webcam, run a compact ImageNet classifier (SqueezeNet) on CPU, and print the top predictions.

Prerequisites (choose your distro):

  • Debian/Ubuntu (apt)
sudo apt update
sudo apt install -y fswebcam python3 python3-venv python3-pip wget
  • Fedora/RHEL (dnf)
sudo dnf install -y fswebcam python3 python3-pip python3-virtualenv wget
  • openSUSE (zypper)
sudo zypper install -y fswebcam python3 python3-pip python3-virtualenv wget

Set up environment and model:

mkdir -p ~/ai-cv && cd ~/ai-cv
python3 -m venv .venv
source .venv/bin/activate
pip install onnxruntime pillow numpy

# Download SqueezeNet ONNX model and ImageNet labels
wget -O squeezenet1.1-7.onnx https://github.com/onnx/models/raw/main/vision/classification/squeezenet/model/squeezenet1.1-7.onnx
wget -O imagenet_classes.txt https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt

Capture a frame:

fswebcam -r 640x480 --no-banner frame.jpg

Classify. Save as classify.py:

#!/usr/bin/env python3
import onnxruntime as ort
from PIL import Image
import numpy as np
import sys

img_path = sys.argv[1] if len(sys.argv) > 1 else "frame.jpg"
labels = [l.strip() for l in open("imagenet_classes.txt", "r").readlines()]

# Preprocess to 224x224 with ImageNet normalization
img = Image.open(img_path).convert("RGB").resize((224, 224))
arr = np.asarray(img).astype(np.float32) / 255.0
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
std  = np.array([0.229, 0.224, 0.225], dtype=np.float32)
arr = (arr - mean) / std
arr = np.transpose(arr, (2, 0, 1))  # HWC -> CHW
arr = np.expand_dims(arr, 0)        # NCHW

sess = ort.InferenceSession("squeezenet1.1-7.onnx", providers=["CPUExecutionProvider"])
inp_name = sess.get_inputs()[0].name
out = sess.run(None, {inp_name: arr})[0][0]  # shape [1000]
# Softmax for readability
exps = np.exp(out - out.max())
probs = exps / exps.sum()
topk = probs.argsort()[-5:][::-1]
for idx in topk:
    print(f"{labels[idx]}: {probs[idx]*100:.2f}%")

Run:

python3 classify.py frame.jpg

Note: If you prefer a live loop, wrap fswebcam and classify.py in a while loop with sleeps.


Case Study 3: Local LLM Log Summaries with ctransformers (TinyLlama, no GPU)

Goal: Summarize error logs on your machine using a small, local LLM—no Internet required—via the ctransformers CPU backend and a quantized GGUF model.

Prerequisites (choose your distro):

  • Debian/Ubuntu (apt)
sudo apt update
sudo apt install -y python3 python3-venv python3-pip wget
  • Fedora/RHEL (dnf)
sudo dnf install -y python3 python3-pip python3-virtualenv wget
  • openSUSE (zypper)
sudo zypper install -y python3 python3-pip python3-virtualenv wget

Set up environment and download a compact chat model:

mkdir -p ~/ai-llm && cd ~/ai-llm
python3 -m venv .venv
source .venv/bin/activate
pip install ctransformers

# TinyLlama 1.1B chat, quantized (example GGUF)
wget -O tinyllama.gguf "https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/TinyLlama-1.1B-Chat-v1.0.Q4_K_M.gguf?download=true"

Summarizer script summarize.py:

#!/usr/bin/env python3
import sys, argparse, textwrap
from ctransformers import AutoModelForCausalLM

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", default="tinyllama.gguf")
ap.add_argument("-p", "--prompt", default="Summarize and group the key issues succinctly.")
args = ap.parse_args()

text = sys.stdin.read().strip()
if not text:
    sys.exit(0)

model = AutoModelForCausalLM.from_pretrained(
    model_path=args.model,
    model_type="llama",
    gpu_layers=0,
)

full_prompt = f"""You are a helpful Linux SRE assistant.
Input logs:
{text[:8000]}

Task: {args.prompt}
Answer:"""

out = model(full_prompt, max_new_tokens=256, temperature=0.2)
print(out.strip())

Example: summarize today’s SSH errors (adjust unit and scope as needed):

journalctl -p err -u ssh.service -S today -o cat \
  | python3 summarize.py -m tinyllama.gguf -p "Summarize SSH errors, group by cause, and list likely remediations."

Note:

  • Small models are fast but less accurate than larger ones; tailor prompts and keep inputs short for best results.

  • You can swap TinyLlama for any compatible GGUF model if you have more CPU/RAM headroom.


Case Study 4: Offline Voice-to-Bash with Vosk and arecord

Goal: Speak a short command (e.g., “disk space”) and run a safe, whitelisted Bash action offline using Vosk speech recognition.

Prerequisites (choose your distro):

  • Debian/Ubuntu (apt)
sudo apt update
sudo apt install -y alsa-utils python3 python3-venv python3-pip wget
  • Fedora/RHEL (dnf)
sudo dnf install -y alsa-utils python3 python3-pip python3-virtualenv wget
  • openSUSE (zypper)
sudo zypper install -y alsa-utils python3 python3-pip python3-virtualenv wget

Set up environment and model:

mkdir -p ~/ai-voice && cd ~/ai-voice
python3 -m venv .venv
source .venv/bin/activate
pip install vosk

# Download a small English model (~50–70MB)
wget -O vosk-model-small-en-us-0.15.zip https://alphacephei.com/vosk/models/vosk-model-small-en-us-0.15.zip
unzip vosk-model-small-en-us-0.15.zip
mv vosk-model-small-en-us-0.15 model

Recorder + command runner voice_cmd.py:

#!/usr/bin/env python3
import json, subprocess, sys, wave, os, time
from vosk import Model, KaldiRecognizer

MODEL_DIR = "model"

# Map short phrases to safe commands
WHITELIST = {
    "disk space": "df -h",
    "memory usage": "free -h",
    "list docker": "docker ps",
    "list podman": "podman ps",
    "show ip": "ip -brief a",
    "uptime": "uptime -p",
}

def record_wav(path="input.wav", seconds=4, rate=16000):
    # Ensure mono 16k WAV via arecord (ALSA)
    subprocess.run([
        "arecord", "-q", "-f", "S16_LE", "-r", str(rate), "-c", "1", path, "trim", "0", str(seconds)
    ], check=True)

def transcribe(path="input.wav"):
    model = Model(MODEL_DIR)
    rec = KaldiRecognizer(model, 16000)
    wf = wave.open(path, "rb")
    assert wf.getnchannels() == 1 and wf.getframerate() == 16000
    data = wf.readframes(4000)
    text = ""
    while data:
        if rec.AcceptWaveform(data):
            text = json.loads(rec.Result()).get("text", "")
        data = wf.readframes(4000)
    final = json.loads(rec.FinalResult()).get("text", "")
    return (final or text).strip()

def run_command(text):
    for phrase, cmd in WHITELIST.items():
        if phrase in text:
            print(f"> {cmd}")
            subprocess.run(cmd, shell=True, check=False)
            return True
    print("No whitelisted command matched.")
    return False

if __name__ == "__main__":
    print("Speak after the beep…")
    time.sleep(0.5)
    print("\a")  # terminal beep
    record_wav()
    txt = transcribe()
    print(f"Heard: {txt!r}")
    run_command(txt)

Run it:

python3 voice_cmd.py

Security tip: Only execute whitelisted commands. Never run arbitrary transcriptions.

Optional container tooling installs (if you want “list docker/podman” to work):

  • Debian/Ubuntu (apt)
sudo apt update
sudo apt install -y docker.io podman
  • Fedora/RHEL (dnf)
sudo dnf install -y podman docker
sudo systemctl enable --now docker
  • openSUSE (zypper)
sudo zypper install -y podman docker
sudo systemctl enable --now docker

Pro Tips for Productionizing

  • Use systemd timers over cron for richer scheduling and logging.

  • Log everything to a single working directory and rotate with logrotate.

  • Pin Python package versions in a requirements.txt for reproducibility.

  • For speed, try ONNX Runtime’s OpenVINO or DirectML providers on supported hardware; otherwise CPU EP is fine.

  • Keep models small and inputs trimmed; pre-filter with grep/jq to feed only relevant text to LLMs.


Conclusion and Call to Action

You don’t need GPUs or cloud credits to put AI to work. With Linux and Bash, you can:

  • Detect oddities in logs.

  • Classify images from a webcam.

  • Summarize system errors locally with a tiny LLM.

  • Trigger safe shell actions by voice—offline.

Pick one case study and run it today on your distro. Then:

  • Extend it (e.g., push reports to a private Git repo or send to a Matrix/Slack webhook).

  • Swap models as your needs grow.

  • Share your scripts and lessons learned with your team.

If you want a follow-up, tell me which scenario you’d like to see expanded (GPU acceleration, containers, or full CI/CD integration), and I’ll publish a deeper dive.