Skip to Content

Execute Commands

TL;DR

Execute one-shot commands on remote machines via client.terminal.execute(). Supports timeouts, custom working directories, environment variables, and shell selection. Returns a tuple of (output, exit_code). Chain multiple commands with && for sequential execution, or loop for independent commands. Always check exit codes for error handling.

The simplest way to run commands on a remote machine.

How do I execute a basic command?

from cmdop import AsyncCMDOPClient async with AsyncCMDOPClient.remote(api_key="cmd_xxx") as client: # Connect to the target remote machine by hostname await client.terminal.set_machine("my-server") # Execute a single command and capture its output and exit code output, exit_code = await client.terminal.execute("ls -la") print(output) # Command output (stdout + stderr combined) print(exit_code) # 0 = success, non-zero = failure

How do I set a timeout for commands?

# Run a long-running build with a 10-minute timeout limit output, code = await client.terminal.execute( "./build.sh", timeout=600 # Timeout in seconds (600s = 10 minutes) ) # Run a quick command with a short 5-second timeout output, code = await client.terminal.execute( "echo hello", timeout=5 )

How do I set the working directory?

# Execute a command in a specific directory using the cwd parameter output, code = await client.terminal.execute( "npm install", cwd="/app/frontend" # Sets the working directory before execution ) # Alternative: chain cd with the command using shell operators output, code = await client.terminal.execute( "cd /app && npm install" )

How do I pass environment variables?

# Pass custom environment variables to the command via the env dict output, code = await client.terminal.execute( "./deploy.sh", env={ "NODE_ENV": "production", # Set Node.js environment mode "API_KEY": "secret" # Pass secrets as env vars (not CLI args) } )

Error Handling

from cmdop.exceptions import TimeoutError, SessionNotFoundError try: output, code = await client.terminal.execute("command") # Check the exit code to determine if the command succeeded if code != 0: print(f"Command failed with code {code}") print(f"Error output: {output}") except TimeoutError: # Raised when the command exceeds the specified timeout duration print("Command timed out") except SessionNotFoundError: # Raised when the target machine is not connected or unreachable print("Machine not connected")

What do exit codes mean?

CodeMeaning
0Success
1General error
2Misuse of command
126Permission denied
127Command not found
128+NKilled by signal N
130Ctrl+C (SIGINT)
137Killed (SIGKILL)

What are the best practices for command execution?

How should I handle paths?

# Good: use absolute paths to avoid PATH resolution issues output, code = await client.terminal.execute("/usr/bin/python3 script.py") # Avoid: relies on PATH which may differ on the remote machine output, code = await client.terminal.execute("python3 script.py")

How should I quote arguments?

# Good: properly quoted argument containing spaces output, code = await client.terminal.execute('grep "hello world" file.txt') # Avoid: unquoted arguments are split by the shell incorrectly output, code = await client.terminal.execute("grep hello world file.txt")

Why should I always check the exit code?

output, code = await client.terminal.execute("./script.sh") # Always verify the exit code - non-zero means the command failed if code != 0: raise Exception(f"Script failed: {output}")

How do I run multiple commands?

How do I run commands sequentially?

# Chain commands with && so each runs only if the previous succeeded output, code = await client.terminal.execute( "cd /app && npm install && npm run build" )

How do I run commands independently?

# Define a list of independent commands to execute one by one commands = ["uptime", "df -h", "free -m"] # Loop through and execute each command separately for cmd in commands: output, code = await client.terminal.execute(cmd) print(f"{cmd}: {output}")

How do I select a specific shell?

# Override the default shell by specifying the shell parameter output, code = await client.terminal.execute( "echo $SHELL", shell="/bin/zsh" # Use zsh instead of the default /bin/sh )

How does the SDK compare to the CLI?

SDKCLI
await client.terminal.execute("cmd")cmdop exec host "cmd"
Returns (output, code)Prints output, exit code
Async PythonSynchronous

Next

Last updated on