How to upload a file using rust to sftp.
This is the only useful link i have found: openssh_sftp_client. But the minimal documentation surrounding usage of this library is making it really difficult
Note: I am not talking about uploading to sftp using cli like sftp
or rftp
I tried two crates ssh2
and rust-ftp
but i am getting error:
use std::io::prelude::*;
use std::net::TcpStream;
use std::path::Path;
use ssh2::Session;
// Connect to the local SSH server
let tcp = TcpStream::connect("SFTP_IP:PORT").unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp);
sess.handshake().unwrap();
sess.userauth_agent("username").unwrap();
// Write the file
let mut remote_file = sess.scp_send(Path::new("remote"),
0o644, 10, None).unwrap();
remote_file.write(b"1234567890").unwrap();
// Close the channel and wait for the whole content to be tranferred
remote_file.send_eof().unwrap();
remote_file.wait_eof().unwrap();
remote_file.close().unwrap();
remote_file.wait_close().unwrap();
use std::str;
use std::io::Cursor;
use ftp::FtpStream;
fn main() {
// Create a connection to an FTP server and authenticate to it.
let mut ftp_stream = FtpStream::connect("SFTP_IP:PORT").unwrap();
let _ = ftp_stream.login("username", "password").unwrap();
// Get the current directory that the client will be reading from and writing to.
println!("Current directory: {}", ftp_stream.pwd().unwrap());
// Change into a new directory, relative to the one we are currently in.
let _ = ftp_stream.cwd("test_data").unwrap();
// Retrieve (GET) a file from the FTP server in the current working directory.
let remote_file = ftp_stream.simple_retr("ftpext-charter.txt").unwrap();
println!("Read file with contents\n{}\n", str::from_utf8(&remote_file.into_inner()).unwrap());
// Store (PUT) a file from the client to the current working directory of the server.
let mut reader = Cursor::new("Hello from the Rust \"ftp\" crate!".as_bytes());
let _ = ftp_stream.put("greeting.txt", &mut reader);
println!("Successfully wrote greeting.txt");
// Terminate the connection to the server.
let _ = ftp_stream.quit();
}
I have managed to find a workaround, but this is not ideal.
Instead of creating a file locally and then uploading to sftp, I am writing the file directly in sftp.
use std::net::TcpStream;
use ssh2::Session;
use std::path::Path;
let tcp = TcpStream::connect("IP:PORT")).unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_Stream(tcp);
sess.handshake().unwrap();
sess.userauth_password("USER", "PSWD").unwrap();
let sftp = sess.sftp().unwrap();
sftp.mkdir(Path::new("path/to/sftp/dir"), 0o777).ok();
sftp.create(&Path::new("path/to/file/in/sftp/dir/file.json"))
.unwrap()
.write_all("text to be written to file")
.unwrap();