有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从Java执行SSH命令会发送状态代码255,但如果有效,则会在终端中发送

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

我禁用了防火墙,并将服务器上侦听SSH的端口更改为22,因为我使用了另一个端口,但没有任何功能。它不会抛出异常或任何东西,如果连接没有问题。有什么想法吗

我试过使用sshjJSch库,但两者都有相同的问题

货运代理已关闭

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) 个答案

  1. # 1 楼答案

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

    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