JschUtil

Origin

This tool originated from my early project: Common-tools. At that time, it was designed to solve the problem of unable to access the internal host port through the bastion host (jump server) environment. Therefore, I found the jsch library. In order to use this library in a more convenient and understandable way, JschUtil was created.

Usage

Introducing jsch

<dependency>
 <groupId>com.jcraft</groupId>
 <artifactId>jsch</artifactId>
 <version>0.1.54</version>
</dependency>

Note: As of the writing of this document, the latest version of jsch is 0.1.54. The version to be introduced should be greater than or equal to this version in theory.

Usage

SSH connection to remote host

// Create a new session for SSH connection to the jump server (bastion host), which is 10.1.1.1:22 in this case
Session session = JschUtil.getSession("10.1.1.1", 22, "test", "123456");

Port mapping

// Create a new session for SSH connection to the jump server (bastion host), which is 10.1.1.1:22 in this case
Session session = JschUtil.getSession("10.1.1.1", 22, "test", "123456");

// Map the protected internal network port 8080 of the bastion host to localhost, so we can access the internal network service by visiting http://localhost:8080/
JschUtil.bindPort(session, "172.20.12.123", 8080, 8080);

Other methods

  • generateLocalPort: Generates a local port (starting from 10001 and finding an unused local port)
  • unBindPort: Unbinds port mapping
  • openAndBindPortToLocal: Shortcut method to handle both connecting to the jump server and binding the remote host port to the local port with a single method call
  • close: Closes the SSH session