Java Process下来自plink的不完整inputStream

时间:2018-06-11 16:06:10

标签: java process runtime inputstream plink

我的问题与使用plink.exe作为Java进程相关。

这是在Thread的run()方法中:

Runtime r = Runtime.getRuntime();
Process p = r.exec("plink -ssh " + target_ip_address);

InputStream in = p.getInputStream();
OutputStream out = p.getOutputStream();

此代码位于无限循环

// Wait until "in" has bytes available 
while ( !(in.available() > 0) ) {
  // Here I have some code that will break out of the while after 10 seconds.
// I use Thread.sleep( 100 ) and count the number of times it gets called
}

StringBuilder response = new StringBuilder();
int responseByte = 0;

while ( in.available() > 0 ) {
  responseByte = in.read();
  response.append( (char) responseByte );
}

我的两个问题是:

  • 如果服务器的主机密钥未在注册表中缓存,则在NORMAL Windows命令提示符下,我将收到一条消息,要求将此密钥存储在缓存中。在Java中,"在"永远不会收到这条消息,为什么?

  • 如何检查密码是否错误?让我解释一下......

为了检查我是否可以发送用户名,密码或任何命令,我这样做:

if ( response.contains("login as: ") ){
  out.write( username + "\r\n".getBytes() );
  out.flush();
}
else if ( response.contains("password: ") ) {
  out.write( password + "\r\n".getBytes() );
  out.flush();
}

如果密码错误,在Windows命令提示符下我收到一条拒绝访问的消息,但在Java Process InputStream"在"中,我没有得到这个。为什么会这样?

以下是Windows命令提示符操作的示例:

E:\path\to\plink>plink -ssh 128.128.128.128
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n) n
login as: username
username@128.128.128.128's password:
Access denied
username@128.128.128.128's password:

所以,我认为Java Process的InputStream应该同时接收密钥消息和拒绝访问,但它们不会。

顺便说一下,我也试过看错误流

InputStream err = p.getErrorStream();

并做同样的事情"在"中,但也没有。

有没有办法让这两条消息显示在流程'输入流?

任何帮助非常感谢!非常感谢你!

1 个答案:

答案 0 :(得分:0)

很抱歉回答我自己的问题,但我发现了问题......

事实证明,错误流实际上接收到ssh密钥消息和“拒绝访问”消息,但是,在所有授权失败后收到“拒绝访问”消息尝试和连接已关闭。

我通过发送密码解决了这个问题,直到关闭连接。我知道这是非常糟糕的解决方案,但我将开始迁移代码以使用JSch作为Martin Prikryl建议

感谢和抱歉给您带来不便!