Browse Source

feat: 补充远程转发方法

sidian 5 years ago
parent
commit
43bbd33bbe

+ 25 - 7
hutool-extra/src/main/java/cn/hutool/extra/ssh/JschUtil.java

@@ -6,13 +6,7 @@ import cn.hutool.core.lang.Assert;
 import cn.hutool.core.net.LocalPortGenerater;
 import cn.hutool.core.util.CharsetUtil;
 import cn.hutool.core.util.StrUtil;
-import com.jcraft.jsch.Channel;
-import com.jcraft.jsch.ChannelExec;
-import com.jcraft.jsch.ChannelSftp;
-import com.jcraft.jsch.ChannelShell;
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.JSchException;
-import com.jcraft.jsch.Session;
+import com.jcraft.jsch.*;
 
 import java.io.IOException;
 import java.io.InputStream;
@@ -233,6 +227,30 @@ public class JschUtil {
 	}
 
 	/**
+	 * 绑定ssh服务端的serverPort端口, 到host主机的port端口上. <br>
+	 * 即数据从ssh服务端的serverPort端口, 流经ssh客户端, 达到host:port上.
+	 *
+	 * @param session  与ssh服务端建立的会话
+	 * @param bindPort ssh服务端上要被绑定的端口
+	 * @param host     转发到的host
+	 * @param port     host上的端口
+	 * @return 成功与否
+	 * @throws JschRuntimeException 端口绑定失败异常
+	 */
+	public static boolean bindRemotePort(Session session, int bindPort, String host, int port) throws JschRuntimeException {
+		if (session != null && session.isConnected()) {
+			try {
+				session.setPortForwardingR(bindPort, host, port);
+			} catch (JSchException e) {
+				throw new JschRuntimeException(e, "From [{}] mapping to [{}] error!", bindPort, port);
+			}
+			return true;
+		}
+		return false;
+	}
+
+
+	/**
 	 * 解除端口映射
 	 *
 	 * @param session   需要解除端口映射的SSH会话

+ 18 - 2
hutool-extra/src/test/java/cn/hutool/extra/ssh/JschUtilTest.java

@@ -3,6 +3,7 @@ package cn.hutool.extra.ssh;
 import cn.hutool.core.io.IoUtil;
 import cn.hutool.core.lang.Console;
 import com.jcraft.jsch.Session;
+import org.junit.Assert;
 import org.junit.Ignore;
 import org.junit.Test;
 
@@ -13,7 +14,7 @@ import org.junit.Test;
  *
  */
 public class JschUtilTest {
-	
+
 	@Test
 	@Ignore
 	public void bindPortTest() {
@@ -22,7 +23,22 @@ public class JschUtilTest {
 		// 将堡垒机保护的内网8080端口映射到localhost,我们就可以通过访问http://localhost:8080/访问内网服务了
 		JschUtil.bindPort(session, "172.20.12.123", 8080, 8080);
 	}
-	
+
+
+	@Test
+	@Ignore
+	public void bindRemotePort() throws InterruptedException {
+		// 建立会话
+		Session session = JschUtil.getSession("looly.centos", 22, "test", "123456");
+		// 绑定ssh服务端8089端口到本机的8000端口上
+		boolean b = JschUtil.bindRemotePort(session, 8089, "localhost", 8000);
+		Assert.assertTrue(b);
+		// 保证一直运行
+//		while (true){
+//			Thread.sleep(3000);
+//		}
+	}
+
 	@Test
 	@Ignore
 	public void sftpTest() {