-
Notifications
You must be signed in to change notification settings - Fork 3
/
ssh_proc.go
112 lines (94 loc) · 2.37 KB
/
ssh_proc.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
109
110
111
112
package gossh
import (
"fmt"
"io/ioutil"
"os/exec"
"syscall"
"time"
)
func newSshProcessTask(host string, cmd string, opt Options) func() (interface{}, error) {
state := &sshProcessTask{
Host: host,
Cmd: cmd,
Options: opt,
}
return state.run
}
// this file is for SshTask that calls the local ssh shell command.
type sshProcessTask struct {
Host string
Cmd string
Options Options
}
func (s *sshProcessTask) run() (interface{}, error) {
start := time.Now()
// must return of type (SshResponseContext, error)
//cmd := exec.Command("/usr/bin/ssh", s.Host, s.Cmd)
cmd := exec.Command("ssh", s.generateCmdArguments()...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
ctx := createContext(s.Host)
// if this is after wait, it seems that the stream is closed
// so no longer readable
out, _ := ioutil.ReadAll(stdout)
ctx.Response.Stdout = string(out)
outerr, _ := ioutil.ReadAll(stderr)
ctx.Response.Stderr = string(outerr)
err = cmd.Wait()
exitCode, err := exitCode(err)
total := time.Now().Sub(start)
ctx.Duration = fmt.Sprintf("%dms", total/time.Millisecond)
if err != nil {
// run on non supported OS
return ctx, err
}
ctx.Response.Code = exitCode
return ctx, nil
}
func (s *sshProcessTask) generateCmdArguments() []string {
// make a slice of init size 4, but can expand to 100
cmd := make([]string, 0)
cmd = append(cmd, "-n")
// add user/identity
if s.Options.User != "" {
cmd = append(cmd, "-l", s.Options.User)
}
if s.Options.Identity != "" {
cmd = append(cmd, "-i", s.Options.Identity)
}
// add options
for key, value := range s.Options.Options {
cmd = append(cmd, "-o", key+"="+value)
}
// add host
cmd = append(cmd, s.Host)
// last action, add cmd
cmd = append(cmd, s.Cmd)
return cmd
}
func exitCode(err error) (int, error) {
if err != nil {
// it puts exit code in err... grrr
exitErr, ok := err.(*exec.ExitError)
if ok {
sys := exitErr.Sys()
// this is system dependent. This is the unix way
waitStatus, ok := sys.(syscall.WaitStatus)
if ok {
return waitStatus.ExitStatus(), nil
}
}
return -1, fmt.Errorf("Unsupported OS; expected syscall status to be on a unix environment", err)
}
// was successful, so exit code is 0
return 0, nil
}