从Java执行SSH命令会发送状态代码255,但如果有效,则会在终端中发送
我正在尝试开发一个小应用程序,它允许我通过SSH将某些命令发送到远程服务器。如果我在Linux终端或Windows命令提示符下尝试,它可以正常工作,但当我在Java应用程序中尝试时,它总是以255的状态代码响应
我禁用了防火墙,并将服务器上侦听SSH的端口更改为22,因为我使用了另一个端口,但没有任何功能。它不会抛出异常或任何东西,如果连接没有问题。有什么想法吗
货运代理已关闭
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());
}
# 1 楼答案
更改为代码,以便在执行
connect
之前获得inputStream
而且
getSession
本应是错误的编辑
下面的代码适用于我
输出