异步从SSH输出中读取数据

huangapple go评论138阅读模式
英文:

Asynchronously Reading From SSH Output

问题

我想编写一个函数,它接受一个SSH会话并运行一个命令,提供一个io.Reader来读取其输出。

  1. package main
  2. import (
  3. "golang.org/x/crypto/ssh"
  4. "io"
  5. )
  6. func StreamOutput(session *ssh.Session, command string) (output io.Reader, err error) {
  7. if session != nil {
  8. defer session.Close()
  9. }
  10. if err != nil {
  11. return output, err
  12. }
  13. // 连接到输出
  14. outReader, err := session.StdoutPipe()
  15. if err != nil {
  16. return output, err
  17. }
  18. errReader, err := session.StderrPipe()
  19. if err != nil {
  20. return output, err
  21. }
  22. output = io.MultiReader(outReader, errReader)
  23. err = session.Start(command)
  24. // 返回要读取的读取器
  25. return output, err
  26. }

然而,当我使用ioutil.ReadAll读取output时,它只间歇性地打印适当的输出,即使调用了session.Wait()。这可能是为什么?是否有更好的方法来返回函数的输出(例如使用通道)?谢谢!

英文:

I'd like to write a function that takes a SSH session and runs a command, providing an io.Reader that reads its output as it is recieved.

  1. package main
  2. import (
  3. "golang.org/x/crypto/ssh"
  4. "io"
  5. )
  6. func StreamOutput(session *ssh.Session, command string) (output io.Reader, err error) {
  7. if session != nil {
  8. defer session.Close()
  9. }
  10. if err != nil {
  11. return output, err
  12. }
  13. // connect to both outputs
  14. outReader, err := session.StdoutPipe()
  15. if err != nil {
  16. return output, err
  17. }
  18. errReader, err := session.StderrPipe()
  19. if err != nil {
  20. return output, err
  21. }
  22. output = io.MultiReader(outReader, errReader)
  23. err = session.Start(command)
  24. // return the readers that are to be read from
  25. return output, err

When I test this code using an ioutil.ReadAll on output, however, it only prints the appropriate output intermittently, even after calling session.Wait(). Why might this be? Is there a better way to return the functions output (channels, perhaps?)? Thanks!

答案1

得分: 0

问题是我在函数中有以下代码:

  1. if session != nil {
  2. defer session.Close()
  3. }

这样,只有在命令完成并在函数返回之前发送其stdout时,输出才会打印出来(这种情况很少发生)。我通过删除这些代码来修复了我的代码。

英文:

The problem was that I had the following code in my function:

  1. if session != nil {
  2. defer session.Close()
  3. }

That way, the output would only print if the command completed and sent back its stdout before the function returned (which was infrequent). I fixed my code simply by removing these lines.

huangapple
  • 本文由 发表于 2015年10月14日 12:03:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/33116411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定