-
Notifications
You must be signed in to change notification settings - Fork 162
/
instance_ssh.go
108 lines (94 loc) · 2.5 KB
/
instance_ssh.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package acceptance
import (
"fmt"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
type InstanceSSH interface {
RunCommand(cmd string) (stdout, stderr string, exitCode int, err error)
RunCommandWithSudo(cmd string) (stdout, stderr string, exitCode int, err error)
}
type instanceSSH struct {
instanceUsername string
instanceIP string
instancePassword string
runner boshsys.CmdRunner
fileSystem boshsys.FileSystem
}
func NewInstanceSSH(
instanceUsername string,
instanceIP string,
instancePassword string,
fileSystem boshsys.FileSystem,
logger boshlog.Logger,
) InstanceSSH {
return &instanceSSH{
instanceUsername: instanceUsername,
instanceIP: instanceIP,
instancePassword: instancePassword,
runner: boshsys.NewExecCmdRunner(logger),
fileSystem: fileSystem,
}
}
func (s *instanceSSH) setupSSH() (boshsys.File, error) {
sshConfigFile, err := s.fileSystem.TempFile("ssh-config")
if err != nil {
return nil, bosherr.WrapError(err, "Creating temp ssh-config file")
}
success := false
defer func() {
if !success {
_ = s.fileSystem.RemoveAll(sshConfigFile.Name())
}
}()
sshConfigTemplate := `
Host warden-vm
Hostname %s
User %s
StrictHostKeyChecking no
`
sshConfig := fmt.Sprintf(
sshConfigTemplate,
s.instanceIP,
s.instanceUsername,
)
err = s.fileSystem.WriteFileString(sshConfigFile.Name(), sshConfig)
if err != nil {
return nil, bosherr.WrapErrorf(err, "Writing to temp ssh-config file: '%s'", sshConfigFile.Name())
}
success = true
return sshConfigFile, nil
}
func (s *instanceSSH) RunCommand(cmd string) (stdout, stderr string, exitCode int, err error) {
sshConfigFile, err := s.setupSSH()
if err != nil {
return "", "", -1, bosherr.WrapError(err, "Setting up SSH")
}
defer s.fileSystem.RemoveAll(sshConfigFile.Name())
return s.runner.RunCommand(
"sshpass",
"-p"+s.instancePassword,
"ssh",
"warden-vm",
"-F",
sshConfigFile.Name(),
cmd,
)
}
func (s *instanceSSH) RunCommandWithSudo(cmd string) (stdout, stderr string, exitCode int, err error) {
sshConfigFile, err := s.setupSSH()
if err != nil {
return "", "", -1, bosherr.WrapError(err, "Setting up SSH")
}
defer s.fileSystem.RemoveAll(sshConfigFile.Name())
return s.runner.RunCommand(
"sshpass",
"-p"+s.instancePassword,
"ssh",
"warden-vm",
"-F",
sshConfigFile.Name(),
fmt.Sprintf("echo %s | sudo -p '' -S %s", s.instancePassword, cmd),
)
}