Skip to content

Instantly share code, notes, and snippets.

@fredlahde
Created February 1, 2025 22:59
Show Gist options
  • Save fredlahde/83379b087d5f443cb1bf7c9ade1bcc12 to your computer and use it in GitHub Desktop.
Save fredlahde/83379b087d5f443cb1bf7c9ade1bcc12 to your computer and use it in GitHub Desktop.
Basic rust ssh2 ssh -L port forward
#[cfg(test)]
mod test {
#[test]
fn foo() {
// start a local tcp echo server:
// ncat -l 127.0.0.1 2000 -k -c 'xargs -n1 echo'
use ssh2::Session;
use std::io::prelude::*;
use std::net::TcpStream;
let tcp = TcpStream::connect("127.0.0.1:22").unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp);
sess.handshake().unwrap();
sess.userauth_agent("fred").unwrap();
let mut chan = sess.channel_direct_tcpip("127.0.01", 2000, None).unwrap();
println!("conn");
let msg = b"hallo\n";
let w = chan.write(msg).unwrap();
assert_eq!(msg.len(), w);
chan.flush().unwrap();
println!("{w} write");
let mut ret = vec![0u8; w];
chan.read_exact(&mut ret).unwrap();
assert_eq!(*msg, *ret);
let ret = String::from_utf8(ret).unwrap();
println!("read: {ret:?}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment