登录
首页 >  Golang >  Go问答

阻塞 ssh.Session.StdinPipe() 方法

来源:stackoverflow

时间:2024-03-27 09:09:32 144浏览 收藏

在使用 Go SSH 模块传输标准输入到远程 shell 时,遇到写入stdinPipe挂起的问题。通过调试,确认问题发生在写入行上。尝试使用管道输入时,管道挂起,无法继续执行。

问题内容

我正在使用 go 的 ssh 模块,并且我正在尝试通过 stdin 将输入从我的程序传输到远程 shell。这按预期工作,打印 hello world

mysession := preparesession()  // helper method to prepare a connection and session object
output, _ := mysession.output("echo hello world")
fmt.println(output)

但是,当我尝试提供标准输入输入时,它挂在 mystdin.write("hello world") 行上(我已使用调试器确认了这一点):

mySession := PrepareSession()
myStdin, _ := mySession.StdinPipe()
myStdin.Write("Hello World")
output, _ := mySession.Output("cat /dev/stdin | echo")
fmt.Println(output)

fmt.fprint(mystdin, "hello world") 替换 mystdin.write("hello world") 会产生相同的问题。

总的来说,我只是不明白管道在 go 中是如何工作的 - 当我向管道提供输入时,如何让管道停止挂起?


解决方案


stdinpipe远程命令的标准输入,如 the docs 中所述。

您的第二个示例尝试在不运行命令的情况下写入远程主机上的标准输入。由于没有远程命令,因此没有 stdin 的消费者,永远挂起。

相反,您应该执行类似于 Output 方法的操作:

func (s *Session) Output(cmd string) ([]byte, error) {
    if s.Stdout != nil {
        return nil, errors.New("ssh: Stdout already set")
    }
    var b bytes.Buffer
    s.Stdout = &b
    err := s.Run(cmd)  <---- you need to run a command on the remote host.
    return b.Bytes(), err
}

以上就是《阻塞 ssh.Session.StdinPipe() 方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>