Created
October 14, 2021 19:18
-
-
Save prnvbn/91a7c35ea9a36d06ee5482e45e04c24a to your computer and use it in GitHub Desktop.
run a command on a remote machine via SSH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unc remoteRun(user string, addr string, privateKey string, cmd string) (string, error) { | |
// privateKey could be read from a file, or retrieved from another storage | |
// source, such as the Secret Service / GNOME Keyring | |
key, err := ssh.ParsePrivateKey([]byte(privateKey)) | |
if err != nil { | |
return "", err | |
} | |
// Authentication | |
config := &ssh.ClientConfig{ | |
User: user, | |
// https://github.com/golang/go/issues/19767 | |
// as clientConfig is non-permissive by default | |
// you can set ssh.InsercureIgnoreHostKey to allow any host | |
HostKeyCallback: ssh.InsecureIgnoreHostKey(), | |
Auth: []ssh.AuthMethod{ | |
ssh.PublicKeys(key), | |
}, | |
//alternatively, you could use a password | |
/* | |
Auth: []ssh.AuthMethod{ | |
ssh.Password("PASSWORD"), | |
}, | |
*/ | |
} | |
// Connect | |
client, err := ssh.Dial("tcp", net.JoinHostPort(addr, "22"), config) | |
if err != nil { | |
return "", err | |
} | |
// Create a session. It is one session per command. | |
session, err := client.NewSession() | |
if err != nil { | |
return "", err | |
} | |
defer session.Close() | |
var b bytes.Buffer // import "bytes" | |
session.Stdout = &b // get output | |
// you can also pass what gets input to the stdin, allowing you to pipe | |
// content from client to server | |
// session.Stdin = bytes.NewBufferString("My input") | |
// Finally, run the command | |
err = session.Run(cmd) | |
return b.String(), err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment