Writing a file (with contents) to an sftp server

I need to access an SFTP server in rust, but I can’t find anything online. None of the crates have any real documentation, and ssh2 doesn’t have a way to write file contents AFAIK. GPT-4 was also not of any help. Would anyone be willing to write me an example? I am really stuck. Thank you in advance!

Use open to obtain a file object, then you can use the file's std::io::Write impl to write data to the file.

1 Like

I didn’t realize it was that simple. Thank you!

Not overly familiar with sftp and the usage of the LIBSSH2_FXF_* flags, but the documentation of open states that it opens the file in read-only mode. I think you are able to open the file so you can write to it with the open_mode method. Something like sftp.open_mode("path", ssh2::OpenFlags::WRITE, 0o666, ssh2::OpenType::File) I guess.

1 Like

You can just use create() I think? It says it opens it in Write mode.

Well, yes, but it also truncates the file by setting the ssh2::OpenFlags::TRUNCATE flag. So with create() you'd override the contents of an existing file, instead of appending to it. If that is your desired behaviour than create() is the better choice.

It doesn’t really matter, the file being written to is empty anyway. BTW, do you know how to specify the IP to the server? There doesn’t seem to be a function for it.

Are the examples in the top-level documentation helpful to you? Looks to me like you have to provide a TcpStream from the standard library that is connected to your server to your ssh Session. Once you have a session where you are successfully authenticated, you can get your Sftp handle from the Session::sftp method.

I tried set_tcp_stream(), but it threw an error. I will try some things later.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.