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.
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.
来源:https://stackoverflow.com/questions/42975994/using-jsch-to-sftp-when-one-must-also-switch-user