Scripting & Automation - Guía de Entorno¶
Guía completa para scripting, automatización de sistemas y tareas con Claude Code.
Capacidades de Claude Code¶
| Capacidad | Herramientas |
|---|---|
| Shell Scripting | Bash, Zsh, Fish |
| Windows Automation | PowerShell, Batch, WinRM |
| Cross-platform | Python, Node.js |
| Task Automation | Make, Just, Task |
| Desktop Automation | AutoHotkey, PyAutoGUI |
| Web Scraping | Playwright, Puppeteer, Scrapy |
| File Processing | awk, sed, jq, yq |
Shell Scripting¶
Bash¶
# Verificar versión
bash --version
# Shebang recomendado
#!/usr/bin/env bash
set -euo pipefail # Modo estricto
# Estructura de script
#!/usr/bin/env bash
set -euo pipefail
# Variables
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly LOG_FILE="/var/log/myscript.log"
# Funciones
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"
}
main() {
log "Script iniciado"
# Lógica principal
log "Script completado"
}
main "$@"
Zsh¶
# macOS default shell
zsh --version
# Oh My Zsh
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
# Plugins útiles
# ~/.zshrc
plugins=(
git
docker
kubectl
z
fzf
zsh-autosuggestions
zsh-syntax-highlighting
)
Fish¶
# Instalar
brew install fish # macOS
sudo apt install fish # Linux
# Configurar como default
chsh -s /usr/bin/fish
# Sintaxis diferente (más simple)
# ~/.config/fish/config.fish
set -x PATH $HOME/.local/bin $PATH
function backup
tar -czf backup-(date +%Y%m%d).tar.gz $argv
end
PowerShell¶
Instalación¶
# Windows: preinstalado (pwsh para PS 7+)
winget install Microsoft.PowerShell
# macOS
brew install powershell/tap/powershell
# Linux
sudo apt install powershell
# Verificar
pwsh --version # PowerShell 7+
Scripting PowerShell¶
# Script template
#Requires -Version 7.0
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# Parámetros
param(
[Parameter(Mandatory=$true)]
[string]$Path,
[switch]$Force
)
# Funciones
function Write-Log {
param([string]$Message)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"[$timestamp] $Message" | Tee-Object -FilePath $LogFile -Append
}
# Main
try {
Write-Log "Script iniciado"
# Lógica
Write-Log "Script completado"
}
catch {
Write-Log "Error: $_"
throw
}
Módulos Útiles¶
# PSReadLine (mejor autocompletado)
Install-Module PSReadLine -Force
# Posh-Git (Git integration)
Install-Module posh-git -Force
# Terminal-Icons
Install-Module Terminal-Icons -Force
# ImportExcel (manipular Excel sin Office)
Install-Module ImportExcel -Force
# Pester (testing)
Install-Module Pester -Force
Python para Scripting¶
Setup¶
# Python 3.11+
python --version
# Librerías útiles para scripting
pip install rich # Output bonito
pip install typer # CLI apps
pip install click # CLI alternativa
pip install pydantic # Validación
pip install python-dotenv # Variables de entorno
pip install requests # HTTP
pip install schedule # Tareas programadas
pip install watchdog # File watching
Script Template¶
#!/usr/bin/env python3
"""Script description."""
import sys
import logging
from pathlib import Path
from typing import Optional
import typer
from rich.console import Console
from rich.logging import RichHandler
# Setup
console = Console()
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[RichHandler(rich_tracebacks=True)]
)
log = logging.getLogger(__name__)
app = typer.Typer()
@app.command()
def main(
path: Path = typer.Argument(..., help="Path to process"),
verbose: bool = typer.Option(False, "--verbose", "-v"),
):
"""Main command description."""
if verbose:
logging.getLogger().setLevel(logging.DEBUG)
log.info(f"Processing {path}")
# Lógica
console.print("[green]Completado![/green]")
if __name__ == "__main__":
app()
Task Runners¶
Make¶
# Makefile
.PHONY: install build test deploy clean
# Variables
APP_NAME := myapp
VERSION := $(shell git describe --tags --always)
# Targets
install:
pip install -r requirements.txt
build:
docker build -t $(APP_NAME):$(VERSION) .
test:
pytest tests/ -v
deploy: build test
kubectl apply -f k8s/
clean:
rm -rf dist/ build/ *.egg-info
find . -type d -name __pycache__ -exec rm -rf {} +
# Con argumentos
run-%:
python -m $(APP_NAME) $*
Just (Moderno, recomendado)¶
# Instalar
cargo install just
# o
brew install just
# justfile
set dotenv-load
# Variables
app_name := "myapp"
version := `git describe --tags --always`
# Recipes
default:
@just --list
install:
pip install -r requirements.txt
build:
docker build -t {{app_name}}:{{version}} .
test *args:
pytest {{args}}
deploy env="staging":
kubectl --context={{env}} apply -f k8s/
# Ejecutar
just build
just test -v
just deploy production
Task (Go)¶
# Instalar
go install github.com/go-task/task/v3/cmd/task@latest
# o
brew install go-task
# Taskfile.yml
version: '3'
vars:
APP_NAME: myapp
tasks:
build:
cmds:
- go build -o {{.APP_NAME}} .
sources:
- "**/*.go"
generates:
- "{{.APP_NAME}}"
test:
cmds:
- go test ./...
docker:
deps: [build]
cmds:
- docker build -t {{.APP_NAME}} .
Desktop Automation¶
AutoHotkey (Windows)¶
# Instalar
winget install AutoHotkey.AutoHotkey
# Script ejemplo (script.ahk)
#Requires AutoHotkey v2.0
; Hotkey: Ctrl+Shift+T abre terminal
^+t:: {
Run "wt.exe"
}
; Text expansion
::btw::by the way
::sig::Best regards,`nJohn Doe
; Automación de ventana
#HotIf WinActive("ahk_exe notepad.exe")
^s:: {
MsgBox "Guardando en Notepad..."
Send "^s"
}
PyAutoGUI (Cross-platform)¶
pip install pyautogui pillow
# Ejemplo
import pyautogui
import time
# Mover mouse
pyautogui.moveTo(100, 100, duration=0.5)
# Click
pyautogui.click()
pyautogui.click(500, 300)
# Escribir
pyautogui.write('Hello World', interval=0.1)
# Hotkey
pyautogui.hotkey('ctrl', 's')
# Screenshot
screenshot = pyautogui.screenshot()
screenshot.save('screen.png')
# Localizar imagen en pantalla
location = pyautogui.locateOnScreen('button.png')
if location:
pyautogui.click(location)
Web Scraping¶
Playwright (Recomendado)¶
pip install playwright
playwright install
# Script
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com")
# Esperar elemento
page.wait_for_selector("h1")
# Extraer texto
title = page.locator("h1").text_content()
print(title)
# Screenshot
page.screenshot(path="screenshot.png")
browser.close()
Scrapy¶
pip install scrapy
# Crear proyecto
scrapy startproject myspider
# Spider ejemplo
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = ["https://quotes.toscrape.com"]
def parse(self, response):
for quote in response.css("div.quote"):
yield {
"text": quote.css("span.text::text").get(),
"author": quote.css("small.author::text").get(),
}
# Ejecutar
scrapy crawl quotes -o quotes.json
File Processing¶
jq (JSON)¶
# Instalar
brew install jq # macOS
winget install jqlang.jq # Windows
# Uso
cat data.json | jq '.items[].name'
cat data.json | jq 'map(select(.active == true))'
cat data.json | jq -r '.users[] | "\(.name): \(.email)"'
# Modificar
jq '.version = "2.0.0"' package.json > tmp && mv tmp package.json
yq (YAML)¶
# Instalar
brew install yq # macOS
winget install MikeFarah.yq # Windows
# Uso
yq '.spec.replicas' deployment.yaml
yq '.spec.replicas = 5' deployment.yaml
yq eval-all 'select(.kind == "Service")' *.yaml
awk/sed¶
# awk - procesar columnas
awk '{print $1, $3}' file.txt
awk -F',' '{sum += $2} END {print sum}' data.csv
awk '/pattern/ {print $0}' file.txt
# sed - buscar/reemplazar
sed 's/old/new/g' file.txt
sed -i 's/old/new/g' file.txt # In-place
sed -n '10,20p' file.txt # Líneas 10-20
Cron & Scheduling¶
Crontab (Linux/macOS)¶
# Editar crontab
crontab -e
# Formato: minuto hora día mes día_semana comando
# Ejemplos:
0 * * * * /path/to/script.sh # Cada hora
0 0 * * * /path/to/daily.sh # Diario a medianoche
0 0 * * 0 /path/to/weekly.sh # Domingos
*/5 * * * * /path/to/every5min.sh # Cada 5 minutos
# Ver crontab
crontab -l
Task Scheduler (Windows)¶
# Crear tarea
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File C:\scripts\backup.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "02:00"
Register-ScheduledTask -TaskName "DailyBackup" -Action $action -Trigger $trigger
# Listar tareas
Get-ScheduledTask | Where-Object {$_.TaskName -like "*Backup*"}
Comandos que Claude Code Ejecutará¶
# Shell
bash script.sh
./script.sh
source script.sh
# PowerShell
pwsh script.ps1
pwsh -Command "Get-Process"
# Python scripts
python script.py
python -m module
# Task runners
make build
just deploy
task docker
# File processing
jq '.key' file.json
yq '.spec' file.yaml
awk '{print $1}' file.txt
# Automation
python -c "import pyautogui; pyautogui.click(100, 100)"
# Scraping
scrapy crawl spider -o output.json
playwright codegen https://example.com
Verificación del Entorno¶
#!/bin/bash
echo "=== Verificación Entorno Scripting ==="
echo -e "\n--- Shells ---"
bash --version | head -1
zsh --version 2>/dev/null || echo "Zsh no instalado"
pwsh --version 2>/dev/null || echo "PowerShell no instalado"
echo -e "\n--- Task Runners ---"
make --version | head -1 2>/dev/null || echo "Make no instalado"
just --version 2>/dev/null || echo "Just no instalado"
echo -e "\n--- File Processing ---"
jq --version 2>/dev/null || echo "jq no instalado"
yq --version 2>/dev/null || echo "yq no instalado"
echo -e "\n--- Python ---"
python --version
pip show typer 2>/dev/null | grep Version || echo "typer no instalado"
echo -e "\n=== Verificación Completa ==="