在Jsch Session中使用绑定地址 [英] Use a bind address with Jsch Session
问题描述
我正在尝试设置一个地址,以便当我离开服务器以保存文件时,我不会以服务器的主机名离开,而要以其他IP地址离开. linux的一面是所有安装程序.我可以运行以下ssh命令,一切都会按预期进行.
I am attempting to set an address so that when I leave my server to scp a file I am not leaving as the servers hostname I am leaving as a different ip. The linux side of things is all setup. I can run the following ssh command and everything works as expected.
ssh -b 1.1.1.1 testuser@sshhost
我的问题是我现在正在尝试使用JSch来结束文件的传输,但是我无法确定正确的会话设置.我正在使用公共私钥,并且这些私钥可以正常工作.以下是我目前的流程.
My issue is now I am attemtpting to use JSch to scp the files over, but I can't figure out the correct session setup. I am using public private keys and those works correctly. Below is my current process.
JSch jsch = new JSch();
Keypair keyPair = KeyPair.load(jsch, privateKey, publicKey);
boolean keyPairdecrpy = keyPair.decrypt(passphrase);
if(keyPairdecrpy)
{
jsch.addIdentity(privateKey, passphrase);
}
Session session = jsch.getSession("user", "sshhost", 22);
Properties config new Properties();
config.put("StrickHostKeyChecking:, "no");
config.put("PreferredAuthentications", "publickey");
session.setConfig(config);
session.connect(timeout);
到目前为止,我已经尝试过了.
So the things I've tried so far.
-
创建一个设置绑定地址的套接字工厂,然后运行
Creating a Socket Factory setting the bind address and then running
InetSocketAddress addr = new InetSicketAddress("1.1.1.1", 0);
Socket socket = new Socket(sshhost, 22);
socket.bind(addr);
session.setSocketFactory((SocketFactory) socket);
尝试将内置端口转发与会话类一起使用
Attempted to use the build in port forwarding with the Session Class
session.setPortForwardingL(0, "1.1.1.1", 22);
推荐答案
使用以下SocketFactory
对我有用:
class MySocketFactory implements SocketFactory {
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
Socket socket = new Socket();
socket.bind(new InetSocketAddress("1.1.1.1", 0));
socket.connect(new InetSocketAddress(host, port));
return socket;
}
@Override
public InputStream getInputStream(Socket socket) throws IOException {
return socket.getInputStream();
}
@Override
public OutputStream getOutputStream(Socket socket) throws IOException {
return socket.getOutputStream();
}
}
我在Linux机器上使用netstat -an
对此进行了验证,并观察到连接的本地端已使用临时端口号绑定到1.1.1.1(我临时用此地址设置了一个接口).
I validated this using netstat -an
on my Linux box and observed the local side of the connection was bound to 1.1.1.1 with an ephemeral port number (I temporarily set up an interface with this address).
我在致电session.connect()
之前立即设置了工厂:
I set the factory immediately before calling session.connect()
:
SocketFactory sfactory = new MySocketFactory();
session.setSocketFactory(sfactory);
session.connect();
这篇关于在Jsch Session中使用绑定地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!