duangongqiong6958 2016-06-07 12:52
浏览 177
已采纳

如何在golang CLI中的远程计算机上执行命令?

How do I execute a command on a remote machine in a golang CLI? I need to write a golang CLI that can SSH into a remote machine via a key and execute a shell command. Furthermore, I need to be able to do this one hop away. e.g. SSH into a machine (like a cloud bastion) and then SSH into another, internal, machine and execute a shell command.

I haven't (yet) found any examples for this.

  • 写回答

4条回答 默认 最新

  • doumengjing1500 2016-06-07 13:04
    关注

    Try with os/exec https://golang.org/pkg/os/exec/ to execute a ssh

    package main
    
    import (
        "bytes"
        "log"
        "os/exec"
    )
    
    func main() {
        cmd := exec.Command("ssh", "remote-machine", "bash-command")
        var out bytes.Buffer
        cmd.Stdout = &out
        err := cmd.Run()
        if err != nil {
            log.Fatal(err)
        }
    }
    

    To jump over machines use the ProxyCommand directive in a ssh config file.

    Host remote_machine_name
      ProxyCommand ssh -q bastion nc remote_machine_ip 22
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?