我正在尝试开发一个小型应用程序,允许我通过 SSH 将某些命令发送到远程服务器。如果我从 Linux 终端或 Windows 命令提示符尝试它,它可以正常工作,但是当我从我的 Java 应用程序执行它时,它总是以状态代码 255 响应。
我禁用了防火墙,并将服务器上监听 SSH 的端口更改为 22,因为我使用了另一个,但没有任何效果。它不会给我抛出异常或任何东西,如果它连接没有问题。有任何想法吗?
ForwardAgent 已关闭
sshj 示例
private void sshj() throws Exception {
SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier((s, i, publicKey) -> true);
ssh.connect("host", 22);
Session session = null;
try {
ssh.authPassword("username", "password");
session = ssh.startSession();
Session.Command cmd = session.exec("command");
System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
cmd.join(5, TimeUnit.SECONDS);
System.out.println("Exit status: " + cmd.getExitStatus());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
ssh.disconnect();
}
}
JSch 示例
private static void jsch() throws Exception {
JSch js = new JSch();
Session s = js.getSession("username", "host", 22);
s.setPassword("password");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
s.setConfig(config);
s.connect();
Channel c = s.openChannel("exec");
ChannelExec ce = (ChannelExec) c;
ce.setCommand("command");
ce.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
ce.disconnect();
s.disconnect();
System.out.println("Exit status: " + ce.getExitStatus());
}