Home > Backend Development > Golang > How to Execute Commands on Remote Machines Using Go CLI?

How to Execute Commands on Remote Machines Using Go CLI?

Patricia Arquette
Release: 2024-11-08 10:53:02
Original
906 people have browsed it

How to Execute Commands on Remote Machines Using Go CLI?

Remote Command Execution in 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
}
Copy after login

Usage

To use the remoteRun function, you can pass in the following parameters:

  • user: Username for remote machine
  • addr: Address of remote machine
  • privateKey: Private key for SSH authentication
  • cmd: Command to be executed

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template