服务器基于安全考虑未暴露不必要的端口,
有些时候我们需要远程连接这些端口, 比如只有3306 仅允许本地连接, 这个时候我们可以通过ssh proxy 方式连接.
直接上代码:
package com.etoak.demo;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
* ssh 代理转发端口
* @author lizhenhe 2022/7/19 21:11
*/
public class SSHProxy {
private static final SSHProxy proxy = new SSHProxy();
private Session session;
/**
* @return
*/
public static SSHProxy getInstance() {
return proxy;
}
/**
* @param host SSH主机
* @param port SSH端口
* @param userId SSH用户
* @param keyFilePath 私钥路径
* @return
* @throws JSchException
*/
public void createSSHSession(String host, int port, String userId, String keyFilePath) throws JSchException {
JSch jsch = new JSch();
this.session = jsch.getSession(userId, host, port);
jsch.addIdentity(keyFilePath);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
}
/**
* @param localePort 本地服务端口
* @param targetHost 连接的目标主机
* @param targetPort 连接的目标端口
* @return
* @throws JSchException
*/
public void forward(int localePort, String targetHost, int targetPort) throws JSchException {
session.setPortForwardingL(localePort, targetHost, targetPort);
}
/**
* @param args
*/
public static void main(String[] args) {
// ===============1. 实例化===============
SSHProxy proxy = SSHProxy.getInstance();
// ===============2. 创建SSH会话===============
//SSH服务器
String host = "x.x.x.x";
//ssh连接私钥路径, 放在项目中,使用配置文件代替
String keyFilePath = "/Users/lizhenhe/Downloads/jsh-ssh-demo/src/main/resources/key.ppk";
//SSH服务端口
int port = 22;
//SSH连接用户名
String userId = "root";
try {
proxy.createSSHSession(host, port, userId, keyFilePath);
} catch (JSchException e) {
e.printStackTrace();
}
// ===============3. 端口跳转 ===============
// 程序中使用 jdbc:mysql://localhost:13306 连接, 其中13306 是通过ssh 代理过来的
// 本地服务端口, 这个可以根据需求更改
int localePort = 13306;
// 目标服务器
String targetHost = "localhost";
// 目标服务端口
int targetPort = 3306;
try {
proxy.forward(localePort, targetHost, targetPort);
//fixme 上线时 修改成logger
System.out.println("通过ssh转发端口成功");
} catch (JSchException e) {
e.printStackTrace();
}
}
}
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
这个时候 你就可以直接通过代码或常用客户端 连接转发出来的端口 如上例中 13306 来连接数据库了,