使用 JSch 分别为各个提示提供输入

Provide inputs to individual prompts separately with JSch

问题是 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) 作为输入流,它会按预期工作。

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

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

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

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