forked from mackerelio/go-check-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-ssh.go
185 lines (164 loc) · 4.86 KB
/
check-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
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
176
177
178
179
180
181
182
183
184
185
package checkssh
import (
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"strconv"
"time"
"github.com/jessevdk/go-flags"
"github.com/mackerelio/checkers"
"golang.org/x/crypto/ssh"
)
type sshOpts struct {
Hostname string `short:"H" long:"hostname" default:"localhost" description:"Host name or IP Address"`
Port int `short:"P" long:"port" default:"22" description:"Port number"`
Timeout float64 `short:"t" long:"timeout" default:"30" description:"Seconds before connection times out"`
Warning float64 `short:"w" long:"warning" description:"Response time to result in warning status (seconds)"`
Critical float64 `short:"c" long:"critical" description:"Response time to result in critical status (seconds)"`
User string `short:"u" long:"user" description:"Login user name" env:"USER"`
Password string `short:"p" long:"password" description:"Login password"`
IdentityFile string `short:"i" long:"identity" description:"Identity file (ssh private key)"`
PassPhrase string `long:"passphrase" description:"Identity passphrase" env:"CHECK_SSH_IDENTITY_PASSPHRASE"`
}
// Do the plugin
func Do() {
opts, err := parseArgs(os.Args[1:])
if err != nil {
os.Exit(1)
}
if opts.Critical > opts.Timeout {
// force timeout
opts.Timeout = opts.Critical
}
ckr := opts.run()
ckr.Name = "SSH"
ckr.Exit()
}
func parseArgs(args []string) (*sshOpts, error) {
opts := &sshOpts{}
_, err := flags.ParseArgs(opts, args)
return opts, err
}
func decrypt(block *pem.Block, passphrase string) (*pem.Block, error) {
data, err := x509.DecryptPEMBlock(block, []byte(passphrase))
if err != nil {
return nil, err
}
decryptedBlock := &pem.Block{
Type: block.Type,
Bytes: data,
}
return decryptedBlock, nil
}
func readPrivateKey(file, passphrase string) ([]byte, error) {
privateKey, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
block, rest := pem.Decode(privateKey)
if len(rest) > 0 {
return nil, errors.New("Invalid private key")
}
if !x509.IsEncryptedPEMBlock(block) {
return privateKey, nil
}
block, err = decrypt(block, passphrase)
if err != nil {
return nil, err
}
privateKey = pem.EncodeToMemory(block)
return privateKey, nil
}
func (opts *sshOpts) makeClientConfig() (*ssh.ClientConfig, error) {
authenticities := make([]ssh.AuthMethod, 0, 1)
if opts.Password != "" {
authenticities = append(authenticities, ssh.Password(opts.Password))
}
if opts.IdentityFile != "" {
data, err := readPrivateKey(opts.IdentityFile, opts.PassPhrase)
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(data)
if err != nil {
return nil, err
}
authenticities = append(authenticities, ssh.PublicKeys(signer))
}
config := &ssh.ClientConfig{User: opts.User, Auth: authenticities}
return config, nil
}
func (opts *sshOpts) dial(config *ssh.ClientConfig) (*ssh.Client, error) {
addr := opts.Hostname + ":" + strconv.Itoa(opts.Port)
timeout := opts.Timeout * float64(time.Second)
conn, err := net.DialTimeout("tcp", addr, time.Duration(timeout))
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}
func (opts *sshOpts) run() *checkers.Checker {
// prevent changing output of some commands
os.Setenv("LANG", "C")
os.Setenv("LC_ALL", "C")
config, err := opts.makeClientConfig()
if err != nil {
return checkers.Unknown(err.Error())
}
start := time.Now()
client, err := opts.dial(config)
if err != nil {
if addrerr, ok := err.(*net.AddrError); ok {
if addrerr.Timeout() {
elapsed := time.Now().Sub(start)
return opts.checkTimeoutError(elapsed, err)
} else if addrerr.Temporary() {
return checkers.Warning(err.Error())
}
}
return checkers.Critical(err.Error())
}
session, err := client.NewSession()
if err != nil {
return checkers.Critical(err.Error())
}
err = session.Close()
if err != nil {
return checkers.Unknown(err.Error())
}
elapsed := time.Now().Sub(start)
return opts.checkTimeout(elapsed)
}
func (opts *sshOpts) checkTimeoutError(elapsed time.Duration, err error) *checkers.Checker {
checker := opts.checkTimeout(elapsed)
if checker.Status == checkers.OK {
checker.Status = checkers.WARNING
}
checker.Message = err.Error()
return checker
}
func (opts *sshOpts) checkTimeout(elapsed time.Duration) *checkers.Checker {
chkSt := checkers.OK
if opts.Warning > 0 && elapsed > time.Duration(opts.Warning)*time.Second {
chkSt = checkers.WARNING
}
if opts.Critical > 0 && elapsed > time.Duration(opts.Critical)*time.Second {
chkSt = checkers.CRITICAL
}
msg := fmt.Sprintf("%.3f seconds response time on", float64(elapsed)/float64(time.Second))
if opts.Hostname != "" {
msg += " " + opts.Hostname
}
if opts.Port > 0 {
msg += fmt.Sprintf(" port %d", opts.Port)
}
return checkers.NewChecker(chkSt, msg)
}