【问题标题】:Incomplete inputStream from plink under a Java ProcessJava进程下来自plink的不完整inputStream
【发布时间】:2018-11-20 22:46:46
【问题描述】:

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

这是在线程的 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 );
}

我的两个问题是:

  • 如果服务器的主机密钥没有缓存在注册表中,在正常的 windows 命令提示符下,我将收到一条消息,要求将此密钥存储在缓存中。在 Java 中,“in”永远不会收到此消息,为什么?

  • 如何检查密码是否错误?让我解释得更好一点...

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

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“in”中,我没有收到此消息。为什么会这样?

以下是 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 进程的 InputStream 应该同时接收到密钥消息和拒绝访问,但他们没有。

顺便说一句,我也尝试查看错误流

InputStream err = p.getErrorStream();

并做与“in”相同的事情,但也没有。

有没有办法让这两条消息显示在 Process 的输入流中?

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

【问题讨论】:

  • 不要使用控制台应用程序在 Java 中实现 SSH,使用原生 Java SSH 库,如 JSch。

标签: java process runtime inputstream plink


【解决方案1】:

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

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

我通过发送密码直到连接关闭来解决它。我知道这是非常糟糕的解决方案,但我将开始迁移代码以使用 JSch,如Martin Prikryl 建议的那样

对于给您带来的不便,我们深表歉意!

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 2013-09-10
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    相关资源
    最近更新 更多