Using JSch to SFTP when one must also switch user

五迷三道 提交于 2019-12-17 09:59:08

问题


I am using JSch in a Java client to connect to a remote server and get some files using SFTP. The following code has been working fine for me: -

JSch ssh = new JSch();
JSch.setConfig(FileTransferConstants.STRICT_HOST_KEY_CHECKING, FileTransferConstants.NO);
Session session = ssh.getSession(userName, host, port);
session.setPassword(password);
session.connect();
Channel channel = session.openChannel(FileTransferConstants.SFTP);
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
sftp.cd(remoteDirectoryPath);
sftp.lcd(localDirectoryPath);

sftp.get(remoteDirectoryPath + remoteFileName, remoteFileName);

The problem is that there has now been a change of site policy. I am no longer permitted to log on directly as this user (userName above). I must first log on as my personal user and then su into the user that has access to the files I want to SFTP.

I don't think there is anyway I can refactor the above code to achieve this and so I have started looking at using a shell or exec channel instead. I have had little success so far and cannot seem to find any examples on the web, so I would be very grateful for any advice or pointers in the right direction. Many thanks.


回答1:


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



来源:https://stackoverflow.com/questions/42975994/using-jsch-to-sftp-when-one-must-also-switch-user

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