Skip to main content
from praisonaiagents import Agent
from praisonaiagents import execute_command

agent = Agent(
    name="Shell Assistant",
    instructions="Run approved shell commands and report output.",
    tools=[execute_command],
)
agent.start("Show disk usage for the current project directory")
The user requests a system check; the agent runs bounded shell commands and returns stdout safely. Shell tools let AI agents execute commands, manage processes, and monitor system resources.
Prerequisites
  • Python 3.10 or higher
  • PraisonAI Agents package installed
  • Basic understanding of shell commands

Shell Tools

Use Shell Tools to execute shell commands with AI agents.
1

Install Dependencies

First, install the required package:
pip install praisonaiagents
2

Import Components

Import the necessary components:
from praisonaiagents import Agent, Task, AgentTeam
from praisonaiagents import execute_command, list_processes, kill_process, get_system_info
3

Create Agent

Create a shell command agent:
shell_agent = Agent(
    name="ShellCommander",
    role="Shell Command Specialist",
    goal="Execute shell commands efficiently and safely.",
    backstory="Expert in command-line operations and automation.",
    tools=[execute_command, list_processes, kill_process, get_system_info],
    reflection=False
)
4

Define Task

Define the shell task:
shell_task = Task(
    description="List and organize files in the current directory.",
    expected_output="Organized file structure with detailed listing.",
    agent=shell_agent,
    name="file_organization"
)
5

Run Agent

Initialize and run the agent:
agents = AgentTeam(
    agents=[shell_agent],
    tasks=[shell_task],
    process="sequential"
)
agents.start()

Understanding Shell Tools

What are Shell Tools?

Shell Tools provide command-line capabilities for AI agents:
  • Command execution
  • Process management
  • Output handling
  • Error handling
  • Environment management

Key Components

Shell Agent

Create specialized shell agents:
Agent(tools=[execute_command, list_processes, kill_process, get_system_info])

Shell Task

Define shell tasks:
Task(description="shell_operation")

Process Types

Sequential or parallel processing:
process="sequential"

Shell Options

Customize shell operations:
timeout=30, shell=True
from praisonaiagents import Agent, Task, AgentTeam
from praisonaiagents import execute_command, list_processes, kill_process, get_system_info

# Create shell agent
shell_agent = Agent(
    name="CommandExecutor",
    role="Shell Command Specialist",
    goal="Execute shell commands efficiently and safely.",
    backstory="Expert in command-line operations and scripting.",
    tools=[execute_command, list_processes, kill_process, get_system_info],
    reflection=False
)

# Define shell task
shell_task = Task(
    description="Clean up temporary files and organize downloads.",
    expected_output="Cleaned and organized file system.",
    agent=shell_agent,
    name="system_cleanup"
)

# Run agent
agents = AgentTeam(
    agents=[shell_agent],
    tasks=[shell_task],
    process="sequential"
)
agents.start()

Advanced Shell Management with Multiple Agents

# Create command agent
command_agent = Agent(
    name="Commander",
    role="Command Executor",
    goal="Execute shell commands systematically.",
    tools=[execute_command, list_processes, kill_process, get_system_info],
    reflection=False
)

# Create monitoring agent
monitor_agent = Agent(
    name="Monitor",
    role="Process Monitor",
    goal="Monitor and manage running processes.",
    backstory="Expert in system monitoring and process control.",
    reflection=False
)

# Define tasks
command_task = Task(
    description="Execute system maintenance commands.",
    agent=command_agent,
    name="system_maintenance"
)

monitor_task = Task(
    description="Monitor system resources and processes.",
    agent=monitor_agent,
    name="process_monitoring"
)

# Run agents
agents = AgentTeam(
    agents=[command_agent, monitor_agent],
    tasks=[command_task, monitor_task],
    process="sequential"
)
agents.start()

Available Functions

from praisonaiagents import execute_command
from praisonaiagents import list_processes
from praisonaiagents import kill_process
from praisonaiagents import get_system_info

Function Details

execute_command(command, cwd=None, timeout=30, env=None, max_output_size=10000, spill=True, spill_dir=None)

