之前我是用jsch连接服务器的,但是没办法使用私钥连接,搜了一下似乎是不支持新版的SSH-rsa,并且jsch很久没更新了,java - "com.jcraft.jsch.JSchException: Auth fail" with working passwords - Stack Overflow
没办法只好使用sshj来连接,但是sshj并没有找到任何和proxy相关的方法,我在网上也没找到任何sshj使用代理的文章,只好去看git上的源码,发现在老版本是有proxy方法的,在0.33分支上废弃后删掉了,这个信息后来也删除了,只有看history才能看到,实属有点坑
可以看出来要通过注入SocketFactory来实现代理,sshj连接的代码我就不放了,网上都有,就放代理相关的代码
自定义ProxySocketFactory
import javax.net.SocketFactory;
import java.io.IOException;
import java.net.*;
public class ProxySocketFactory extends SocketFactory {
private final Proxy proxy;
public ProxySocketFactory(Proxy proxy) {
this.proxy = proxy;
}
@Override
public Socket createSocket() {
return new Socket(proxy);
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
Socket socket = new Socket(proxy);
socket.connect(new InetSocketAddress(host, port));
return socket;
}
@Override
public Socket createSocket(InetAddress address, int port) throws IOException {
Socket socket = new Socket(proxy);
socket.connect(new InetSocketAddress(address, port));
return new Socket(address, port);
}
@Override
public Socket createSocket(String host, int port, InetAddress clientAddress, int clientPort) throws IOException, UnknownHostException {
Socket socket = new Socket(proxy);
socket.bind(new InetSocketAddress(clientAddress, clientPort));
socket.connect(new InetSocketAddress(host, port));
return socket;
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress clientAddress, int clientPort) throws IOException {
Socket socket = new Socket(proxy);
socket.bind(new InetSocketAddress(clientAddress, clientPort));
socket.connect(new InetSocketAddress(address, port));
return socket;
}
}
在SSHClient.connect之前注入
if(!StringUtils.isEmpty(proxy)){
//proxy=127.0.0.1:2100
String[] split = proxy.split(":");
sshClient.setSocketFactory(new ProxySocketFactory(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(split[0], Integer.valueOf(split[1])))));
}
sshClient.connect(host,port);