java跳板執(zhí)行ssh命令方式
更新時間:2024年12月17日 10:25:46 作者:princeAladdin
本文分享了在Java中使用跳板機執(zhí)行SSH命令的方法,并推薦了一些Maven依賴,希望這些信息對大家有所幫助
java跳板執(zhí)行ssh命令
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();
// 創(chuàng)建跳板會話
Session jumpSession = jsch.getSession(jumpUser, jumpHost, jumpPort);
jumpSession.setPassword(jumpPassword);
jumpSession.setConfig("StrictHostKeyChecking", "no");
jumpSession.connect();
// 創(chuàng)建跳板通道
int forwardedPort = 10022; // 本地轉(zhuǎn)發(fā)端口
jumpSession.setPortForwardingL(forwardedPort, targetHost, targetPort);
// 創(chuàng)建目標(biāo)服務(wù)器會話
Session targetSession = jsch.getSession(targetUser, "localhost", forwardedPort);
targetSession.setPassword(targetPassword);
targetSession.setConfig("StrictHostKeyChecking", "no");
targetSession.connect();
// 執(zhí)行命令
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();
}
}
// 關(guān)閉通道和會話
channelExec.disconnect();
targetSession.disconnect();
jumpSession.disconnect();
} catch (JSchException | IOException e) {
LOGGER.error("跳板連接服務(wù)器執(zhí)行異常",e);
}
return excuteResult;
}
}
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
深入Ajax代理的Java Servlet的實現(xiàn)詳解
本篇文章是對Ajax代理的Java Servlet的實現(xiàn)方法進行了詳細的分析介紹,需要的朋友參考下2013-06-06
Maven依賴管理之parent與dependencyManagement深入分析
首先我們來說說parent標(biāo)簽,其實這個不難解釋,就是父的意思,pom也有繼承的。比方說我現(xiàn)在有A,B,C,A是B,C的父級?,F(xiàn)在就是有一個情況B,C其實有很多jar都是共同的,其實是可以放在父項目里面,這樣,讓B,C都繼承A就方便管理了2022-10-10

