JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等>。
如果需要监控本机,推荐我上一篇博文工具类二十基于oshi监控服务器
依赖
<!-- 流量采集工具包 -->
<!-- <dependency>-->
<!-- <groupId>org.fusesource</groupId>-->
<!-- <artifactId>sigar</artifactId>-->
<!-- <version>1.6.4</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 远程连接指令 -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
核心SSH连接工具类
package com.test.drc.util;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class SSHLinux {
// public static void main(String[] args) throws IOException, JSchException {
// String host = "192.168.7.212";
// int port = 22;
// String user = "root";
// String password = "XXX!@#212";
// String command = "du -sh /opt/jdyp/mysql";
// List<String> res = exeCommand(host, port, user, password, command);
// res.forEach(it -> {
// System.out.println(it);
// });
//
// }
public static List<String> exeCommand(String host, int port, String user, String password, String command) {
List<String> out = null;
ChannelExec channelExec = null;
Session session = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect(10000);
channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.setErrStream(System.err);
channelExec.connect(50000);
out = IOUtils.readLines(in, "UTF-8");
channelExec.disconnect();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(</