forked from stevensu1977/commandcast
/
hostconfig.go
61 lines (52 loc) · 1.1 KB
/
hostconfig.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
package main
import (
"bytes"
"golang.org/x/crypto/ssh"
"strings"
)
// Host configure
type HostConfig struct {
Host string
User string
Timeout int
ClientConfig *ssh.ClientConfig
Session *ssh.Session
}
// Start SSH session
func (this *HostConfig) StartSession() (*ssh.Session, error) {
host := this.Host
if !strings.ContainsAny(this.Host, ":") {
host = host + ":22"
}
conn, err := ssh.Dial("tcp", host, this.ClientConfig)
if err != nil {
return nil, err
}
this.Session, err = conn.NewSession()
if err != nil {
return nil, err
}
return this.Session, err
}
// Stop SSH session
func (this *HostConfig) StopSession() {
if this.Session != nil {
this.Session.Close()
}
}
// Execute command
func (this *HostConfig) ExecuteCmd(cmd string) (string, error) {
if this.Session == nil {
if _, err := this.StartSession(); err != nil {
return "", err
}
}
var stdoutBuf bytes.Buffer
this.Session.Stdout = &stdoutBuf
this.Session.Run(cmd)
return stdoutBuf.String(), nil
}
// To string
func (this HostConfig) String() string {
return this.User + "@" + this.Host
}