-
Notifications
You must be signed in to change notification settings - Fork 6
/
devices.go
85 lines (69 loc) · 1.96 KB
/
devices.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
package main
import (
"os"
"strings"
"github.com/slashdoom/aruba_exporter/config"
"github.com/slashdoom/aruba_exporter/connector"
"github.com/pkg/errors"
)
func devicesForConfig(cfg *config.Config) ([]*connector.Device, error) {
devs := make([]*connector.Device, len(cfg.Devices))
var err error
for i, d := range cfg.Devices {
devs[i], err = deviceFromDeviceConfig(d, cfg)
if err != nil {
return nil, err
}
}
return devs, nil
}
func deviceFromDeviceConfig(device *config.DeviceConfig, cfg *config.Config) (*connector.Device, error) {
auth, err := authForDevice(device, cfg)
if err != nil {
return nil, errors.Wrapf(err, "could not initialize config for device %s", device.Host)
}
port := "22"
host := device.Host
if strings.Contains(host, ":") {
d := strings.Split(host, ":")
host = d[0]
port = d[1]
}
return &connector.Device{
Host: host,
Port: port,
Auth: auth,
DeviceConfig: device,
}, nil
}
func authForDevice(device *config.DeviceConfig, cfg *config.Config) (connector.AuthMethod, error) {
user := cfg.Username
if device.Username != nil {
user = *device.Username
}
if device.KeyFile != nil {
return authForKeyFile(user, *device.KeyFile)
}
if cfg.KeyFile != "" {
return authForKeyFile(user, cfg.KeyFile)
}
if device.Password != nil {
return connector.AuthByPassword(user, *device.Password), nil
}
if cfg.Password != "" {
return connector.AuthByPassword(user, cfg.Password), nil
}
return nil, errors.New("no valid authentication method available")
}
func authForKeyFile(username, keyFile string) (connector.AuthMethod, error) {
f, err := os.Open(keyFile)
if err != nil {
return nil, errors.Wrap(err, "could not open ssh key file")
}
defer f.Close()
auth, err := connector.AuthByKey(username, f)
if err != nil {
return nil, errors.Wrap(err, "could not load ssh private key file")
}
return auth, nil
}