2026 年自托管 AI:使用 Ollama 和 Bash 自动化您的 Linux 工作流

发布: (2026年2月16日 GMT+8 19:49)
3 分钟阅读
原文: Dev.to

Source: Dev.to

Cover image for Self-Hosted AI in 2026: Automating Your Linux Workflow with Ollama and Bash

为什么要自托管 AI 用于自动化?

  • 隐私 – 您的系统日志、内部脚本和服务器配置永远不会离开本机。
  • 零延迟 – 不需要往返外部服务器。
  • 成本 – 运行 Llama 3 或 Mistral 等模型的费用仅为电费。
  • 离线能力 – 即使没有网络,您的自动化仍然可以工作。

搭建基础:Ollama + systemd

安装

curl -fsSL https://ollama.com/install.sh | sh

systemd 服务

Ollama 的安装程序通常会为您创建一个服务。验证并设置开机自启:

sudo systemctl daemon-reload
sudo systemctl enable ollama
sudo systemctl start ollama

检查状态:

systemctl status ollama

提升层次:“AI‑SysAdmin” Bash 脚本

ask-ai.sh 脚本

#!/bin/bash

# A simple wrapper to interact with local Ollama for Linux tasks
MODEL="llama3"   # You can use mistral, codellama, etc.
PROMPT="You are a senior Linux SysAdmin. Output only the bash commands needed to fulfill the request. No explanation unless asked."

if [ -z "$1" ]; then
    echo "Usage: ./ask-ai.sh 'Your request here'"
    exit 1
fi

REQUEST="$1"

# Combine context and request
FULL_PROMPT="$PROMPT\n\nRequest: $REQUEST"

# Call Ollama API via curl (local only)
RESPONSE=$(curl -s http://localhost:11434/api/generate -d "{
  \"model\": \"$MODEL\",
  \"prompt\": \"$FULL_PROMPT\",
  \"stream\": false
}")

# Extract response (requires jq)
COMMAND=$(echo "$RESPONSE" | jq -r '.response')

echo -e "\033[1;34mAI Suggestion:\033[0m"
echo "$COMMAND"

# Ask for confirmation before executing
read -p "Execute these commands? (y/N): " confirm
if [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]]; then
    eval "$COMMAND"
else
    echo "Execution cancelled."
fi

使用方法

  1. 赋予脚本可执行权限:chmod +x ask-ai.sh
  2. 安装 jq(JSON 解析器):sudo apt install jq(或您发行版对应的命令)。
  3. 运行请求,例如:
./ask-ai.sh "Find all files larger than 100MB in /var/log and show their sizes"

专业提示:安排维护任务

将脚本与 cronsystemd timers 结合,实现周期性维护。下面是每周日凌晨 3 点运行的 cron 示例:

0 3 * * 0 /path/to/ask-ai.sh "Check for broken symlinks in /usr/local/bin and log them to /var/log/ai_cleanup.log" --auto

(为脚本添加 --auto 参数,以在自动化任务中跳过确认提示。)

总结与参考

自托管 AI 不仅仅是聊天,它还能帮助构建更智能、更自主的环境。通过在 Bash 中封装 Ollama,您可以把语言模型变成 DevOps 工具箱中的功能成员。

参考资料与进一步阅读

0 浏览
Back to Blog

相关文章

阅读更多 »

n8n 是纯粹的精彩

!Miguel Valdeshttps://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2...