akhildevelops
akhildevelops

Reputation: 591

How can I return from `channel.write` method that hangs indefinitely

I'm unable to getout after writing to stdin of the server.

Here's the example code that uses ssh2 crate:

// creates channel struct from session 
// channel: https://docs.rs/ssh2/latest/ssh2/struct.Channel.html
// session: https://docs.rs/ssh2/latest/ssh2/struct.Session.html
let mut channel = self.0.channel_session()?;

// utils::USER_ADD="useradd"
// username="some_user"
let user_add = format!("sudo -S {} {}\n", utils::USER_ADD, username);
channel.write(user_add.as_bytes())?;
channel.flush()?;
        
let mut stderr = channel.stderr();
let mut response = String::new();
        
channel.wait_close()?;
channel.exit_status()?;

Upvotes: 0

Views: 116

Answers (2)

Jacob
Jacob

Reputation: 66

I think you need to add channel.shell().unwrap(); before calling write.

you can check the write window capacity with println!("{}", channel.write_window().remaining);

Also, you might look at using channel.exec(<command>) instead of using write (https://docs.rs/ssh2/latest/ssh2/index.html#run-a-command)

Upvotes: 0

Jmb
Jmb

Reputation: 23414

You're waiting for the server to close the connection, but you never tell it to. This is equivalent to login in to the server, typing the sudo command, and then waiting to be disconnected even though you never type exit or logout. You need to call channel.close() before channel.wait_close().

Upvotes: 1

Related Questions