forked from cloudfoundry/bosh-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh_cmd_runner.go
84 lines (72 loc) · 2.02 KB
/
ssh_cmd_runner.go
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package acceptance
import (
"fmt"
"io"
"strings"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
type CmdRunner interface {
RunCommand(env map[string]string, args ...string) (string, string, int, error)
RunStreamingCommand(out io.Writer, env map[string]string, args ...string) (string, string, int, error)
}
type sshCmdRunner struct {
vmUsername string
vmIP string
vmPort string
privateKeyPath string
runner boshsys.CmdRunner
}
func NewSSHCmdRunner(
vmUsername string,
vmIP string,
vmPort string,
privateKeyPath string,
logger boshlog.Logger,
) CmdRunner {
return &sshCmdRunner{
vmUsername: vmUsername,
vmIP: vmIP,
vmPort: vmPort,
privateKeyPath: privateKeyPath,
runner: boshsys.NewExecCmdRunner(logger),
}
}
func (r *sshCmdRunner) RunCommand(env map[string]string, args ...string) (string, string, int, error) {
exports := make([]string, len(env))
for k, v := range env {
exports = append(exports, fmt.Sprintf("%s=%s", k, v))
}
argsWithEnv := append(exports, args...)
return r.runner.RunCommand(
"ssh",
"-o", "StrictHostKeyChecking=no",
"-i", r.privateKeyPath,
"-p", r.vmPort,
fmt.Sprintf("%s@%s", r.vmUsername, r.vmIP),
strings.Join(argsWithEnv, " "),
)
}
func (r *sshCmdRunner) RunStreamingCommand(out io.Writer, env map[string]string, args ...string) (string, string, int, error) {
exports := make([]string, len(env))
for k, v := range env {
exports = append(exports, fmt.Sprintf("%s=%s", k, v))
}
argsWithEnv := append(exports, args...)
cmd := boshsys.Command{
Name: "ssh",
Args: []string{
"-o", "StrictHostKeyChecking=no",
"-i", r.privateKeyPath,
"-p", r.vmPort,
fmt.Sprintf("%s@%s", r.vmUsername, r.vmIP),
strings.Join(argsWithEnv, " "),
},
Stdout: out,
Stderr: out,
}
// write command being run
cmdString := fmt.Sprintf("> %s %s\n", cmd.Name, strings.Join(cmd.Args, " "))
out.Write([]byte(cmdString))
return r.runner.RunComplexCommand(cmd)
}