How to Run Remote Commands via SSH in Go CLI?

Susan Sarandon
Release: 2024-11-07 19:50:02
Original
739 people have browsed it

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

Usage:

  output, err := remoteRun("root", "MY_IP", "PRIVATE_KEY", "ls")
  if err != nil {
      // handle error
  }
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!