Using JSch to SFTP when one must also switch user

青春壹個敷衍的年華 提交于 2019-11-28 13:09:03

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.


Generally a need to switch the user to automate some operation, is a sign of a bad design. You should directly use an account that has an access to the resources you need for the task. The correct solution is to setup a dedicated private key with only privileges needed for your task.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!