Léim go dtí an príomhábhar
Gaeilge— Roghnaigh teanga
Roghchlár

Shell: Cur isteach orduithe

Ceacht 18 as 20 Forbróir
Ar an leathanach seo
  1. Shell: Cur isteach orduithe
  2. Coincheap agus Ailtireacht
  3. Cás Úsáide: Diagnóis Córais
  4. Feidhmiú a Dhaingniú
  5. Cur i bhFeidhm mar Fheidhm Shaincheaptha
  6. Sruthanna Oibre Uathoibrithe
  7. Príomhphointí

Shell: Cur isteach orduithe

Seo an uirlis is cumhachtaí sa chúrsa seo, agus an t-aon cheann ar féidir le botún a chumhacht a chasadh in aghaidh tú. Léann uirlisí eile, ríomhann siad nó cuardaíonn siad; gníomhaíonn an ceann seo ar mheaisín. Fanann diagnóis chórais mífhoirmithe ina diagnóis amháin; scriosann ordú glantáin mífhoirmithe comhaid.

Clúdaíonn an ceacht seo úsáid agus cosaintí le chéile toisc nach féidir iad a scaradh. An riail órga: níor chóir don mhúnla ordú a chur i gcrích riamh nár údarásaigh tú go sainráite roimh ré.

Coincheap agus Ailtireacht

Tá an difríocht ón Ateangaire Cóid ríthábhachtach, agus tagann sí anuas ar fhocal amháin: leithlisiú. Rithann an tAteangaire Cóid i ngaineamhlach in-idirdhealaithe, leithlisithe ón líonra, áit arb é an measctha is measa ná ríomh mícheart. Rithann Shell i dtimpeallacht a chumraíonn tú féin – d’fhéadfadh sé a bheith ar do mheaisín áitiúil, nó ar fhreastalaí – áit arb é an measctha is measa ná oibríocht dochúlaithe.

Is é an tsaoirse seo an pointe: gan í, tá imlonnú agus cothabháil uathoibrithe dodhéanta. Éilíonn sé ort, áfach, an raon feidhme feidhmiúcháin a roghnú go feasach. Is beagnach i gcónaí an rogha cheart coimeádán tiomnaithe le pribhléidí teoranta seachas rochtain dhíreach ar an óstach.

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"}]
)

Cás Úsáide: Diagnóis Córais

# 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

Feidhmiú a Dhaingniú

Oibríonn trí chosaint le chéile, agus níl aon cheann acu leordhóthanach leis féin. Is é an liosta ceadaithe an bonn: liostaíonn tú cad atá ceadaithe seachas cad atá toirmiscthe, toisc go mbíonn leagan éagsúil in easnamh i gcónaí ar liosta blocála – agus ní theastaíonn ach ceann amháin. Cuireann teorainn ama cosc ar ordú greamaithe an córas a chur ar ceal. Teorannaíonn comhadlann oibre shrianta an damáiste má dhíríonn ordú dlisteanach ar an áit mhícheart.

Is é an ceathrú cosaint, nach bhfuil teicniúil ach fiú na trí cinn eile le chéile: éiligh deimhniú daonna ar aon oibríocht scriosach nó dochúlaithe. Déanann múnla botúin leis an muinín chéanna agus atá aige nuair atá sé ceart.

# 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"}

Cur i bhFeidhm mar Fheidhm Shaincheaptha

Tá buntáiste ag baint leis an méid seo a chur i bhfeidhm tú féin trí ghlao feidhme nach ba chóir duit a mheas mar rogha thánaisteach: tá an bailíochtú i do chód féin. Is tú a chinneann an liosta ceadaithe, an logáil, agus na céimeanna deimhnithe, agus is féidir leat gach rud a iniúchadh. Maidir le huirlis a bhfuil an leibhéal riosca seo aici, is fearr smacht a choinneáil ar an bpointe seiceála, fiú nuair a bheidh leagan dúchasach ar fáil.

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)

Sruthanna Oibre Uathoibrithe

Imlonnú Uathoibrithe

Is é an imlonnú an cás úsáide is luachmhaire, ar choinníoll go dtuigeann tú cad atá tú a tharmligean. Ní chruthaíonn an múnla an nós imeachta: slabhraíonn sé céimeanna a shainigh tú, fíoraíonn sé aschuir idirmheánacha, agus stopann sé ar aon ainrialtacht. Is oibreoir aireach é, ní cinnteoir.

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")

Monatóireacht agus Foláirimh

Casann monatóireacht loighic an chuid eile den cheacht seo bun os cionn: tá na horduithe anseo inléite amháin, mar sin tá siad díobhálach, agus tá an luach sa léirmhíniú. Aithníonn múnla a léann spás diosca, ualach, agus logaí earráide comhcheangail nach mbraitheann tairseach leithlisithe – rud a fhágann gurb é seo an pointe iontrála is sábháilte chun tosú leis an uirlis seo.

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
)

Príomhphointí

  • Nascann an uirlis Shell an múnla le d’bonneagar
  • Cuir liostaí ceadaithe agus liostaí blocála i bhfeidhm d’orduithe
  • Úsáid teorainneacha ama agus comhadlanna oibre srianta
  • Ligeann glao feidhme duit Shell a chur i bhfeidhm mar uirlis saincheaptha
  • Comhcheangail Shell le huirlisí eile le haghaidh sruthanna oibre DevOps iomlána