Home >Backend Development >Golang >How to Execute Commands on Remote Machines Using Go CLI?
Introduction
This guide will provide you with the necessary steps to execute commands on a remote machine using a Go CLI. You'll learn how to connect via SSH, authenticate using a key, and handle single-hop connections, enabling you to execute commands on both bastion and target machines.
Using SSH for Remote Execution
The first step involves utilizing the "golang.org/x/crypto/ssh" package to establish an SSH connection. This package provides the necessary functionality for secure remote command execution.
Example Usage
To demonstrate how it works, let's create a function called remoteRun that runs a single command on a remote machine and returns the output:
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 session.Stdout = &b err = session.Run(cmd) return b.String(), err }
Usage
To use the remoteRun function, you can pass in the following parameters:
Single-Hop Connections
If you need to connect to the target machine via a bastion machine, you can use the remoteRun function in a nested fashion:
bastionOutput, err := remoteRun("user", "bastion-addr", "key", "ssh user@target-addr -p 22") if err != nil { // Handle error } targetOutput, err := remoteRun("user", "target-addr", "key", "command-on-target") if err != nil { // Handle error }
In this example, the bastionOutput variable contains the output from the SSH command that connects to the target machine. From there, the targetOutput variable contains the output of the command executed on the target machine.
The above is the detailed content of How to Execute Commands on Remote Machines Using Go CLI?. For more information, please follow other related articles on the PHP Chinese website!