Use a bind address with Jsch Session

对着背影说爱祢 提交于 2019-12-08 03:36:46

问题


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

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.

  1. 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);
    
  2. Attempted to use the build in port forwarding with the Session Class

    session.setPortForwardingL(0, "1.1.1.1", 22);
    

回答1:


Using the following SocketFactory worked for me:

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();
    }

}

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).

I set the factory immediately before calling session.connect():

SocketFactory sfactory = new MySocketFactory();
session.setSocketFactory(sfactory);

session.connect();


来源:https://stackoverflow.com/questions/56120486/use-a-bind-address-with-jsch-session

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