Work with persistent shell sessions using startShell, writeToShell, and shell events
Interactive shell sessions allow you to maintain a persistent connection with a command-line interface on the remote server. This is useful for commands that require continuous interaction or when you need to maintain state across multiple commands.
Send commands to the active shell session using writeToShell():
Copy
Ask AI
// Execute a commandawait client.writeToShell('ls -la\n');// Change directory (state persists)await client.writeToShell('cd /var/www\n');// Run command in new directoryawait client.writeToShell('pwd\n');
Don’t forget to include the newline character (\n) at the end of your commands to execute them. Without it, the command will be typed but not executed.
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.
Copy
Ask AI
// This will auto-start a VANILLA shellawait client.writeToShell('ls\n');// Equivalent to:// await client.startShell(PtyType.VANILLA);// await client.writeToShell('ls\n');
One of the key advantages of shell sessions over execute() is state persistence:
Example: Working Directory
Copy
Ask AI
// With execute() - each command runs in a fresh contextawait client.execute('cd /var/www'); // Changes directoryawait client.execute('pwd'); // Still in home directory!// With shell - state persistsawait client.writeToShell('cd /var/www\n');await client.writeToShell('pwd\n'); // Shows /var/www
Example: Environment Variables
Copy
Ask AI
// Set an environment variableawait client.writeToShell('export MY_VAR=hello\n');// Use it in subsequent commandsawait client.writeToShell('echo $MY_VAR\n'); // Outputs: hello