java jsch 切换用户,当还必须切换用户时,使用JSch到SFTP

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值