forked from vmware-archive/cfops
/
remote_execute.go
88 lines (77 loc) · 1.77 KB
/
remote_execute.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
package command
import (
"fmt"
"io"
"golang.org/x/crypto/ssh"
)
// Config for the SSH connection
type SshConfig struct {
Username string
Password string
Host string
Port int
}
type ClientInterface interface {
NewSession() (SSHSession, error)
}
type DefaultRemoteExecutor struct {
Client ClientInterface
}
//Wrapper of ssh client to match client interface signature, since client.NewSession() does not use an interface
type SshClientWrapper struct {
sshclient *ssh.Client
}
func NewClientWrapper(client *ssh.Client) *SshClientWrapper {
return &SshClientWrapper{
sshclient: client,
}
}
func (c *SshClientWrapper) NewSession() (SSHSession, error) {
return c.sshclient.NewSession()
}
// This method creates executor based on ssh, it has concrete ssh reference
func NewRemoteExecutor(sshCfg SshConfig) (executor Executer, err error) {
clientconfig := &ssh.ClientConfig{
User: sshCfg.Username,
Auth: []ssh.AuthMethod{
ssh.Password(sshCfg.Password),
},
}
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", sshCfg.Host, sshCfg.Port), clientconfig)
if err != nil {
return
}
c := NewClientWrapper(client)
executor = &DefaultRemoteExecutor{
Client: c,
}
return
}
type SSHSession interface {
Start(cmd string) error
Wait() error
StdoutPipe() (io.Reader, error)
Close() error
}
// Copy the output from a command to the specified io.Writer
func (executor *DefaultRemoteExecutor) Execute(dest io.Writer, command string) (err error) {
session, err := executor.Client.NewSession()
defer session.Close()
if err != nil {
return
}
stdoutReader, err := session.StdoutPipe()
if err != nil {
return
}
err = session.Start(command)
if err != nil {
return
}
_, err = io.Copy(dest, stdoutReader)
if err != nil {
return
}
err = session.Wait()
return
}