generated from Scorify/check-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
110 lines (88 loc) · 2.17 KB
/
main.go
File metadata and controls
110 lines (88 loc) · 2.17 KB
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
package ssh
import (
"context"
"fmt"
"strings"
"github.com/scorify/schema"
"golang.org/x/crypto/ssh"
)
type Schema struct {
Server string `key:"server"`
Port int `key:"port" default:"22"`
Username string `key:"username"`
Password string `key:"password"`
Command string `key:"command"`
ExpectedOutput string `key:"expected_output"`
}
func Validate(config string) error {
conf := Schema{}
err := schema.Unmarshal([]byte(config), &conf)
if err != nil {
return err
}
if conf.Server == "" {
return fmt.Errorf("server is required; got %q", conf.Server)
}
if conf.Port <= 0 || conf.Port > 65535 {
return fmt.Errorf("port must be between 1 and 65535; got %d", conf.Port)
}
if conf.Username == "" {
return fmt.Errorf("username is required; got %q", conf.Username)
}
if conf.Password == "" {
return fmt.Errorf("password is required; got %q", conf.Password)
}
if conf.Command == "" {
return fmt.Errorf("command is required; got %q", conf.Command)
}
return nil
}
func Run(ctx context.Context, config string) error {
conf := Schema{}
err := schema.Unmarshal([]byte(config), &conf)
if err != nil {
return err
}
ssh_config := &ssh.ClientConfig{
User: conf.Username,
Auth: []ssh.AuthMethod{
ssh.Password(conf.Password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
target := fmt.Sprintf("%s:%d", conf.Server, conf.Port)
errChan := make(chan error)
go func() {
defer close(errChan)
client, err := ssh.Dial("tcp", target, ssh_config)
if err != nil {
errChan <- err
return
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
errChan <- err
return
}
defer session.Close()
output, err := session.CombinedOutput(conf.Command)
if err != nil {
errChan <- err
return
}
outputString := strings.TrimSpace(string(output))
expectedOutputString := strings.TrimSpace(conf.ExpectedOutput)
if outputString != expectedOutputString {
errChan <- fmt.Errorf("expected output \"%s\" but got \"%s\"", expectedOutputString, outputString)
return
}
errChan <- nil
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errChan:
return err
}
}