sshj使用代理连接服务器

之前我是用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

java 复制代码
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之前注入

java 复制代码
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);
相关推荐
xlsw_35 分钟前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
神仙别闹1 小时前
基于java的改良版超级玛丽小游戏
java
远游客07132 小时前
centos stream 8下载安装遇到的坑
linux·服务器·centos
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭2 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
暮湫2 小时前
泛型(2)
java
超爱吃士力架2 小时前
邀请逻辑
java·linux·后端
南宫生2 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
转码的小石2 小时前
12/21java基础
java
李小白663 小时前
Spring MVC(上)
java·spring·mvc
GoodStudyAndDayDayUp3 小时前
IDEA能够从mapper跳转到xml的插件
xml·java·intellij-idea