Execute Remote Commands with SSH in Golang CLI
Executing commands on remote machines is a common task when automating system administration. In Golang, the "golang.org/x/crypto/ssh" package offers a convenient way to establish SSH connections and run commands remotely.
To execute a command on a remote machine, follow these steps:
Establish an SSH Connection:
Use the ssh.Dial function to establish an SSH connection to the remote machine. You will need to provide the following information:
Here is an example function demonstrating how to run a remote command and return its output:
import ( "bytes" "net" "golang.org/x/crypto/ssh" ) func remoteRun(user, addr, privateKey, cmd string) (string, error) { key, err := ssh.ParsePrivateKey([]byte(privateKey)) if err != nil { return "", err } config := &ssh.ClientConfig{ User: user, HostKeyCallback: ssh.InsecureIgnoreHostKey(), Auth: []ssh.AuthMethod{ ssh.PublicKeys(key), }, } client, err := ssh.Dial("tcp", net.JoinHostPort(addr, "22"), config) if err != nil { return "", err } session, err := client.NewSession() if err != nil { return "", err } defer session.Close() var b bytes.Buffer // capture output session.Stdout = &b // get output err = session.Run(cmd) return b.String(), err }
This function can be used to execute commands on remote machines, providing a convenient way to automate system administration tasks from Golang CLI scripts.
The above is the detailed content of How to Execute Remote Commands with SSH in a Golang CLI?. For more information, please follow other related articles on the PHP Chinese website!