1.依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
2.demo
package common.utils;
import common.exception.SshException;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
public class SshUtils {
private static Session session = null;
public static HashMap getResult(ConnectParam param) throws SshException {
HashMap<String, String> map = new HashMap<>();
try {
JSch jsch = new JSch();
session = jsch.getSession(param.getUserName(), param.getIp(), Integer.parseInt(param.getPort()));
session.setPassword(param.getPassWord());
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications", "password");
session.connect(5000);
Channel channel = session.openChannel("exec");
ChannelExec exec = (ChannelExec) channel;
InputStream errorStream = exec.getErrStream();
exec.setCommand(param.getCommand());
exec.connect();
try {
while (true) {
InputStream inputStream = exec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String buf;
if (errorStream.available() > 0) {
byte[] tmp = new byte[1024];
int i = errorStream.read(tmp, 0, 1024);
if (i < 0) {
break;
}
throw new SshException(new String(tmp, 0, i));
}
if (exec.isClosed()) {
break;
}
}
} catch (SshException e) {
throw new SshException(e.getMessage());
} finally {
channel.disconnect();
}
return map;
} catch (Exception e) {
throw new SshException(e.getMessage());
} finally {
close();
}
}
private static void close() {
if (session != null && session.isConnected()) {
session.disconnect();
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class ConnectParam {
private String userName = "root";
private String passWord = "123456";
private String ip;
private String port = "22";
private String command = "ls";
public ConnectParam(String ip) {
this.ip = ip;
}
public ConnectParam(String userName, String passWord, String ip, String port) {
this.userName = userName;
this.passWord = passWord;
this.ip = ip;
this.port = port;
}
}
public static void main(String[] args) {
ConnectParam connectParam = new ConnectParam("168.1.1.112");
System.out.println(getResult(connectParam));
}
}
3.备注 – 连接远程耗时的原因
// 使用密码登录 禁止使用秘钥登录(默认先使用秘钥,失败后使用密码,耗时严重)
session.setConfig("StrictHostKeyChecking", "no");
// 之前没加这句大概慢17s
session.setConfig("PreferredAuthentications", "password");