Safely executes shell commands:
  • Timeout protection
  • Output capture
  • Dangerous command blocking (PR #2062) — rm, mkfs, dd, shutdown, etc.
  • Environment and working directory control
  • Large output spill — over-budget output is saved to a retrievable artifact
ParameterTypeDefaultDescription
commandstrCommand to execute (split with shlex, no shell).
cwdOptional[str]NoneWorking directory.
timeoutint30Maximum execution time in seconds.
envOptional[Dict[str, str]]NoneExtra environment variables.
max_output_sizeint10000Byte/char budget for the inline preview.
spillboolTrueSave over-budget output to an artifact instead of dropping the middle.
spill_dirOptional[str]NoneDirectory for artifacts (overrides PRAISONAI_TOOL_OUTPUT_DIR).
Commands always run with shell=False for security. The command string is split with shlex, so pipes and redirects are not interpreted.

Dangerous Command Protection

By default, commands whose base name is in DANGEROUS_COMMANDS are blocked:
# Returns: success=False, exit_code=-1
# error: "Command 'rm' is in DANGEROUS_COMMANDS; pass allow_dangerous=True to override."
The check uses shlex.split + os.path.basename, so rm and /usr/bin/rm are both classified as rm. Unparseable commands fall through to later validation.
from praisonaiagents import Agent, execute_command
from functools import partial

agent = Agent(
    name="SafeShellAgent",
    instructions="Run shell commands safely; refuse destructive operations.",
    tools=[execute_command],
)

agent.start("List files in current directory")  # works
agent.start("Delete /tmp/test")                 # blocked — rm in pipeline

# Explicit override (use sparingly; combine with approval)
risky_exec = partial(execute_command, allow_dangerous=True)
# Basic command execution
result = execute_command("ls -la")

# Advanced execution (shell=False — deprecated param omitted)
result = execute_command(
    "python script.py",
    cwd="/path/to/scripts",
    timeout=60,
    env={"PYTHONPATH": "/custom/path"},
)

# Returns: Dict[str, Union[str, int, bool]]
# Example output:
# {
#     'stdout': 'command output...',
#     'stderr': 'error output if any',
#     'exit_code': 0,
#     'success': True,
#     'execution_time': 0.123,
#     # Only present on overflow with spill=True:
#     'stdout_artifact': '/tmp/praisonai_tool_output/stdout_xxxxx.txt',
#     'stderr_artifact': '/tmp/praisonai_tool_output/stderr_xxxxx.txt'
# }

Large Output Handling

When output exceeds max_output_size, the full buffer is saved to a disk artifact and the preview keeps a bounded head/tail plus a pointer to that file.
<head bytes...>
...[52,318 chars / 894 lines truncated in preview]...
Full output saved to: /tmp/praisonai_tool_output/stdout_xxxxx.txt
Use read_file/grep on that path to inspect the omitted region (do NOT re-run the command through head/tail).
<tail bytes...>
The agent reads the omitted region straight from the artifact path.
from praisonaiagents.tools import read_file

read_file("/tmp/praisonai_tool_output/stdout_xxxxx.txt")
Set spill=False to keep the legacy middle-truncated preview with no persistence. See Tool Output Spill for the full mechanism.

list_processes()

Lists running system processes:
  • Process details
  • Resource usage
  • User information
  • Performance metrics
# Get list of running processes
processes = list_processes()

# Sort by CPU usage
cpu_intensive = sorted(
    processes,
    key=lambda x: x['cpu_percent'],
    reverse=True
)[:5]

# Returns: List[Dict[str, Union[int, str, float]]]
# Example output:
# [
#     {
#         'pid': 1234,
#         'name': 'python',
#         'username': 'user',
#         'memory_percent': 2.5,
#         'cpu_percent': 15.3
#     },
#     ...
# ]

kill_process(pid: int, force: bool = False)

Terminates system processes:
  • Graceful termination
  • Force kill option
  • Error handling
  • Access control
# Graceful termination
result = kill_process(1234)

# Force kill
result = kill_process(
    pid=1234,
    force=True  # Use SIGKILL
)

# Returns: Dict[str, Union[bool, str]]
# Example output:
# {
#     'success': True,
#     'message': 'Process 1234 killed successfully'
# }
# or
# {
#     'success': False,
#     'message': 'Access denied to kill process 1234'
# }

get_system_info()

Retrieves system information:
  • CPU statistics
  • Memory usage
  • Disk space
  • Platform details
  • Boot time
# Get system information
info = get_system_info()

# Access specific metrics
print(f"CPU Usage: {info['cpu']['percent']}%")
print(f"Memory Free: {info['memory']['free']} bytes")

# Returns: Dict[str, Union[float, int, str, Dict]]
# Example output:
# {
#     'cpu': {
#         'percent': 45.2,
#         'cores': 8,
#         'physical_cores': 4
#     },
#     'memory': {
#         'total': 16000000000,
#         'available': 8000000000,
#         'percent': 50.0,
#         'used': 8000000000,
#         'free': 4000000000
#     },
#     'disk': {
#         'total': 500000000000,
#         'used': 250000000000,
#         'free': 250000000000,
#         'percent': 50.0
#     },
#     'boot_time': 1641544800,
#     'platform': 'Darwin'
# }

Example Agent Configuration

from praisonaiagents import Agent
from praisonaiagents import (
    execute_command, list_processes,
    kill_process, get_system_info
)

agent = Agent(
    name="SystemManager",
    description="An agent that manages system processes and executes commands",
    tools=[
        execute_command, list_processes,
        kill_process, get_system_info
    ]
)

Dependencies

The shell tools require the following package:
  • psutil: For system and process information
This will be automatically installed when needed.

Error Handling

All functions include comprehensive error handling:
  • Command execution errors
  • Process access errors
  • Permission errors
  • Timeout errors
  • Resource errors
Errors are handled consistently:
  • Success cases return expected data type
  • Error cases return error details in result
  • All errors are logged for debugging

Common Use Cases

  1. System Monitoring:
# Monitor system resources
info = get_system_info()
if info['cpu']['percent'] > 90:
    print("High CPU usage detected!")
if info['memory']['percent'] > 80:
    print("Low memory warning!")

# List resource-intensive processes
processes = sorted(
    list_processes(),
    key=lambda x: x['memory_percent'],
    reverse=True
)[:5]
print("Top memory users:", processes)
  1. Process Management:
# Find and kill zombie processes
for process in list_processes():
    if process['name'] == 'zombie_process':
        result = kill_process(
            process['pid'],
            force=True
        )
        print(f"Kill result: {result['message']}")
  1. Command Execution:
# Run a series of maintenance commands
commands = [
    "apt-get update",
    "apt-get upgrade -y",
    "apt-get autoremove -y"
]
for cmd in commands:
    result = execute_command(
        cmd,
        timeout=300,
        shell=True
    )
    if result['success']:
        print(f"Command succeeded: {cmd}")
    else:
        print(f"Command failed: {result['stderr']}")

Best Practices

Configure agents with clear shell focus:
Agent(
    name="ShellManager",
    role="Command Line Specialist",
    goal="Execute shell commands safely and efficiently",
    tools=[execute_command, list_processes, kill_process, get_system_info]
)
Define specific shell operations:
Task(
    description="Clean up system temp files and optimize storage",
    expected_output="Optimized system storage"
)

Common Patterns

Shell Command Pipeline

# Command agent
commander = Agent(
    name="Commander",
    role="Shell Commander",
    tools=[execute_command]
)

# Monitor agent
monitor = Agent(
    name="Monitor",
    role="Process Monitor"
)

# Define tasks
command_task = Task(
    description="Execute maintenance commands",
    agent=commander
)

monitor_task = Task(
    description="Monitor command execution",
    agent=monitor
)

# Run workflow
agents = AgentTeam(
    agents=[commander, monitor],
    tasks=[command_task, monitor_task]
)

## Related

<CardGroup cols={2}>
  <Card title="Custom Tools" icon="wrench" href="/docs/tools/custom">
    Build your own agent tools
  </Card>
  <Card title="Tools Overview" icon="toolbox" href="/docs/tools/tools">
    Browse PraisonAI tool documentation
  </Card>
  <Card title="Tool Output Spill" icon="file-arrow-down" href="/docs/features/tool-output-spill">
    Save large command output to a retrievable artifact
  </Card>
</CardGroup>