Thursday, 12 December 2013

Java SFTP Connection and File Transfer using JSch

Requirement to change the location of a file via SFTP  using  JCraft
       

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;


public class Send {
 

    public static  void main (String args[] ) {
        String SFTPHOST = "";
        int SFTPPORT = 22;
        String SFTPUSER = "";
        String SFTPPASS = "";
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        System.out.println("preparing the host information for sftp.");

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            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;
            channelSftp.cd("/export/home/sanal.s");
            System.out.println(channelSftp.getHome() );
            File f = new File("c:\\party1.xml");
            channelSftp.put(new FileInputStream(f), f.getName());
            channelSftp.rename("/export/home/sanal.s/party1.xml", "/export/home/sanal.s/test/party1.xml");
            System.out.println("File transfered successfully to host.");

        } catch (Exception ex) {
             System.out.println("Exception found while tranfer the response.");
        }
        finally{
            channelSftp.exit();
            System.out.println("sftp Channel exited.");
            channel.disconnect();
            System.out.println("Channel disconnected.");
            session.disconnect();
            System.out.println("Host Session disconnected.");
        }
    }  
}

       
 

AWS Certificate Manager - Import Certificate

How to import a certificate. Use Key Store Explorer to open the cert and export keypair in PEM format  This will save a file cert.pem. Make ...