Rust
Rust
Check Whether an SSH Exit Status Was Received
See more SSH Examples
Demonstrates the Chilkat Ssh.ChannelReceivedExitStatus method, which reports whether the server supplied an exit-status value for a channel. The only argument is the channel number. When it returns true, call GetChannelExitStatus to read the value.
Background: Always test this before reading the exit status, because the server is not required to send one for every channel type or command — treating a missing status as "0" would silently turn a failure into a success. Exit status is independent of EOF and CLOSE: it can arrive after EOF and either before or together with CLOSE.
Chilkat Rust Downloads
// Demonstrates the Ssh.ChannelReceivedExitStatus method, which reports whether the server
// supplied an exit-status value for a channel. The only argument is the channel number. When
// it returns true, call GetChannelExitStatus to read the value.
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;
}
let channel_num = ssh.open_session_channel();
if channel_num < 0 {
println!("{}", ssh.last_error_text());
return;
}
if ssh.send_req_exec(channel_num, "test -f /etc/hosts").is_err() {
println!("{}", ssh.last_error_text());
return;
}
// IMPORTANT: Set a read timeout. ReadTimeoutMs defaults to 0, which means no limit -- without
// it, this call waits forever if the server never sends channel close.
ssh.set_read_timeout_ms(15000);
if ssh.channel_receive_to_close(channel_num).is_err() {
println!("{}", ssh.last_error_text());
return;
}
// The server is not required to send an exit status for every channel type or command.
if ssh.channel_received_exit_status(channel_num) {
let exit_status = ssh.get_channel_exit_status(channel_num);
println!("Exit status: {}", exit_status);
} else {
println!("The server did not provide an exit status.");
}
ssh.disconnect();