异步从SSH输出中读取数据

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

Asynchronously Reading From SSH Output

问题

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

package main

import (
	"golang.org/x/crypto/ssh"
	"io"
)

func StreamOutput(session *ssh.Session, command string) (output io.Reader, err error) {
	if session != nil {
		defer session.Close()
	}
	if err != nil {
		return output, err
	}
	// 连接到输出
	outReader, err := session.StdoutPipe()
	if err != nil {
		return output, err
	}
	errReader, err := session.StderrPipe()
	if err != nil {
		return output, err
	}
	output = io.MultiReader(outReader, errReader)
	err = session.Start(command)
	// 返回要读取的读取器
	return output, err
}

然而,当我使用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.

package main

import (
	"golang.org/x/crypto/ssh"
	"io"
)

func StreamOutput(session *ssh.Session, command string) (output io.Reader, err error) {
	if session != nil {
		defer session.Close()
	}
	if err != nil {
		return output, err
	}
	// connect to both outputs
	outReader, err := session.StdoutPipe()
	if err != nil {
		return output, err
	}
	errReader, err := session.StderrPipe()
	if err != nil {
		return output, err
	}
	output = io.MultiReader(outReader, errReader)
	err = session.Start(command)
	// return the readers that are to be read from
	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

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

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

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

英文:

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

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

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:

确定