java跳板执行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();
// 创建跳板会话
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;
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论