Shell: Komentojen suorittaminen
Tällä sivulla
Shell: Komentojen suorittaminen
Tämä on kurssin tehokkain työkalu, ja ainoa, jossa virhe voi kääntää sen voiman sinua vastaan. Muut työkalut lukevat, laskevat tai etsivät; tämä toimii koneella. Huonosti muotoiltu järjestelmädiagnostiikka on vain diagnostiikkaa; huonosti muotoiltu siivouskomento poistaa tiedostoja.
Käsittelemme tässä oppitunnissa käytön ja turvatoimet yhdessä, koska niitä ei voi erottaa toisistaan. Kultainen sääntö: malli ei saa koskaan suorittaa komentoa, jota et ole nimenomaisesti hyväksynyt etukäteen.
Käsite ja arkkitehtuuri
Ero Code Interpreteriin on ratkaiseva, ja se tiivistyy yhteen sanaan: eristäminen. Code Interpreter suoritetaan kertakäyttöisessä, verkosta eristetyssä hiekkalaatikossa, jossa pahin mahdollinen skenaario on väärä laskutoimitus. Shell toimii ympäristössä, jonka sinä määrität – se voi olla paikallinen koneesi tai palvelin – jossa pahin skenaario on peruuttamaton operaatio.
Tämä vapaus on koko pointti: ilman sitä automatisoitu käyttöönotto ja ylläpito ovat mahdottomia. Se kuitenkin vaatii, että valitset suoritusalueen tietoisesti. Erillinen säiliö rajoitetuilla oikeuksilla on lähes aina oikea valinta verrattuna suoraan pääsyyn isäntäkoneelle.
from openai import OpenAI
client = OpenAI()
# The Shell tool is used via the Agents SDK
# because it requires a controlled execution environment
from agents import Agent, Runner
agent = Agent(
name="devops-assistant",
model="gpt-5.6-terra",
instructions=(
"You are a DevOps assistant. You execute system commands "
"to diagnose and resolve infrastructure issues. "
"Explain each command before executing it."
),
tools=[{"type": "shell"}]
)
Käyttötapaus: Järjestelmädiagnostiikka
# The agent can execute diagnostic commands
agent = Agent(
name="diagnostic",
model="gpt-5.6-terra",
instructions=(
"Diagnose the system state by executing appropriate commands. "
"Start with basic checks (disk, memory, CPU) "
"then dig deeper based on symptoms."
),
tools=[{"type": "shell"}]
)
# The agent will execute commands like:
# df -h -> disk space
# free -m -> memory
# top -bn1 -> CPU load
# systemctl status nginx -> service status
Suorituksen turvaaminen
Kolme turvamekanismia toimivat yhdessä, eikä yksikään niistä riitä yksinään. Sallittujen luettelo (allowlist) on perusta: luettelet, mitä on sallittu, sen sijaan että luettelisit, mitä on kielletty, koska kiellettyjen luettelosta (blocklist) puuttuu aina variaatioita – ja yksi riittää. Aikakatkaisu estää jumittuneen komennon lukitsemasta järjestelmää. Rajoitettu työhakemisto rajoittaa vahinkoa, jos laillinen komento osoittaa väärään sijaintiin.
Neljäs turvamekanismi on ei-tekninen, mutta sen arvo vastaa muita kolmea yhteensä: vaadi ihmisen vahvistus kaikille tuhoisille tai peruuttamattomille operaatioille. Malli tekee virheitä yhtä itsevarmasti kuin se on oikeassa.
# Pattern: wrapper function with validation
import subprocess
import shlex
ALLOWED_COMMANDS = {
"diagnostic": ["df", "free", "top", "uptime", "ps", "netstat", "curl", "ping"],
"deployment": ["git", "docker", "npm", "pip"],
"files": ["ls", "cat", "head", "tail", "wc", "grep", "find"],
}
FORBIDDEN_COMMANDS = ["rm", "dd", "mkfs", "shutdown", "reboot", "kill", "passwd"]
def execute_secure_command(command: str, category: str = "diagnostic") -> dict:
"""Executes a command with security validation."""
# Parse the command
parts = shlex.split(command)
executable = parts[0]
# Check prohibitions
if executable in FORBIDDEN_COMMANDS:
return {
"error": f"Forbidden command: {executable}",
"reason": "This command is on the blocklist"
}
# Check permissions
allowed = ALLOWED_COMMANDS.get(category, [])
if executable not in allowed:
return {
"error": f"Command not allowed in category '{category}'",
"allowed": allowed
}
# Execute with timeout
try:
result = subprocess.run(
parts,
capture_output=True,
text=True,
timeout=30,
cwd="/tmp" # Restricted working directory
)
return {
"stdout": result.stdout,
"stderr": result.stderr,
"return_code": result.returncode
}
except subprocess.TimeoutExpired:
return {"error": "Timeout: command exceeded 30 seconds"}
Toteutus mukautettuna funktiona
Tämän toteuttaminen itse funktion kutsumisen (function calling) kautta tarjoaa etua, jota ei kannata pitää vain vararatkaisuna: validointi elää sinun koodissasi. Sinä päätät sallittujen luettelon, lokituksen ja vahvistusvaiheet, ja voit tarkistaa kaiken jälkikäteen. Työkalulle, johon liittyy tämäntasoinen riski, tarkastuspisteen hallinnan pitäminen on suositeltavaa, vaikka natiiviversio tulisi saataville.
tools = [
{
"type": "function",
"name": "execute_command",
"description": (
"Execute a shell command on the server. "
"Allowed commands: system diagnostics (df, free, top, uptime, ps), "
"file reading (ls, cat, head, tail, grep), "
"network (curl, ping, netstat). "
"Destructive commands are forbidden."
),
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The shell command to execute"
},
"directory": {
"type": "string",
"description": "Working directory (default: /tmp)"
}
},
"required": ["command"],
"additionalProperties": False
},
"strict": True
}
]
import json
def handle_calls(response):
results = []
for item in response.output:
if item.type == "function_call" and item.name == "execute_command":
args = json.loads(item.arguments)
result = execute_secure_command(
args["command"],
category="diagnostic"
)
results.append({
"type": "function_call_output",
"call_id": item.call_id,
"output": json.dumps(result)
})
return results
# Full loop
response = client.responses.create(
model="gpt-5.6-terra",
input="Check disk space and available memory",
tools=tools
)
results = handle_calls(response)
final_response = client.responses.create(
model="gpt-5.6-terra",
input=response.output + results,
tools=tools
)
print(final_response.output_text)
Automatisointityönkulut
Automatisoitu käyttöönotto
Käyttöönotto on arvokkain käyttötapaus, edellyttäen että ymmärrät, mitä delegoit. Malli ei keksi menettelyä itse: se ketjuttaa määrittämäsi vaiheet, tarkistaa välivaiheiden tulosteet ja pysähtyy poikkeaman sattuessa. Se on tarkkaavainen operaattori, ei päätöksentekijä.
tools_deploy = [
{
"type": "function",
"name": "execute_deploy_step",
"description": (
"Execute a deployment step. "
"Possible steps: git_pull, tests, build, deploy, rollback. "
"Each step is validated before proceeding to the next."
),
"parameters": {
"type": "object",
"properties": {
"step": {
"type": "string",
"enum": ["git_pull", "tests", "build", "deploy", "rollback"]
},
"parameters": {
"type": "object",
"properties": {
"branch": {"type": "string"},
"environment": {"type": "string", "enum": ["staging", "production"]}
}
}
},
"required": ["step"],
"additionalProperties": False
},
"strict": True
}
]
def execute_step(step: str, params: dict) -> dict:
scripts = {
"git_pull": "cd /app && git pull origin {branch}",
"tests": "cd /app && npm test",
"build": "cd /app && npm run build",
"deploy": "cd /app && ./deploy.sh {environment}",
"rollback": "cd /app && ./rollback.sh {environment}"
}
command = scripts[step].format(**params)
return execute_secure_command(command, "deployment")
Valvonta ja hälytykset
Valvonta kääntää tämän oppitunnin muun logiikan päälaelleen: tässä komennot ovat vain luku -tilassa, joten ne ovat harmittomia, ja arvo piilee tulkinnassa. Malli, joka lukee levytilaa, kuormitusta ja virhelokeja, havaitsee korrelaatioita, jotka eristetty kynnysarvo missaa – mikä tekee tästä turvallisimman lähtökohdan tämän työkalun käytön aloittamiseen.
def check_system_health() -> dict:
"""Checks system health and returns a report."""
checks = {}
# Disk space
r = execute_secure_command("df -h /", "diagnostic")
checks["disk"] = r
# Memory
r = execute_secure_command("free -m", "diagnostic")
checks["memory"] = r
# Services
for service in ["nginx", "postgresql", "redis"]:
r = execute_secure_command(
f"systemctl is-active {service}",
"diagnostic"
)
checks[f"service_{service}"] = r
return checks
# The AI analyzes the results and suggests actions
response = client.responses.create(
model="gpt-5.6-terra",
input=f"Analyze this system health report and identify issues:\n"
f"{json.dumps(check_system_health(), indent=2)}",
tools=tools
)
Keskeiset asiat
- Shell-työkalu yhdistää mallin infrastruktuuriisi
- Toteuta sallittujen ja kiellettyjen komentojen luettelot
- Käytä aikakatkaisuja ja rajoitettuja työhakemistoja
- Funktion kutsuminen mahdollistaa Shellin toteuttamisen mukautettuna työkaluna
- Yhdistä Shell muihin työkaluihin kokonaisvaltaisia DevOps-työnkulkuja varten