maven 依赖
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
代码
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.lang.invoke.MethodHandles;
public class SSHJumpServerUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().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();
Session jumpSession = jsch.getSession(jumpUser, jumpHost, jumpPort);
jumpSession.setPassword(jumpPassword);
jumpSession.setConfig("StrictHostKeyChecking", "no");
jumpSession.connect();
int forwardedPort = 10022;
jumpSession.setPortForwardingL(forwardedPort, targetHost, targetPort);
Session targetSession = jsch.getSession(targetUser, "localhost", forwardedPort);
targetSession.setPassword(targetPassword);
targetSession.setConfig("StrictHostKeyChecking", "no");
targetSession.connect();
ChannelExec channelExec = (ChannelExec) targetSession.openChannel("exec");
channelExec.setCommand(command);
InputStream in = channelExec.getInputStream();
channelExec.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
excuteResult = new String(tmp, 0, i);
}
if (channelExec.isClosed()) {
if (in.available() > 0) continue;
LOGGER.debug("exit-status: " + channelExec.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
ee.printStackTrace();
}
}
channelExec.disconnect();
targetSession.disconnect();
jumpSession.disconnect();
} catch (JSchException | IOException e) {
LOGGER.error("跳板连接服务器执行异常",e);
}
return excuteResult;
}
}