Home > Backend Development > Golang > How to Execute Commands on Remote Machines with a Golang CLI?

How to Execute Commands on Remote Machines with a Golang CLI?

DDD
Release: 2024-11-07 19:12:02
Original
861 people have browsed it

How to Execute Commands on Remote Machines with a Golang CLI?

Executing Commands on Remote Machines with a golang CLI

To execute commands on remote machines, a Golang CLI can utilize the "golang.org/x/crypto/ssh" package. Here's a solution to your query:

The function remoteRun demonstrates how to execute a single command on a remote machine and retrieve its output:

func remoteRun(user string, addr string, privateKey string, cmd string) (string, error) {
    // Read or retrieve the private key
    key, err := ssh.ParsePrivateKey([]byte(privateKey))
    if err != nil {
        return "", err
    }

    // Configure authentication
    config := &ssh.ClientConfig{
        User: user,
        HostKeyCallback: ssh.InsecureIgnoreHostKey(), // Allow any host
        Auth: []ssh.AuthMethod{
            ssh.PublicKeys(key),
        },
    }

    // Establish a connection
    client, err := ssh.Dial("tcp", net.JoinHostPort(addr, "22"), config)
    if err != nil {
        return "", err
    }

    // Create a session
    session, err := client.NewSession()
    if err != nil {
        return "", err
    }
    defer session.Close()

    // Collect the command's output
    var b bytes.Buffer
    session.Stdout = &b

    // Execute the command
    err = session.Run(cmd)
    if err != nil {
        return "", err
    }

    return b.String(), nil
}
Copy after login

This function takes the user, address, private key, and command as input and returns the command's output as a string. You can specify the user, address, and private key that grants access to the machine you wish to execute the command on.

The above is the detailed content of How to Execute Commands on Remote Machines with 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