How do I execute a command on a remote machine in a golang CLI?

前端 未结 4 1187
臣服心动
臣服心动 2021-02-13 07:02

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. Furthermor

4条回答
  •  梦如初夏
    2021-02-13 07:43

    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
    

提交回复
热议问题