从模拟的SSH服务器(Apache MINA)收集命令响应



所以我要做的是创建单元测试,以检查调用的命令(通过 ssh 连接在 shell 上(是否有正确的响应。问题是我无法阅读这些回复。关于Apache MINA的教程并不多,所以我想也许你们中的一些人可以帮助我。这是一个代码

@Before
public void setUpSSHd() {
    sshd=SshServer.setUpDefaultServer();
    sshd.setPort(22999);
    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
        public boolean authenticate(String username, String password, ServerSession session) {
            // TODO Auto-generated method stub
            return true;
        }
    });
    List<NamedFactory<KeyExchange>> keyExchangeFactories;
    keyExchangeFactories = sshd.getKeyExchangeFactories();
    sshd.setKeyExchangeFactories(keyExchangeFactories);
    try {
        sshd.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
@After
public void teardown() throws Exception { sshd.stop(); }
@Test
public void testCommands() throws Exception {
    SshClient client = SshClient.setUpDefaultClient();
    client.start();
    ClientSession session = null;
    try {
        session = client.connect("localhost", 22999).await().getSession();
        session.authPassword("none", "none").await().isSuccess();
        System.out.println("Connection established");
        final ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
        ByteArrayOutputStream sent = new ByteArrayOutputStream();
        PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
        channel.setIn(new PipedInputStream(pipedIn));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        channel.setOut(out);
        channel.setErr(err);
        channel.open();
        pipedIn.write("dirrn".getBytes());
        pipedIn.flush();
        channel.waitFor(ClientChannel.CLOSED, 0);
        channel.close(false);
        client.stop();
        System.out.println(out.toString());
    } catch (Exception e) {
        e.printStackTrace();
        fail("Cannot establish a connection");
    } finally {
        if (session != null)
            session.close(true);
    }
}

现在,我只是尝试打印出收集到的回复。但是,每次尝试这样做时,我都会得到空字符串。我认为 ssh 服务器配置可能存在问题(它应该使用什么 shell?最好的情况是,如果我可以在服务器端定义自己的命令和响应,然后只在客户端检查它

编辑:我试图手动连接到这个模拟的ssh服务器,但我有 Unable to negotiate with ::1 port 22999: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1错误信息。

我建议您更新Apache SSH。根据源存储库,版本 0.5.0 已有 7 年的历史。

将您发布的代码与默认的 JCE 提供程序和 Apache SSH 一起使用

<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-core</artifactId>
    <version>0.5.0</version>
<dependency>

与 SSH 客户端的连接失败,并显示

Their offer: diffie-hellman-group1-sha1

使用更新的 Apache SSH 版本

<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-core</artifactId>
    <version>1.4.0</version>
<dependency>

连接成功

最新更新