使用JSch分别为各个提示提供输入
问题在于,在常规登录后,SSH连接需要提供另一个用户ID和密码信息.
The problem is that the SSH connection requires the provision of another userid and password info after the general log in.
我正在使用JSch连接到远程服务器.它以InputStream
的形式接受输入.此InputStream
只能传递一次.由于会话是交互式的,因此会导致问题.
I am using JSch to connect to the remote server. It takes input in the form of a InputStream
. And this InputStream
can only be passed once. This causes problems as the session is interactive.
我尝试将输入流作为换行符的单独值("username\npassword\n"
)传递.但是,这不起作用.欢迎大家提出意见.即使我必须完全寻找一个新的Java库.
I've tried passing the input stream as linefeed separate values ("username\npassword\n"
). This however does not work. Any suggestions would be welcome. Even if I have to look for a new Java library altogether.
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连接显示的下一组指令.
The password is not entered properly and it does not navigate to the next set of instruction displayed by the ssh connection.
但是,如果我尝试使用系统控制台(System.in
)作为输入流,则它会按预期工作.
However, if I try the same with the system console (System.in
) as the input stream, it works as expected.
如果我正确理解了您的问题,则似乎密码提供的速度过快以及服务器的实现方式,它会丢弃输入时间过早的输入(在提示之前).
If I understand your question correctly, it looks like the password is provided too quickly and the way the server is implemented, it discards the input that comes too early (before a prompt).
您可能需要等待,然后再发送密码.
You may need to wait before sending the password.
channel.connect();
OutputStream out = channel.getOutputStream();
out.write(("username2\n").getBytes());
out.flush();
Thread.sleep(1000);
out.write(("password2\n").getBytes());
out.flush();
更高级的解决方案是实现类似期望的功能.
A more advanced solution would be to implement an Expect-like functionality.