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

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

    Try the package https://github.com/appleboy/easyssh-proxy

    package main
    
    import (
        "fmt"
        "time"
    
        "github.com/appleboy/easyssh-proxy"
    )
    
    func main() {
        // Create MakeConfig instance with remote username, server address and path to private key.
        ssh := &easyssh.MakeConfig{
            User:   "appleboy",
            Server: "example.com",
            // Optional key or Password without either we try to contact your agent SOCKET
            //Password: "password",
            // Paste your source content of private key
            // Key: `-----BEGIN RSA PRIVATE KEY-----
            // MIIEpAIBAAKCAQEA4e2D/qPN08pzTac+a8ZmlP1ziJOXk45CynMPtva0rtK/RB26
            // 7XC9wlRna4b3Ln8ew3q1ZcBjXwD4ppbTlmwAfQIaZTGJUgQbdsO9YA==
            // -----END RSA PRIVATE KEY-----
            // `,
            KeyPath: "/Users/username/.ssh/id_rsa",
            Port:    "22",
            Timeout: 60 * time.Second,
        }
    
        // Call Run method with command you want to run on remote server.
        stdout, stderr, done, err := ssh.Run("ls -al", 60*time.Second)
        // Handle errors
        if err != nil {
            panic("Can't run remote command: " + err.Error())
        } else {
            fmt.Println("don is :", done, "stdout is :", stdout, ";   stderr is :", stderr)
        }
    
    }
    

    See more example.

提交回复
热议问题