Using JSch to SFTP when one must also switch user Using JSch to SFTP when one must also switch user unix unix

Using JSch to SFTP when one must also switch user


I do not think you can do this directly with JSch. But with some modification of its code, it's probably doable.

Note that my answer assumes that the server is *nix-based (what is backed by your reference to su) and uses OpenSSH SFTP server.


You have to open SSH "exec" channel, to execute something like:

sudo /bin/sftp-server

But on top of that channel, you need to build the ChannelSftp instance, not ChannelExec.

So you will need to implement Session.openChannel-like method, that will open exec channel, but create ChannelSftp for it.


For some background, see how it's possible to do sudo with WinSCP SFTP client.

Note that while the FAQ claims, that you won't be able to use password for the sudo, that's true for WinSCP. But as you have a full control of the session with JSch, you may be able to feed the password to sudo.

For that you might override the ChannelSftp.start() to write the password to the channel input, before starting the actual SFTP session.

You still need the requiretty option be off, as the SFTP cannot work with TTY.


For general considerations when automating operations using a different/root account, see:
Allowing automatic command execution as root on Linux using SSH