-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
103 lines (77 loc) · 1.74 KB
/
session.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
package sshexec
import (
"bytes"
"io/ioutil"
"os"
"strconv"
"time"
"github.com/satori/go.uuid"
"golang.org/x/crypto/ssh"
)
// ssh session
type HostSession struct {
Username string
Password string
Hostname string
Signers []ssh.Signer
Port int
}
// result of the command execution
type ExecResult struct {
Id uuid.UUID
Host string
Command string
Result bytes.Buffer
StartTime time.Time
EndTime time.Time
}
// execute the command and return a result structure
func (exec *HostSession) Exec(id uuid.UUID, command string, config ssh.ClientConfig) (*ExecResult, error) {
client, err := ssh.Dial("tcp", exec.Hostname+":"+strconv.Itoa(exec.Port), &config)
if err != nil {
return nil, err
}
session, err := client.NewSession()
if err != nil {
return nil, err
}
defer session.Close()
var b bytes.Buffer
session.Stdout = &b
start := time.Now()
if err := session.Run(command); err != nil {
return nil, err
}
end := time.Now()
result := &ExecResult{
Id: id,
Host: exec.Hostname,
Command: command,
Result: b,
StartTime: start,
EndTime: end,
}
return result, nil
}
func (exec *HostSession) GenerateConfig() ssh.ClientConfig {
var auths []ssh.AuthMethod
if len(exec.Password) != 0 {
auths = append(auths, ssh.Password(exec.Password))
} else {
auths = append(auths, ssh.PublicKeys(exec.Signers...))
}
config := ssh.ClientConfig{
User: exec.Username,
Auth: auths,
}
config.Ciphers = []string{"aes128-cbc", "3des-cbc"}
return config
}
func readKey(filename string) (ssh.Signer, error) {
f, _ := os.Open(filename)
bytes, _ := ioutil.ReadAll(f)
return generateKey(bytes)
}
func generateKey(keyData []byte) (ssh.Signer, error) {
return ssh.ParsePrivateKey(keyData)
}