Home > Article > Backend Development > How to Run Remote Commands via SSH in Go CLI?
Running Remote Commands via SSH in Go CLI
To execute commands on a remote machine using a Go CLI, you'll want to utilize the "golang.org/x/crypto/ssh" package.
Simple Command Execution
Here's a function that demonstrates a simple usage of executing a single command on a remote machine and returning the output:
import ( "bytes" "golang.org/x/crypto/ssh" "io" "net" ) func remoteRun(user string, addr string, privateKey string, 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 session.Stdout = &b err = session.Run(cmd) return b.String(), err }
Usage:
output, err := remoteRun("root", "MY_IP", "PRIVATE_KEY", "ls") if err != nil { // handle error }
Multi-Hop Execution
For one-hop-away execution, you can simply establish an SSH connection to the intermediate machine first using the provided addr and privateKey. Once connected, use the remoteRun function within that session to execute the command on the internal machine.
The above is the detailed content of How to Run Remote Commands via SSH in Go CLI?. For more information, please follow other related articles on the PHP Chinese website!