Java通过SSH jar包,远程连接Host进行命令执行,支持接收正常返回结果以及异常结果
Pom配置:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
Java工具类 :
//SshUtil类定义
@Data
public class SshHost {
String sshId;
String platform;
String ip;
String user;
String pwd;
Integer port = 22;
}
//工具类定义
@Slf4j
public class SshUtil {
static public SshUtil sshUtil = null;
static public SshUtil getRemoteClient(SshHost sshHost) throws JSchException {
if (sshUtil == null) {
sshUtil = new SshUtil(sshHost);
}
return sshUtil;
}
public SshHost sshHost = null;
public SshUtil(SshHost host) throws JSchException {
sshHost = host;
}
public List<String> exceCommond(String commond) {
List<String> listResult = new ArrayList<>();
Session session = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(sshHost.getUser(), sshHost.getIp(), sshHost.getPort());
session.setPassword(sshHost.getPwd());
// 使用密码登录 禁止使用秘钥登录(默认先使用秘钥,失败后使用密码,耗时严重)
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications", "password");
// 连接超时
session.connect(5000);
Channel channel = session.openChannel("exec");
ChannelExec exec = (ChannelExec) channel;
// 返回结果流(命令执行错误的信息通过getErrStream获取)
exec.setCommand(commond);
exec.connect();
try {
// 开始获得SSH命令的结果
while (true) {
InputStream inputStream = exec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String buf;
// 此处是对结果进行封装,封装成自己想要的样子,我这里是map
while ((buf = reader.readLine()) != null) {
String gbk = new String(buf.getBytes("gbk"), StandardCharsets.UTF_8);
listResult.add(gbk);
}
// 对错误的处理结果进行处理
InputStream errorStream = exec.getErrStream();
if (errorStream.available() > 0) {
byte[] tmp = new byte[1024];
int i = errorStream.read(tmp, 0, 1024);
if (i < 0) {
break;
}
log.error(new String(tmp, 0, i));
//Throw.bizStatusException(new String(tmp, 0, i));
}
if (exec.isClosed()) {
break;
}
}
} finally {
//关闭连接
channel.disconnect();
}
return listResult;
} catch (JSchException e) {
e.printStackTrace();
Throw.bizStatusException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Throw.bizStatusException(e.getMessage());
} finally {
if (session != null && session.isConnected()) {
session.disconnect();
}
return listResult;
}
}
}