Recently a client of our unexpectedly shifted some important files we collect from an ftp to sftp server. Initially I was under the impression that it would be simple to write
I guess this is what you are looking for -
/**
* @param args
*/
public static void main(String[] args) {
/*Below we have declared and defined the SFTP HOST, PORT, USER
and Local private key from where you will make connection */
String SFTPHOST = "10.20.30.40";
int SFTPPORT = 22;
String SFTPUSER = "kodehelp";
// this file can be id_rsa or id_dsa based on which algorithm is used to create the key
String privateKey = "/home/kodehelp/.ssh/id_rsa";
String SFTPWORKINGDIR = "/home/kodehelp/";
JSch jSch = new JSch();
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
jSch.addIdentity(privateKey);
System.out.println("Private Key Added.");
session = jSch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
System.out.println("shell channel connected....");
channelSftp = (ChannelSftp)channel;
channelSftp.cd(SFTPWORKINGDIR);
System.out.println("Changed the directory...");
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SftpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(channelSftp!=null){
channelSftp.disconnect();
channelSftp.exit();
}
if(channel!=null) channel.disconnect();
if(session!=null) session.disconnect();
}
}
See more at
http://kodehelp.com/sftp-connection-public-key-authentication-java/