SFTP SSHClient Java Example

SFTP SSHClient Java Example

If you are looking to connect Linux server through SFTP or SSHClient using java where you could connect the server and fetch data’s from directory. Please refer example below:

  • Jar needed:
<dependency>
	<groupId>sshj</groupId>
	<artifactId>sshj</artifactId>
	<version>1.0</version>
</dependency>

<dependency>
	<groupId>eddsa</groupId>
	<artifactId>eddsa</artifactId>
	<version>1.0</version>
</dependency>
  • SSHClientJavaHonkTest.java:
package com.javahonk.sftpclient;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.RemoteResourceInfo;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SSHClientJavaHonkTest {
	
	private static final Logger logger = LogManager.getLogger(SSHClientJavaHonkTest.class.getName());

	public static void main(String[] args) throws IOException {
		
		String dtsPath = "/" + "Path" + "/";
		
		SSHClient sshClient = new SSHClient();
		 
		sshClient.addHostKeyVerifier("Host key identifier"); // Will be something like this: "7a:d7:27:86:65:bf:d3:09:51:7a:ba:f9:77:ce:5e:6d"
				 
		sshClient.connect("JavaHonk.com", 10022); //Sever name and port number
		 
		sshClient.authPassword("user id", "Password");
		 
		SFTPClient sftpClient = sshClient.newSFTPClient();
				
		List<RemoteResourceInfo > files = sftpClient.ls("/");
		 
		boolean fileCreated = false;
		 
		 Set<String> filenames = new HashSet<>();
		 
		 for(RemoteResourceInfo file : files){
			 
			 String filename = file.getName();
			 
			 logger.info("SFTPing File found on date {}:{}", LocalDate.now(), filename);
			 
			 File localFile = Files.createFile(Paths.get("../test/javahonk" + "/" + filename)).toFile();
			 
			 FileSystemFile fileSystemFile = new FileSystemFile(localFile);
			 
			 sftpClient.get(file.getPath(), fileSystemFile);
			 
			 filenames.add(filename);
		 }
		 
		
		 sftpClient.close();
		 sshClient.disconnect();
		 sshClient.close();
		 

	}

}
  • For more details please refer this link

Leave a Reply

Your email address will not be published. Required fields are marked *