更新时间:2023-11-11 20:11:40
您可以考虑使用 Expect-like 第三方库,可简化远程服务的使用和捕获输出.这些库旨在执行一系列命令.您可以尝试以下一组不错的选项:
You can consider using an Expect-like third party library which simplifies working with remote services and capturing output. Those libraries are designed to execute a sequence of commands. Here is a good set of options you can try:
然而,当我要解决类似的问题时,我发现这些库相当陈旧.它们还引入了许多不需要的依赖项.所以我创建了我自己的并提供给其他人.它被称为 ExpectIt.我的图书馆的优势在项目主页上有说明.你可以试试看.
However, when I was about to solve similar problem I found these libraries are rather old. They also introduce a lot of unwanted dependencies. So I created my own and made it available for others. It is called ExpectIt. The advantages of my library it are stated on the project home page. You can give it a try.
以下是使用 sshj 与公共远程 SSH 服务交互的示例:
Here is an example of interacting with a public remote SSH service using sshj:
SSHClient ssh = new SSHClient();
...
ssh.connect("sdf.org");
ssh.authPassword("new", "");
Session session = ssh.startSession();
session.allocateDefaultPTY();
Shell shell = session.startShell();
Expect expect = new ExpectBuilder()
.withOutput(shell.getOutputStream())
.withInputs(shell.getInputStream(), shell.getErrorStream())
.build();
try {
expect.expect(contains("[RETURN]"));
expect.sendLine();
String ipAddress = expect.expect(regexp("Trying (.*)\\.\\.\\.")).group(1);
System.out.println("Captured IP: " + ipAddress);
expect.expect(contains("login:"));
expect.sendLine("new");
expect.expect(contains("(Y/N)"));
expect.send("N");
expect.expect(regexp(": $"));
expect.send("\b");
expect.expect(regexp("\\(y\\/n\\)"));
expect.sendLine("y");
expect.expect(contains("Would you like to sign the guestbook?"));
expect.send("n");
expect.expect(contains("[RETURN]"));
expect.sendLine();
} finally {
session.close();
ssh.close();
expect.close();
}
这是完整可行的链接示例.