使用 sshj 返回 Shell 返回值
我正在使用 sshj 连接到远程计算机以检索各种值。据我在 sshj 中的理解,当我执行以下代码来检索远程计算机的主机名时:
SSHClient sshClient = new SSHClient();
Session session = sshClient.startSession();
Command commandObject = session.exec("hostname");
我知道我可以通过抓取输入流来检索返回值
session.getInputStream();
我似乎遇到的问题是,会话对象(和命令)被设计为“使用一次然后扔掉”的时尚。因此,考虑到这一点,我想在完成后关闭会话以清理资源,即
commandObject.close();
但是,由于 sshj 的异步特性,我无法确定输入流中何时有返回值可用因为似乎没有内置任何回调功能。
我能想到解决此问题的唯一方法是在检查输入流之前休眠预定的时间。然而我觉得这只是一个黑客,我希望有一个更好的解决方案来解决这一切。
有人在使用 sshj 时遇到过类似的问题吗?有什么可能的解决方案吗?
干杯!
I am using sshj to connect to remote machines to retrieve various values. As I understand in sshj, when I perform the following code to retrieve the hostname of the remote machine:
SSHClient sshClient = new SSHClient();
Session session = sshClient.startSession();
Command commandObject = session.exec("hostname");
I know that I can retrieve the return values by grabbing the inputstream
session.getInputStream();
The problem that I seem to have is that, the session object (and command) is designed as a 'use once then throwaway' fashion. So, with this in mind, I want to close the session once I am finished with it to clean up the resources, i.e.
commandObject.close();
However, due to the asynchronous nature of sshj, I am unable to determine when a return value is available in the inputstream as there doesn't seem to be any callback feature built in.
The only way that I can think of getting around this issue is to sleep for a predefined period before inspecting the inputstream. However I feel as though this is merely a hack, and I hope that there is a better solution to all of this.
Has anyone had any similar issues using sshj? With any possible solutions?
Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在 Session 对象上调用 join(),当命令退出时,此方法将返回(或者如果超时到期)。然后你可以使用 getExitCode() 检查退出代码 ->如果未收到退出代码,则该整数可能为 null。
编辑:返回值是指命令生成的输出吗? getInputStream() 或 getErrorStream() 返回的 InputStream 实现了 available() 方法,因此您可以基于该方法实现解决方案。
You can call join() on the Session object, and when the command has exited this method will return (or if the timeout expires). Then you can check the exit code with getExitCode() -> Integer which may be null if no exit code was received.
Edit: by return values did you mean the output generated by the command? The InputStream retured by getInputStream() or getErrorStream() implement the available() method, so you can implement a solution based on that.