我想使用带有私钥登录的jsch库在远程linux服务器上执行命令。 然后在我的http响应中返回输出,这是我的代码。
package org.acme.getting.started;
import com.jcraft.jsch.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.*;
@Path("/hello")
public class GreetingResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
JSch jsch = new JSch();
Session session = null;
String privateKeyPath = "/path/to/my/private/key";
try {
jsch.addIdentity(privateKeyPath);
session = jsch.getSession(username, host, port);
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
} catch (JSchException e) {
throw new RuntimeException("Failed to create Jsch Session object.", e);
}
String command = "cat /etc/hosts";
try {
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setPty(false);
channel.connect(5000);
channel.disconnect();
session.disconnect();
return outputStream.toString();
} catch (JSchException | IOException e) {
throw new RuntimeException("Error durring SSH command execution. Command: " + command);
}
}
}
,但不返回实际的命令结果值。 这是我在http响应中得到的内容:java.io.BufferedOutputStream@462a649f
这是我的堆栈版本:
Java版本:11 jsch:0.1.55