forked from ericmaryea/cisco_exporter
/
connection.go
175 lines (150 loc) · 3.57 KB
/
connection.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package connector
import (
"bufio"
"errors"
"io"
"io/ioutil"
"regexp"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh"
)
var (
cachedConfig *ssh.ClientConfig
lock = &sync.Mutex{}
)
func config(user, password string, legacyCiphers bool, timeout int) (*ssh.ClientConfig, error) {
lock.Lock()
defer lock.Unlock()
if cachedConfig != nil {
return cachedConfig, nil
}
bufpassword, err := ioutil.ReadFile("/etc/prometheus/ciscoexporter_secrets")
if err != nil {
return nil, err
}
password = string (bufpassword)
cachedConfig = &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(password),},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: time.Duration(timeout) * time.Second,
}
if legacyCiphers {
cachedConfig.SetDefaults()
cachedConfig.Ciphers = append(cachedConfig.Ciphers, "aes128-cbc", "3des-cbc")
}
return cachedConfig, nil
}
// NewSSSHConnection connects to device
func NewSSSHConnection(host, user, password string, legacyCiphers bool, timeout int, batchSize int) (*SSHConnection, error) {
if !strings.Contains(host, ":") {
host = host + ":22"
}
c := &SSHConnection{
Host: host,
legacyCiphers: legacyCiphers,
batchSize: batchSize,
}
err := c.Connect(user, password, timeout)
if err != nil {
return nil, err
}
return c, nil
}
// SSHConnection encapsulates the connection to the device
type SSHConnection struct {
client *ssh.Client
Host string
stdin io.WriteCloser
stdout io.Reader
session *ssh.Session
legacyCiphers bool
batchSize int
}
// Connect connects to the device
func (c *SSHConnection) Connect(user, password string, timeout int) error {
config, err := config(user, password, c.legacyCiphers, timeout)
if err != nil {
return err
}
c.client, err = ssh.Dial("tcp", c.Host, config)
if err != nil {
return err
}
session, err := c.client.NewSession()
if err != nil {
c.client.Conn.Close()
return err
}
c.stdin, _ = session.StdinPipe()
c.stdout, _ = session.StdoutPipe()
modes := ssh.TerminalModes{
ssh.ECHO: 0,
ssh.OCRNL: 0,
}
session.RequestPty("vt100", 0, 2000, modes)
session.Shell()
c.session = session
c.RunCommand("")
c.RunCommand("terminal length 0")
return nil
}
type result struct {
output string
err error
}
// RunCommand runs a command against the device
func (c *SSHConnection) RunCommand(cmd string) (string, error) {
buf := bufio.NewReader(c.stdout)
io.WriteString(c.stdin, cmd+"\n")
outputChan := make(chan result)
go func() {
c.readln(outputChan, cmd, buf)
}()
select {
case res := <-outputChan:
return res.output, res.err
case <-time.After(cachedConfig.Timeout):
return "", errors.New("Timeout reached")
}
}
// Close closes connection
func (c *SSHConnection) Close() {
if c.client.Conn == nil {
return
}
c.client.Conn.Close()
if c.session != nil {
c.session.Close()
}
}
func loadPublicKeyFile(file string) (ssh.AuthMethod, error) {
b, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
key, err := ssh.ParsePrivateKey(b)
if err != nil {
return nil, err
}
return ssh.PublicKeys(key), nil
}
func (c *SSHConnection) readln(ch chan result, cmd string, r io.Reader) {
re := regexp.MustCompile(`.+#\s?$`)
buf := make([]byte, c.batchSize)
loadStr := ""
for {
n, err := r.Read(buf)
if err != nil {
ch <- result{output: "", err: err}
}
loadStr += string(buf[:n])
if strings.Contains(loadStr, cmd) && re.MatchString(loadStr) {
break
}
}
loadStr = strings.Replace(loadStr, "\r", "", -1)
ch <- result{output: loadStr, err: nil}
}