SFTP (Secured File Transfer Protocol)

Day 3.

SFTP allows an application to send a file from a source system or server to a target system or server.

For this you need to have a pair of public private key ready with you. The private key should be in the source system which will be sent to the target server with the file which your application is sending to the target server.

Now the target server should have the public key from the pair. When you will send the file and the private key along with it, the combination of public private key will be checked. If it is the part of the pair , then file will be accepted otherwise the application will throw one error  message that the key which was added as identity is INVALID.

Let us see one sample code in Java which implements SFTP.

JSch jsch = new JSch();
jsch.addIdentity(privatekey);  
session = jsch.getSession(
username, serverhost, portNumber);   

/**
*in most of cases like when for Linux servers password is *not required to pass.
*You can just omit this line while implementing SFTP
*/    
session.setPassword(
password);        
java.util.
Properties config = new java.util.Properties();        

config.put("StrictHostKeyChecking", "no");       

session.setConfig(config);         
session.connect();        

System.out.println("Host connected.");        
channel = session.openChannel(
"sftp");        

channel.connect();         
System.out.println("sftp channel opened and connected.");        
channelSftp = (
ChannelSftp) channel;        
/**
*server's destination path where you want to send your *files
*/
channelSftp.cd(
serverDestinationPath);        
File f = new File(fileName);        
channelSftp.put(
new FileInputStream(f), f.getName());        
log.info(
"File transfered successfully to host using SFTP.");

However, in most of the cases you might get error if the destination path or the location of private key which is being added as identity is not valid.

Always keep this inside a try-catch block followed by a finally block where you have to close the SFTP channel followed by session.close(); method call.

I will update this post again. Post your questions below.

2 Replies to “SFTP (Secured File Transfer Protocol)”

Leave a comment

Design a site like this with WordPress.com
Get started