I use Jsch lib to connect in ssh to a remote sftp server.
The program connects to the server, and then count the number of files in the directory and then displays their contents.
import java.util.Vector; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class DemoSftp { public static void main(String[] args) throws JSchException, SftpException { String hostname = "hostname"; String login = "login"; String password = "password"; String directory = "the directory"; java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch ssh = new JSch(); Session session = ssh.getSession(login, hostname, 22); session.setConfig(config); session.setPassword(password); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftp = (ChannelSftp) channel; sftp.cd(directory); Vector files = sftp.ls("*"); System.out.printf("Found %d files in dir %s%n", files.size(), directory); for (ChannelSftp.LsEntry file : files) { if (file.getAttrs().isDir()) { continue; } System.out.printf("Reading file : %s%n", file.getFilename()); BufferedReader bis = new BufferedReader(new InputStreamReader(sftp.get(file.getFilename()))); String line = null; while ((line = bis.readLine()) != null) { System.out.println(line); } bis.close(); } channel.disconnect(); session.disconnect(); } }
Thanks !
This one made my day.
Keep up the good work…
It’s very good one and help me so much but the problem is that when I use cd(dir), it doesn’t work.
its a very good one
nice simple and to the point example.
nice
very much clear and crisp code
Thank you for providing the below code , this was very clear for understanding.