-
Notifications
You must be signed in to change notification settings - Fork 10
/
ssh.go
88 lines (80 loc) · 1.88 KB
/
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
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"golang.org/x/crypto/ssh"
)
type (
grapeSSH struct {
keySigner ssh.Signer
}
grapeSSHClient struct {
*ssh.Client
}
std struct {
Out string
Err string
}
sshOutput struct {
Command command
Std std
}
sshOutputArray []*sshOutput
sshError error
)
func (gSSH *grapeSSH) newError(errMsg string) sshError {
return errors.New(errMsg)
}
func (gSSH *grapeSSH) setKey(keyPath keyPath) sshError {
privateBytes, err := ioutil.ReadFile(string(keyPath))
if err != nil {
return gSSH.newError("Could not open identity file.")
}
privateKey, err := ssh.ParsePrivateKey(privateBytes)
if err != nil {
return gSSH.newError(fmt.Sprint("Could not parse identity file."))
}
gSSH.keySigner = privateKey
return nil
}
func (gSSH *grapeSSH) newClient(server server, hostKeyCallback ssh.HostKeyCallback) (*grapeSSHClient, sshError) {
client, err := ssh.Dial("tcp", server.Host, &ssh.ClientConfig{
User: server.User,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(gSSH.keySigner),
},
HostKeyCallback: hostKeyCallback,
})
if err != nil {
return nil, gSSH.newError(err.Error() + " - could not establish ssh connection")
}
return &grapeSSHClient{client}, nil
}
func (client *grapeSSHClient) execCommand(cmd command) *sshOutput {
output := &sshOutput{
Command: cmd,
}
session, err := client.NewSession()
if err != nil {
output.Std.Err = "could not establish ssh session"
} else {
var stderr, stdout bytes.Buffer
session.Stdout, session.Stderr = &stdout, &stderr
session.Run(string(cmd))
session.Close()
output.Std = std{
Out: stdout.String(),
Err: stderr.String(),
}
}
return output
}
func (client *grapeSSHClient) execCommands(commands commands) sshOutputArray {
output := sshOutputArray{}
for _, command := range commands {
output = append(output, client.execCommand(command))
}
return output
}