【问题标题】:Provide inputs to individual prompts separately with JSch使用 JSch 分别为各个提示提供输入
【发布时间】:2019-09-09 19:55:49
【问题描述】:

问题是SSH连接需要在一般登录后提供另一个用户名和密码信息。

我正在使用 JSch 连接到远程服务器。它以InputStream 的形式接受输入。而这个InputStream只能通过一次。这会导致问题,因为会话是交互式的。

我尝试将输入流作为换行符单独的值传递 ("username\npassword\n")。然而,这不起作用。欢迎大家提出意见。即使我必须完全寻找一个新的 Java 库。

try {
    JSch jsch=new JSch();
    Session session=jsch.getSession( "username1", "host", 22);
    session.setPassword("password1");
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect(30000);
    Channel channel=session.openChannel("shell");           
    String data = "username2\npassword2\n";
    channel.setInputStream(new ByteArrayInputStream(data.getBytes()));
    channel.setOutputStream(System.out);
    channel.connect(3*1000);
} catch (Exception e) {
    e.printStackTrace();
}   

密码输入不正确,无法导航到 ssh 连接显示的下一组指令。

但是,如果我尝试使用系统控制台 (System.in) 作为输入流,它会按预期工作。

【问题讨论】:

    标签: java ssh jsch


    【解决方案1】:

    如果我正确理解您的问题,看起来密码提供得太快了,并且服务器的实现方式,它丢弃了过早的输入(在提示之前)。

    您可能需要等待才能发送密码。

    channel.connect();
    OutputStream out = channel.getOutputStream();
    out.write(("username2\n").getBytes());
    out.flush();   
    Thread.sleep(1000); 
    out.write(("password2\n").getBytes());
    out.flush();
    

    更高级的解决方案是实现类似Expect 的功能。

    【讨论】:

      猜你喜欢
      • 2021-06-14
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多