SoFunction
Updated on 2025-03-04

Java springboard execution ssh command method

Java springboard executes ssh command

maven dependency

<dependency>
    <groupId></groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.5.6</version>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>logback-core</artifactId>
    <version>1.5.6</version>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>
import ;
import ;
import ;
import ;
import org.;
import org.;

import ;
import ;
import ;

public class SSHJumpServerUtil {

    private static final Logger LOGGER = (().lookupClass());

    public static String executeCommandWithJumpServer(String jumpHost, String jumpUser, String jumpPassword, int jumpPort,
                                                    String targetHost, String targetUser, String targetPassword, int targetPort,
                                                    String command) {
        String excuteResult = null;
        try {
            JSch jsch = new JSch();

            // Create a springboard session            Session jumpSession = (jumpUser, jumpHost, jumpPort);
            (jumpPassword);
            ("StrictHostKeyChecking", "no");
            ();

            // Create a springboard channel            int forwardedPort = 10022; // Local forwarding port            (forwardedPort, targetHost, targetPort);

            // Create a target server session            Session targetSession = (targetUser, "localhost", forwardedPort);
            (targetPassword);
            ("StrictHostKeyChecking", "no");
            ();

            // Execute the command            ChannelExec channelExec = (ChannelExec) ("exec");
            (command);

            InputStream in = ();
            ();

            // Read command output            byte[] tmp = new byte[1024];
            while (true) {
                while (() &gt; 0) {
                    int i = (tmp, 0, 1024);
                    if (i &lt; 0) break;
                    excuteResult = new String(tmp, 0, i);
                }
                if (()) {
                    if (() &gt; 0) continue;
                    ("exit-status: " + ());
                    break;
                }
                try {
                    (1000);
                } catch (Exception ee) {
                    ();
                }
            }

            // Close channels and sessions            ();
            ();
            ();
        } catch (JSchException | IOException e) {
            ("Springboard connection server execution exception",e);
        }

        return excuteResult;
    }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.