从Java执行SSH命令会发送状态代码255,但在终端中是否起作用

时间:2018-11-21 00:43:27

标签: java ssh jsch sshj

我正在尝试开发一个小型应用程序,该应用程序允许我通过SSH将某些命令发送到远程服务器。如果我从Linux终端或Windows命令提示符下尝试它,则可以正常工作,但是当我从Java应用程序中尝试它时,它总是以255的状态代码响应。

我已经禁用了防火墙,并且将我在服务器上侦听SSH的端口更改为22,因为我使用了另一个端口,但是没有任何作用。它不会引发任何异常,也不会引发任何问题。有什么想法吗?

我尝试过使用sshjJSch库,但都遇到了相同的问题。

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());
}

1 个答案:

答案 0 :(得分:0)

更改代码,以便在执行inputStream之前获得connect

InputStream in = ce.getInputStream();
ce.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

此外,getSession应该是错误的

public Session getSession(String username,
                      String host,
                      int port)

修改

以下代码对我有用

JSch js = new JSch();
Session s = js.getSession("username", "127.0.0.1", 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("uptime");

InputStream in = ce.getInputStream();
ce.connect();

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
      System.out.println(line);
}

ce.disconnect();
s.disconnect();

System.out.println("Exit status: " + ce.getExitStatus());

输出

 10:26:08 up 149 days, 58 min,  3 users,  load average: 0.61, 0.68, 0.68
Exit status: 0