使用JSch连接SFTP时如何选择网络接口 [英] How to select network interface when connecting to SFTP with JSch

查看:930
本文介绍了使用JSch连接SFTP时如何选择网络接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了通过JSch创建远程SFTP服务器会话的问题:

I am facing problem to create a session to a remote SFTP server by JSch:

我用来通过shell连接sftp服务器的命令是:

The command i use to connect the sftp server through shell is:

sftp -o BindAddress=SOME_IP_ADDRRESS myUserName@HOST_IP_ADDR

并且工作正常,但是当我尝试使用Java(JSch)时,我收到超时异常。 Java代码是

and its working fine, but when I am trying with Java (JSch) then I am getting a timeout exception. The Java code is

/* KEY_FILE_NAME = is a file with rsa public key */
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(KEY_FILE_NAME).getFile());
JSch jsch = new JSch();
jsch.addIdentity(file.getAbsolutePath());
Properties hash = new Properties();
hash.put("StrictHostKeyChecking", "no");
logger.debug("SSh Server Host name >>" + SSH_SERVER_HOST_NAME + " || User Name >>" +  SSH_SERVER_USER_NAME);

session = jsch.getSession(SSH_SERVER_USER_NAME, SSH_SERVER_HOST_NAME);
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.setConfig(hash);
session.setPort(22);
session.setTimeout(45000);
session.connect();

我得到的例外是:


com.jcraft.jsch.JSchException:超时:套接字未建立

com.jcraft.jsch.JSchException: timeout: socket is not established

我猜它会像我没有在我使用shell命令时使用 -o 选项设置 BindAddress 。如果是这种情况,那么如何在JSch中设置 -o BindAddress 参数?或者我做错了什么,请建议。

I guess its coming as I am not setting the BindAddress with -o option which I am using while I am using the shell command. If that is the case then how to set the -o BindAddress parameter in JSch? Or am I doing something wrong, please suggest.

推荐答案

我认为没有明确支持选择连接的网络接口来自JSch。

I do not think there's an explicit support for selecting a network interface to connect from in JSch.

但你可以实现 SocketFactory 界面,例如它创建一个 Socket 实例使用构造函数重载与 localAddr

But you can implement a SocketFactory interface, such as that it creates a Socket instance using the constructor overload with the localAddr:

public Socket(InetAddress address, int port, InetAddress localAddr, int localPort)

(对于 localPort 使用0)

然后将工厂传递给 Session.setSocketFactory() $ c> connect(),你应该很好。

Then pass the factory to the Session.setSocketFactory() before calling the connect() and you should be good.

这篇关于使用JSch连接SFTP时如何选择网络接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