feat:ssh 管理
This commit is contained in:
@@ -8,7 +8,7 @@
|
||||
<artifactId>xservice-basic</artifactId>
|
||||
<version>1.1</version>
|
||||
</parent>
|
||||
<version>1.2</version>
|
||||
<version>1.3</version>
|
||||
|
||||
<artifactId>xservice-common</artifactId>
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.xiang.xservice.basic.utils;
|
||||
|
||||
import com.jcraft.jsch.JSch;
|
||||
import com.jcraft.jsch.Session;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class SSHManager {
|
||||
private static final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
|
||||
|
||||
public static void createTunnel(String key, String sshHost, int sshPort,
|
||||
String sshUser, String sshPassword,
|
||||
int localPort, String remoteHost, int remotePort) throws Exception {
|
||||
if (sessionMap.containsKey(key) && sessionMap.get(key).isConnected()) {
|
||||
return; // 已存在
|
||||
}
|
||||
JSch jsch = new JSch();
|
||||
Session 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, remoteHost, remotePort);
|
||||
|
||||
sessionMap.put(key, session);
|
||||
System.out.println("SSH Tunnel for [" + key + "] established.");
|
||||
}
|
||||
|
||||
public static void closeTunnel(String key) {
|
||||
Session session = sessionMap.get(key);
|
||||
if (session != null && session.isConnected()) {
|
||||
session.disconnect();
|
||||
sessionMap.remove(key);
|
||||
System.out.println("SSH Tunnel for [" + key + "] closed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user