栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在sshj中执行命令序列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在sshj中执行命令序列

您可以考虑使用类似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();    }

这是完整可行示例的链接。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/498198.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号