0

I have the below code which works for FTP. How do I make it to work for SFTP

((ChannelExec) channel).setCommand(cmd);
channel.setXForwarding(true);
channel.setInputStream(System.in);
InputStream in=channel.getInputStream();
channel.connect();
return in;

I know that I need to use ChannelSftp instead of Channel class, but I get type cast error in the setcommand line. Cannot cast type ChannelSftp to ChannelExec

MansoorShaikh
  • 913
  • 1
  • 6
  • 19

2 Answers2

1

The first thing to understand is SFTP is different than FTP or FTP/s. SFTP works off of SSH whereas FTP/s uses SSL.

That being said, JSCH provides a pretty straight forward way to use SFTP, including setting X forwarding. Take a look at the examples as well as the linked question from mabbas.

Based upon your comment, it appears that you actually want a remote shell to be invoked/executed against, try the following to see if it'll do what you need:

//connect to the remote shell
Channel channel=session.openChannel("shell");
((ChannelShell)channel).setAgentForwarding(true);
channel.setInputStream(System.in); //Send commands here
channel.setOutputStream(System.out); //output responses here      
channel.connect();

You won't be able to use ChannelSftp as it does not have a setCommand or exec method

Community
  • 1
  • 1
Robert H
  • 11,520
  • 18
  • 68
  • 110
0

If you're using JSCH, they have several example programs which illustrate how to use the library. The SFTP client example illustrates how to open an SFTP session.

Session session=jsch.getSession(user, host, port);
...
session.connect();

Channel channel=session.openChannel("sftp");
channel.connect();
ChannelSftp c=(ChannelSftp)channel;

That's all you have to do. ChannelSftp contains functions to send and receive files, get file listings, and so on. You don't have to access the channel's input or output streams.

Kenster
  • 23,465
  • 21
  • 80
  • 106