|
|
package com.ruoyi.common.db;
|
|
|
|
|
|
import com.jcraft.jsch.JSch;
|
|
|
import com.jcraft.jsch.Session;
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
|
import org.springframework.stereotype.Component;
|
|
|
|
|
|
import javax.annotation.PreDestroy;
|
|
|
|
|
|
@Component
|
|
|
public class SshTunnelConfig {
|
|
|
private Session session;
|
|
|
|
|
|
//@Value("${ssh.host}")
|
|
|
private String sshHost="62.234.183.14";
|
|
|
// @Value("${ssh.port}")
|
|
|
private int sshPort=22;
|
|
|
// @Value("${ssh.user}")
|
|
|
private String sshUser="root";
|
|
|
// @Value("${ssh.identity}")
|
|
|
private String sshIdentity="D:\\rpkj\\yoga-app-manager\\private_key\\runpeng20250915.pem";
|
|
|
|
|
|
// @Value("${ssh.remote.db.host}")
|
|
|
private String remoteDbHost="127.0.0.1";
|
|
|
// @Value("${ssh.local.port}")
|
|
|
private int localPort=32768;
|
|
|
|
|
|
// @Value("${ssh.remote.db.port}")
|
|
|
private int remoteDbPort=19116;
|
|
|
|
|
|
public void createSshTunnel() throws Exception {
|
|
|
JSch jsch = new JSch();
|
|
|
jsch.addIdentity(sshIdentity);
|
|
|
session = jsch.getSession(sshUser, sshHost, sshPort);
|
|
|
// session.setPassword(sshPassword);
|
|
|
|
|
|
// 避免检查已知主机,生产环境应考虑更安全的方式
|
|
|
java.util.Properties config = new java.util.Properties();
|
|
|
config.put("StrictHostKeyChecking", "no");
|
|
|
session.setConfig(config);
|
|
|
session.connect();
|
|
|
// 设置本地端口转发
|
|
|
session.setPortForwardingL(localPort, remoteDbHost, remoteDbPort);
|
|
|
System.out.println("SSH隧道已建立,本地端口:" + localPort);
|
|
|
|
|
|
}
|
|
|
|
|
|
@PreDestroy
|
|
|
public void closeSshTunnel() {
|
|
|
if (session != null && session.isConnected()) {
|
|
|
session.disconnect();
|
|
|
System.out.println("SSH隧道已关闭");
|
|
|
}
|
|
|
}
|
|
|
|
|
|
}
|