package com.chrtc.common.util;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* @create 2021-12-17 18:11
* @desc JSch工具类
**/
public class JSchUtils {
private static JSch jSch = null;
private static Session session;
/***
* @Author xhh
* @Description 获取session
* @GreateTime 2021/12/17 18:16
* @Params []
* @return
*/
public static Session getSession() throws JSchException {
//创建JSch对象
if (null == jSch) {
synchronized (JSch.class) {
if (jSch == null) {
jSch = new JSch();
}
}
}
//"~/.ssh/id_rsa"
//检查本地是否有SSH Key存在
if (Files.exists(Paths.get("1111aaaa"))) {
//设置私钥
jSch.addIdentity("1111aaaa", "xhh");
}
//获取session
if (null == session) {
synchronized (Session.class) {
if (session == null) {
session = jSch.getSession("root", "192.168.21.11", 22);
}
}
}
session.setPassword("root");
session.setConfig("StrictHostKeyChecking", "no");
return session;
}
/***
* @Author xhh
* @Description 执行shell command命令
* @GreateTime 2021/12/17 18:41
* @Params [session, command]
* @return
*/
public static List<String> remoteExecute (Session session, String command) throws JSchException {
List<String> resultLines = new ArrayList<>();
ChannelExec channel = null;
try {
//创建通道执行器
channel = (ChannelExec) session.openChannel("exec");
//执行命令
channel.setCommand(command);
//或缺输入流
InputStream input = channel.getInputStream();
//连接时间
channel.connect(10000);
//读取流
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(input));
String inputLine = null;
while ((inputLine = inputReader.readLine()) != null) {
resultLines.add(inputLine);
}
} finally {
if (input != null) {
try {
//关流
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (channel != null) {
try {
channel.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return resultLines;
}
}
浪客行1213的简书
xhh