Starting a Shell Session
Use thestartShell() method to initiate an interactive shell session:
PTY (Pseudo-Terminal) Types
The library supports multiple PTY types for different terminal emulation needs:- VANILLA
- VT100
- VT102
- VT220
- ANSI
- XTERM
Choose the PTY type based on your needs:
- Use VANILLA for simple scripts and basic command execution
- Use XTERM for full-featured interactive sessions
- Use VT100/VT102 for compatibility with older systems
Reading from the Shell
Set up an event listener to receive output from the shell:1
Register the Shell event handler
2
Start the shell session
3
Process incoming data
The
Shell event will fire whenever the remote shell sends output:Writing to the Shell
Send commands to the active shell session usingwriteToShell():
Complete Example
Here’s a full example of an interactive shell session:Automatic Shell Initialization
The
writeToShell() method automatically starts a shell session (using PtyType.VANILLA) if one isn’t already active. However, it’s recommended to explicitly call startShell() with your desired PTY type for better control.Closing the Shell
When you’re done with the shell session, close it to free up resources:State Persistence
One of the key advantages of shell sessions overexecute() is state persistence:
Example: Working Directory
Example: Working Directory
Example: Environment Variables
Example: Environment Variables
Example: Interactive Programs
Example: Interactive Programs
Best Practices
- Always register event handlers before starting the shell to avoid missing initial output
- Add delays between commands if you need to wait for output (or implement a proper response parser)
- Use appropriate PTY types for your use case
- Close the shell when done to free resources
- Handle errors appropriately as shell operations can fail
Use Cases
- Running interactive programs (database CLIs, REPLs, etc.)
- Executing a series of related commands that depend on shared state
- Monitoring real-time output from long-running processes
- Working with shell scripts that require user input
- Maintaining a persistent working directory across commands
Next Steps
- Learn about executing simple commands for one-off operations
- Explore SFTP operations for file transfers
- Check platform-specific considerations for iOS and Android differences