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

时间:2018-01-31 15:16:05

标签: java apache ssh mina

所以我试图做的是创建单元测试,检查调用的命令(在shell上通过ssh连接)是否有正确的响应。问题是我无法阅读这些回复。关于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("dir\r\n".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 错误信息。

1 个答案:

答案 0 :(得分:0)

我建议你更新Apache SSH。基于source repository版本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>

连接成功