自动化工作流是 AI 被低估的能力之一。写 Shell 脚本、编排 CI/CD、处理批量文件——这些重复性的”基建”工作,AI 能帮你快速完成,节省大量机械操作的时间。
一、Shell 脚本生成 Shell 脚本是最常见的自动化工具。用自然语言描述需求,AI 能直接生成可用的脚本。
1.1 文件清理脚本 写一个 PowerShell 脚本,自动清理超过 100MB 的日志文件:
1 2 3 4 5 6 写一个 PowerShell 脚本: - 扫描当前目录及子目录下所有 .log 文件 - 文件超过 100MB 的自动压缩后删除原文件 - 压缩后的文件以原始名+.zip 命名 - 输出操作日志到 cleanup.log - 显示总共释放了多少空间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 $logFile = "cleanup.log" $cutoffSize = 100 MB$totalFreed = 0 Get-ChildItem -Recurse -Filter *.log | Where-Object { $_ .Length -gt $cutoffSize } | ForEach-Object { $zipPath = "$ ($_ .DirectoryName)\$ ($_ .BaseName).zip" Compress-Archive -Path $_ .FullName -DestinationPath $zipPath $freed = $_ .Length $totalFreed += $freed Remove-Item -Path $_ .FullName "$ (Get-Date): Compressed $ ($_ .Name) ($ ('{0:N2}' -f ($freed /1MB)) MB → zip)" | Out-File $logFile -Append } "总计释放: $ ('{0:N2}' -f ($totalFreed /1MB)) MB" | Out-File $logFile -Append
1.2 批量重命名脚本 1 2 3 4 5 写一个 Bash 脚本: - 将 src/ 下所有 .js 文件重命名为 .ts - 如果同名 .ts 已存在,添加 _migrated 后缀 - 输出重命名映射表到 rename.log - 只处理文件,跳过目录和符号链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #!/bin/bash log ="rename.log" > "$log " count=0 for file in src/*.js; do [ -f "$file " ] || continue base="${file%.js} " target="${base} .ts" if [ -f "$target " ]; then target="${base} _migrated.ts" fi mv "$file " "$target " echo "$file → $target " >> "$log " ((count++)) done echo "完成:$count 个文件已重命名"
二、文件批量处理 除了 Shell 脚本,Python 脚本在处理复杂逻辑时更灵活。
2.1 批量替换文件内容 用 Python 脚本批量替换文件中的内容:
1 2 3 4 5 写一个 Python 脚本: - 遍历 source/ 目录下所有 .md 文件 - 将图片链接从旧路径替换为新路径 - 保存到 output/ 目录,保持目录结构 - 输出处理报告
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import osimport resource_dir = "source" output_dir = "output" old_base = "/images/old/" new_base = "/images/new/" report = [] for root, dirs, files in os.walk(source_dir): for file in files: if not file.endswith('.md' ): continue src_path = os.path.join(root, file) rel_path = os.path.relpath(src_path, source_dir) dst_path = os.path.join(output_dir, rel_path) os.makedirs(os.path.dirname(dst_path), exist_ok=True ) with open (src_path, 'r' , encoding='utf-8' ) as f: content = f.read() new_content = content.replace(old_base, new_base) changes = content.count(old_base) with open (dst_path, 'w' , encoding='utf-8' ) as f: f.write(new_content) if changes > 0 : report.append(f"{rel_path} : 替换了 {changes} 处链接" ) print (f"处理完成。共处理 {len (report)} 个文件:" )for line in report: print (f" - {line} " )
2.2 批量图片压缩 1 2 3 4 5 写一个 Python 脚本,批量压缩 source/img 下的图片: - 支持 jpg/png/webp - 压缩到指定质量(默认 80%) - 覆盖原文件前备份到 backup/ 目录 - 输出压缩前后的文件大小对比
AI 会生成完整的图片处理脚本,使用 Pillow 库进行压缩,包含备份机制和进度显示。
三、GitHub Actions + AI 编排 3.1 自动生成 CI 配置文件 1 2 3 4 5 为我的 Next.js 项目生成 GitHub Actions CI 配置: - 分支:main - 触发条件:push 和 pull_request - 步骤:Checkout → npm ci → lint → test → build → deploy - 使用缓存加速
AI 会生成完整的 YAML 文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 name: CI on: push: branches: [main ] pull_request: branches: [main ] jobs: ci: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 20 cache: 'npm' - run: npm ci - run: npm run lint - name: Run tests run: npm test - name: Build run: npm run build - name: Deploy if: github.ref == 'refs/heads/main' && github.event_name == 'push' run: npm run deploy env: DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
3.2 AI 驱动的自动化工作流 在项目代码中,AI 也可以帮你实现业务逻辑的自动化:
1 2 3 4 5 每次向 main 分支推送博文时: 1. 自动触发部署 2. 生成变更日志(git log) 3. 预热 CDN 4. 部署失败时发送通知
对应的自动化脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 #!/bin/bash echo "=== 部署后自动化 ===" echo "## 变更日志 ($(date +%Y-%m-%d) )" > CHANGELOG-latest.mdgit log --oneline --no-merges HEAD~5..HEAD >> CHANGELOG-latest.md curl -s -o /dev/null -w "CDN 预热: %{http_code}\n" \ -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE /purge_cache" \ -H "Authorization: Bearer $CF_TOKEN " \ -H "Content-Type: application/json" \ -d '{"purge_everything":true}' sleep 10status=$(curl -s -o /dev/null -w "%{http_code}" https://example.com) if [ "$status " != "200" ]; then echo "健康检查失败 (HTTP $status ),执行回滚..." git revert HEAD --no-edit npm run build echo "已自动回滚,请检查部署" fi
3.3 AI 生成 Workflow 模板库
场景
Prompt 示例
生成内容
NPM 发布
“每次推 tag 时自动发布到 NPM”
.github/workflows/npm-publish.yml
Docker 构建
“main 分支 push 时构建并推送 Docker 镜像”
.github/workflows/docker-build.yml
自动部署
“PR 合并到 main 后自动部署到 Vercel”
.github/workflows/deploy-vercel.yml
代码检查
“每个 PR 自动运行 lint + test + typecheck”
.github/workflows/pr-check.yml
四、定时任务与监控 4.1 系统健康检查 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 """ AI 生成:系统健康检查脚本 每 5 分钟检查 CPU、内存、磁盘、关键进程 超过阈值时发送通知 """ import psutilimport requestsimport jsonTHRESHOLDS = { 'cpu' : 80 , 'memory' : 85 , 'disk' : 90 , } def check_system (): alerts = [] cpu = psutil.cpu_percent(interval=1 ) if cpu > THRESHOLDS['cpu' ]: alerts.append(f"CPU 使用率 {cpu} % (阈值: {THRESHOLDS['cpu' ]} %)" ) memory = psutil.virtual_memory() if memory.percent > THRESHOLDS['memory' ]: alerts.append(f"内存使用率 {memory.percent} % (阈值: {THRESHOLDS['memory' ]} %)" ) for part in psutil.disk_partitions(): usage = psutil.disk_usage(part.mountpoint) if usage.percent > THRESHOLDS['disk' ]: alerts.append(f"磁盘 {part.mountpoint} {usage.percent} %" ) if alerts: webhook_url = "https://hooks.example.com/alert" requests.post(webhook_url, json={"text" : "\n" .join(alerts)}) return len (alerts) if __name__ == "__main__" : alert_count = check_system() print (f"检查完成,{alert_count} 个告警" )
4.2 定时任务配置 AI 除了生成检查脚本,还能生成对应的定时任务配置(Linux crontab / Windows Task Scheduler):
1 2 3 4 为健康检查脚本生成 crontab 配置: - 每 5 分钟执行一次 - 日志输出到 /var/log/healthcheck.log - 只保留最近 30 天的日志
1 2 3 4 5 6 7 8 9 10 11 */5 * * * * /usr/bin/python3 /opt/scripts/healthcheck.py >> /var/log/healthcheck.log 2>&1 /var/log/healthcheck.log { daily rotate 30 compress missingok notifempty }
五、AI 自动化编程的安全实践 自动化脚本涉及文件操作和系统命令,安全是首要考虑:
原则
说明
实践方法
干运行
先看 AI 计划做什么,再执行
提示 AI 先输出计划再写代码
分步确认
每一步操作都让 AI 展示 diff
Git add -p 逐块审查
回滚机制
确保操作可逆
操作前自动备份或 Git commit
权限最小化
限制脚本的文件和网络权限
指定目录白名单
日志审计
记录所有操作
自动生成操作日志文件
本章小结
Shell 脚本生成是 AI 最直接的高效工具,复杂脚本秒级生成
文件批量处理用 Python 脚本配合 AI 描述,逻辑更灵活
GitHub Actions 配置可通过 AI 快速生成,覆盖 CI/CD 全部场景
定时任务和监控脚本让运维自动化,AI 生成后微调即可使用
自动化脚本要注重安全机制(干运行、分步确认、回滚、审计)
AI 在自动化领域的最大价值是:把”想清楚怎么做”的时间从小时级压缩到分钟级
下一篇进入高级进阶篇——构建 RAG 知识库。