Java – Not able to connect to Secured Channel when doing SFTP with JSch

exceptionjavajschsftp

I am trying to implement JSch to retrieve a file from remote windows sftp server to Linux.

Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
        try{
           JSch jsch = new JSch();
           session = jsch.getSession("userName","hostName",22);
           session.setPassword("password");
           java.util.Properties config = new java.util.Properties();
           config.put("StrictHostKeyChecking", "no");
          session.setConfig(config);
          session.connect();
          System.out.println(session.sendKeepAliveMsg());
          channel = session.openChannel("sftp");
          channel.connect();
         }catch(Exception e){
               e.printstacktrace();
         }

I am getting following exception while running this code.

com.jcraft.jsch.JSchException: java.io.IOException: inputstream is closed
    at com.jcraft.jsch.ChannelSftp.start(ChannelSftp.java:288)
    at com.jcraft.jsch.Channel.connect(Channel.java:152)

When I debug I found:

start();

method in Channel class is throwing the exception. Is there anyway I can prevent this? I don't understand why the method is there without doing nothing.

Best Answer

Try to cast your channel into ChannelSft before the connect:

Channel channel = session.openChannel("sftp");
ChannelSftp channelSftp = (ChannelSftp) channel;
channelSftp.connect();
Related Topic