Friday, January 15, 2021

sftp in Java

 The code below shows how to transfer a file from one machine to another via sftp.

Session session = null;
ChannelSftp sftp = null;

try {
JSch jsch = new JSch();
session = jsch.getSession(username, remoteIPAddress);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();

com.jcraft.jsch.Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;

//Get a file from a remote machine
String path = sftp.pwd(); //remote path

//If the file is located in a different directory, switch to that directory
sftp.cd("<the path>");
sftp.get("<the file>", "<local directory where you want the file to be>");

//Send a file to a remote machine
sftp.lcd("<local directory that has the file>"); 
sftp.put("<file name>", ".");
sftp.exit();
sftp.disconnect();
session.disconnect():

} catch (JSchException je) {
Log.instance().error(je);
System.out.println("Failed to restart rx30css for the store.");
}

-----------------------------------------------------------------------------------------------------------------



If you have ever asked the questions below, you will benefit from reading this book.
What is the meaning of life?
Why do I have to suffer?
How can I have the life I like to have?
How can I be the person I want to be?
How can I have good and harmonious relations with others?

What is the true meaning of spiritual practice?  Check it out here. 

No comments:

Post a Comment