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

前端 未结 4 1199
臣服心动
臣服心动 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:30

    You can run commands on a remote machine over SSH using the "golang.org/x/crypto/ssh" package.

    Here is an example function demonstrating simple usage of running a single command on a remote machine and returning the output:

    //e.g. output, err := remoteRun("root", "MY_IP", "PRIVATE_KEY", "ls")
    func remoteRun(user string, addr string, privateKey string, cmd string) (string, error) {
        // privateKey could be read from a file, or retrieved from another storage
        // source, such as the Secret Service / GNOME Keyring
        key, err := ssh.ParsePrivateKey([]byte(privateKey))
        if err != nil {
            return "", err
        }
        // Authentication
        config := &ssh.ClientConfig{
            User: user,
            Auth: []ssh.AuthMethod{
                ssh.PublicKeys(key),
            },
            //alternatively, you could use a password
            /*
                Auth: []ssh.AuthMethod{
                    ssh.Password("PASSWORD"),
                },
            */
        }
        // Connect
        client, err := ssh.Dial("tcp", net.JoinHostPort(addr, "22"), config)
        if err != nil {
            return "", err
        }
        // Create a session. It is one session per command.
        session, err := client.NewSession()
        if err != nil {
            return "", err
        }
        defer session.Close()
        var b bytes.Buffer  // import "bytes"
        session.Stdout = &b // get output
        // you can also pass what gets input to the stdin, allowing you to pipe
        // content from client to server
        //      session.Stdin = bytes.NewBufferString("My input")
    
        // Finally, run the command
        err = session.Run(cmd)
        return b.String(), err
    }
    

提交回复
热议问题