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条)

报告相同问题?

悬赏问题

  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题