summaryrefslogtreecommitdiff
path: root/cmd/podman/system/connection/shared.go
blob: 3fd7c59fbe121b1f526f26b7d471e2f6e894e3a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package connection

import (
	"bytes"

	"github.com/pkg/errors"
	"golang.org/x/crypto/ssh"
)

// ExecRemoteCommand takes a ssh client connection and a command to run and executes the
// command on the specified client. The function returns the Stdout from the client or the Stderr
func ExecRemoteCommand(dial *ssh.Client, run string) (string, error) {
	sess, err := dial.NewSession() // new ssh client session
	if err != nil {
		return "", err
	}
	defer sess.Close()

	var buffer bytes.Buffer
	var bufferErr bytes.Buffer
	sess.Stdout = &buffer                 // output from client funneled into buffer
	sess.Stderr = &bufferErr              // err form client funneled into buffer
	if err := sess.Run(run); err != nil { // run the command on the ssh client
		return "", errors.Wrapf(err, bufferErr.String())
	}
	out := buffer.String() // output from command
	return out, nil
}