-
Notifications
You must be signed in to change notification settings - Fork 0
/
lister.go
70 lines (58 loc) · 1.18 KB
/
lister.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
package main
import (
"io/ioutil"
"net"
"os"
"strings"
)
type listerFunc func([]string) ([]string, error)
func (lf listerFunc) List(args []string) ([]string, error) {
return lf(args)
}
func init() {
registerLister("khost", listerFunc(listKnownHosts))
}
// retrieve host names from ~/.ssh/known_hosts
func listKnownHosts(noargs []string) ([]string, error) {
f, err := os.Open(expandPath("~/.ssh/known_hosts"))
if err != nil {
return nil, err
}
content, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
var hosts []string
lines := strings.Split(string(content), "\n")
for _, line := range lines {
// ignore comments
if strings.HasPrefix(line, "#") {
continue
}
// ignore empty line
if strings.Trim(line, " ") == "" {
continue
}
// ignore hashed hostname
if strings.HasPrefix(line, "|") {
continue
}
parts := strings.Split(line, " ")
if len(parts) != 3 {
continue
}
hs := strings.Split(parts[0], ",")
for _, h := range hs {
// ignore ip address
if net.ParseIP(h) != nil {
continue
}
// ignore hostname with port
if strings.Contains(h, ":") {
continue
}
hosts = append(hosts, h)
}
}
return hosts, nil
}