Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang: Execute shell commands on remote server

I have 50 something Linux machines (RHEL). I want to run some commands on these machines from a go script running on a central machine. I have setup password-less ssh authentication to all of them from the central machine to all the remote machines. Though I'm open to non-ssh solutions too, though something secure is preferred.

The commands being run would change over time. I would also want to process the output and return codes of commands being run on the remote machines in my script running on central machine.

I only found this ssh package, which supports only password authentication method, which is not good enough.

Any other options?

like image 504
Kashyap Avatar asked Feb 06 '26 01:02

Kashyap


2 Answers

You just can use this package https://github.com/hypersleep/easyssh

For example you can call ps ax remotely:

package main

import (
    "fmt"
    "github.com/hypersleep/easyssh"    
)

func main() {
    ssh := &easyssh.MakeConfig {
        User: "core",
        Server: "core",
        Key: "/.ssh/id_rsa",
        Port: "22",
    }

    response, err := ssh.Run("ps ax")
    if err != nil {
        panic("Can't run remote command: " + err.Error())
    } else {
        fmt.Println(response)
    }
}
like image 96
Vladis Spirenskas Avatar answered Feb 07 '26 13:02

Vladis Spirenskas


You can use public keys with the go.crypto/ssh package using PublicKeys.

There's a detailed example in the repo around line 114.

Another example using ssh agent @ https://github.com/davecheney/socksie/blob/master/main.go.

like image 22
OneOfOne Avatar answered Feb 07 '26 13:02

OneOfOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!