问题
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.
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);
回答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