Home > Backend Development > Golang > How to Execute Remote Commands with SSH in a Golang CLI?

How to Execute Remote Commands with SSH in a Golang CLI?

DDD
Release: 2024-11-11 08:12:03
Original
972 people have browsed it

How to Execute Remote Commands with SSH in a Golang CLI?

Execute Remote Commands with SSH in Golang CLI

Executing commands on remote machines is a common task when automating system administration. In Golang, the "golang.org/x/crypto/ssh" package offers a convenient way to establish SSH connections and run commands remotely.

To execute a command on a remote machine, follow these steps:

  1. Establish an SSH Connection:
    Use the ssh.Dial function to establish an SSH connection to the remote machine. You will need to provide the following information:

    • Username
    • IP address or hostname
    • Port (default is 22)
    • Authentication credentials (key or password)
  2. Create an SSH Session:
    Once the connection is established, use the NewSession function to create a new session. The session represents a connection to a specific command.
  3. Configure Input and Output:
    You can configure the standard in and out streams for the session. For example, you can redirect the output to a bytes.Buffer to capture the command results.
  4. Run the Command:
    Use the session.Run function to execute the desired command on the remote machine. This function will block until the command completes.

Here is an example function demonstrating how to run a remote command and return its output:

import (
    "bytes"
    "net"

    "golang.org/x/crypto/ssh"
)

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  // capture output
    session.Stdout = &b // get output

    err = session.Run(cmd)
    return b.String(), err
}
Copy after login

This function can be used to execute commands on remote machines, providing a convenient way to automate system administration tasks from Golang CLI scripts.

The above is the detailed content of How to Execute Remote Commands with SSH in a Golang 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template