Here is my code, which retrieves content of the file, on the remote server and display as output.
package sshexample; import com.jcraft.jsch.*; import java.io.*; public class SSHexample { public static void main(String[] args) { String user = "user"; String password = "password"; String host = "192.168.100.103"; int port=22; String remoteFile="sample.txt"; try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); System.out.println("Establishing Connection..."); session.connect(); System.out.println("Connection established."); System.out.println("Creating SFTP Channel."); ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp"); sftpChannel.connect(); System.out.println("SFTP Channel created."); InputStream out= null; out= sftpChannel.get(remoteFile); BufferedReader br = new BufferedReader(new InputStreamReader(out)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); sftpChannel.disconnect(); session.disconnect(); } catch(JSchException | SftpException | IOException e) { System.out.println(e); } } }
Now how to implement this program that the file is copied in the localhost and how to copy a file from localhost to the server.
Here how to make work the transfer of files for any format of files.
JSch is the Java implementation of SSH2 that allows us to connect to an SSH server and use port forwarding, X11 forwarding, and file transfer. Also, it is licensed under the BSD style license and provides us with an easy way to establish an SSH connection with Java.
The proper steps to upload a file to FTP serverEnter local passive mode for data connection. Set file type to be transferred to binary. Create an InputStream for the local file. Construct path of the remote file on the server.
The most trivial way to upload a file over SFTP with JSch is:
JSch jsch = new JSch(); Session session = jsch.getSession(user, host); session.setPassword(password); session.connect(); ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp"); sftpChannel.connect(); sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");
Similarly for a download:
sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");
You may need to deal with UnknownHostKey
exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With