Home  >  Article  >  Backend Development  >  How to Run Remote Commands via SSH in Go CLI?

How to Run Remote Commands via SSH in Go CLI?

Susan Sarandon
Susan SarandonOriginal
2024-11-07 19:50:02788browse

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!

Statement:
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