doudiemei2013 2019-06-04 14:05
浏览 575
已采纳

写入ssh.Session.StdinPipe()已挂起

I'm using go's ssh module, and I'm trying to pipe input from my program to the remote shell over stdin. This works as expected, printing Hello World:

mySession := PrepareSession()  // helper method to prepare a Connection and Session object
output, _ := mySession.Output("echo Hello World")
fmt.Println(output)

When I try to provide stdin input, however, it hangs on the line myStdin.Write("Hello World") (I've confirmed this with a debugger):

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

Replacing myStdin.Write("Hello World") with fmt.Fprint(myStdin, "Hello World") yields the same problem.

Overall I just don't understand how pipes work in Go - how do I get the pipe to stop hanging when I feed input to it?

  • 写回答

1条回答 默认 最新

  • doufangmu9087 2019-06-04 15:36
    关注

    StdinPipe is the standard input for the remote command, as mentioned in the docs.

    Your second example attempts to write to stdin on the remote host without running a command. Since there is no remote command, there is no consumer for stdin, hanging forever.

    Instead, you should do something similar to the Output method:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题