【发布时间】:2018-01-31 15:16:05
【问题描述】:
所以我想要做的是创建单元测试来检查调用的命令(在 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
错误信息。
【问题讨论】:
-
这可能取决于您使用的 Mina/BouncyCastle 版本。你用的是哪一个?
-
我使用的是 apache ssh core 0.5.0、slf4j-api 1.6.1 和 jsch 0.1.49
-
你试过我的答案了吗?它解决了你的问题吗?
-
实际上,当我包含更新版本的 sshd-core 时,我的大多数课程都无法识别。所以我切换回 0.5.0。事实证明,shellFactory 解决了命令处理的主要问题
标签: java ssh apache-mina