您可以考虑使用类似Expect的第三方库,该库简化了使用远程服务和捕获输出的过程。这些库旨在执行一系列命令。您可以尝试以下一组不错的选择:
- Expect4J
- 期望
- Java的期望
但是,当我要解决类似的问题时,我发现这些库已经很旧了。它们还引入了很多不需要的依赖项。因此,我创建了自己的,并提供给其他人。它称为ExpectIt。我的图书馆的优势在项目主页上有所说明。您可以尝试一下。
这是一个使用sshj与公共远程SSH服务进行交互的示例:
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(); }这是完整可行示例的链接。



