Executing Commands on Remote Machines with a golang CLI
To execute commands on remote machines, a Golang CLI can utilize the "golang.org/x/crypto/ssh" package. Here's a solution to your query:
The function remoteRun demonstrates how to execute a single command on a remote machine and retrieve its output:
func remoteRun(user string, addr string, privateKey string, cmd string) (string, error) { // Read or retrieve the private key key, err := ssh.ParsePrivateKey([]byte(privateKey)) if err != nil { return "", err } // Configure authentication config := &ssh.ClientConfig{ User: user, HostKeyCallback: ssh.InsecureIgnoreHostKey(), // Allow any host Auth: []ssh.AuthMethod{ ssh.PublicKeys(key), }, } // Establish a connection client, err := ssh.Dial("tcp", net.JoinHostPort(addr, "22"), config) if err != nil { return "", err } // Create a session session, err := client.NewSession() if err != nil { return "", err } defer session.Close() // Collect the command's output var b bytes.Buffer session.Stdout = &b // Execute the command err = session.Run(cmd) if err != nil { return "", err } return b.String(), nil }
This function takes the user, address, private key, and command as input and returns the command's output as a string. You can specify the user, address, and private key that grants access to the machine you wish to execute the command on.
The above is the detailed content of How to Execute Commands on Remote Machines with a Golang CLI?. For more information, please follow other related articles on the PHP Chinese website!