execute() method allows you to run individual SSH commands on a remote server and receive the output. This is ideal for one-off commands that don’t require an interactive session.
Basic Usage
Once you have an established SSH connection, you can execute commands using theexecute() method:
Common Examples
- File System Operations
- System Information
- Service Management
- Network Operations
Using Callbacks
You can also use the optional callback parameter instead of promises:Chaining Commands
1
Chain with shell operators
You can chain multiple commands using shell operators like
&&, ||, or ;:2
Use pipes
Pipe output between commands:
Error Handling
Best Practices
- Keep it simple: The
execute()method is designed for single commands. For complex interactions, use interactive shell instead. - Handle timeouts: Long-running commands may timeout. Consider using shell sessions for commands that take significant time.
- Parse output: Command output is returned as a string. Parse it appropriately for your use case.
- Security: Avoid passing user input directly into commands without sanitization to prevent command injection.
Processing Output
Here’s an example of parsing command output:Limitations
- Commands are executed in a non-interactive environment
- No persistent state between
execute()calls (each command runs in a fresh context) - Standard output and error are combined in the response
- For interactive commands or maintaining session state, use startShell() instead
Next Steps
- Learn about interactive shell sessions for more complex interactions
- Explore SFTP operations for file management