英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论