dongwh1992 2014-04-11 18:18
浏览 667
已采纳

Golang写入输入并从终端进程获取输出

I have a question regarding how to send input and receive output from a terminal subprocess such as ssh. An example in python would be something like this:

how to give subprocess a password and get stdout at the same time

I cannot find a simple example in Golang that is similar how the above work.

In Golang I would want to do something like this but it does not seem to work:

    cmd := exec.Command("ssh", "user@x.x.x.x")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    stdin, _ := cmd.StdinPipe()
    stdin.Write([]byte("password
"))
    cmd.Run()

However; I'm not sure how to do this in go because every time i exec this ssh command I am only able to get the output. I am unable to input my password automatically from code. Does anyone have examples of writing to terminal processes such as ssh? If so, please share.

  • 写回答

2条回答 默认 最新

  • donglie9067 2014-04-15 14:04
    关注

    Thanks to the comments above, I was able to get ssh access working with a password. I used golang's ssh api library. It was fairly simple as I followed the examples from:

    https://code.google.com/p/go/source/browse/ssh/example_test.go?repo=crypto

    Specifically:

    func ExampleDial() {
        // An SSH client is represented with a ClientConn. Currently only
        // the "password" authentication method is supported.
        //
        // To authenticate with the remote server you must pass at least one
        // implementation of AuthMethod via the Auth field in ClientConfig.
        config := &ClientConfig{
                User: "username",
                Auth: []AuthMethod{
                        Password("yourpassword"),
                },
        }
        client, err := Dial("tcp", "yourserver.com:22", config)
        if err != nil {
                panic("Failed to dial: " + err.Error())
        }
    
        // Each ClientConn can support multiple interactive sessions,
        // represented by a Session.
        session, err := client.NewSession()
        if err != nil {
                panic("Failed to create session: " + err.Error())
        }
        defer session.Close()
    
        // Once a Session is created, you can execute a single command on
        // the remote side using the Run method.
        var b bytes.Buffer
        session.Stdout = &b
        if err := session.Run("/usr/bin/whoami"); err != nil {
                panic("Failed to run: " + err.Error())
        }
        fmt.Println(b.String())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码