Sample code for 30+ languages & platforms
Rust

Start a Remote Shell with QuickShell

See more SSH Examples

Demonstrates the Chilkat Ssh.QuickShell method, which starts a remote shell using the simplified sequence OpenSessionChannel → SendReqPty → SendReqShell. It takes no arguments and returns the shell channel number, or -1 on failure. The default PTY size is 80 columns by 24 rows.

Background: Note that QuickShell does allocate a PTY, so unlike a bare SendReqShell the remote shell runs interactively: it prints a command prompt, echoes the commands you send, and runs interactive login scripts. That is convenient for terminal-style work but means the output contains prompts and echoed input that scripted parsing must tolerate. The method returns as soon as the shell request is accepted — it does not consume the initial login text or prompt, so read and discard that before relying on command output.

Chilkat Rust Downloads

Rust

// Demonstrates the Ssh.QuickShell method, which starts a remote shell using the simplified
// sequence OpenSessionChannel, SendReqPty, and SendReqShell.  It takes no arguments and returns
// the shell channel number, or -1 on failure.  The default PTY size is 80 columns by 24 rows.

let ssh = chilkat::Ssh::new();

let ssh_port = 22;
if ssh.connect("ssh.example.com", ssh_port).is_err() {
    println!("{}", ssh.last_error_text());
    return;
}

// Normally you would not hard-code the password in source.  You should instead obtain it
// from an interactive prompt, environment variable, or a secrets vault.
let password = "mySshPassword".to_string();

if ssh.authenticate_pw("mySshLogin", &password).is_err() {
    println!("{}", ssh.last_error_text());
    return;
}

// Start the shell.  Note that QuickShell allocates a PTY, so the remote shell runs
// interactively: it prints a command prompt and echoes the commands that are sent to it.
let channel_num = ssh.quick_shell();
if channel_num < 0 {
    println!("{}", ssh.last_error_text());
    return;
}

// QuickShell returns as soon as the shell request is accepted -- it does not wait for or
// consume the initial login text or prompt.
if ssh.channel_send_string(channel_num, "uname -a; echo DONE_MARKER\n", "utf-8").is_err() {
    println!("{}", ssh.last_error_text());
    return;
}

// IMPORTANT: Set a read timeout before receiving until a match.  ReadTimeoutMs defaults to 0,
// which means no limit -- without it, this call waits forever if the received data never
// contains a match.
ssh.set_read_timeout_ms(15000);

let case_sensitive = false;
if ssh.channel_receive_until_match(channel_num, "DONE_MARKER", "utf-8", case_sensitive).is_err() {
    println!("{}", ssh.last_error_text());
    return;
}

let Ok(output) = ssh.get_received_text(channel_num, "utf-8") else {
    println!("{}", ssh.last_error_text());
    return;
};

println!("{}", output);

ssh.disconnect();