forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh_config.go
71 lines (59 loc) · 1.19 KB
/
ssh_config.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
package git
import (
"bufio"
"os"
"path/filepath"
"regexp"
"strings"
)
const (
hostReStr = "(?i)^[ \t]*(host|hostname)[ \t]+(.+)$"
)
type SSHConfig map[string]string
func newSSHConfigReader() *SSHConfigReader {
return &SSHConfigReader{
Files: []string{
filepath.Join(os.Getenv("HOME"), ".ssh/config"),
"/etc/ssh_config",
"/etc/ssh/ssh_config",
},
}
}
type SSHConfigReader struct {
Files []string
}
func (r *SSHConfigReader) Read() SSHConfig {
config := make(SSHConfig)
hostRe := regexp.MustCompile(hostReStr)
for _, filename := range r.Files {
r.readFile(config, hostRe, filename)
}
return config
}
func (r *SSHConfigReader) readFile(c SSHConfig, re *regexp.Regexp, f string) error {
file, err := os.Open(f)
if err != nil {
return err
}
defer file.Close()
hosts := []string{"*"}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
match := re.FindStringSubmatch(line)
if match == nil {
continue
}
names := strings.Fields(match[2])
if strings.EqualFold(match[1], "host") {
hosts = names
} else {
for _, host := range hosts {
for _, name := range names {
c[host] = name
}
}
}
}
return scanner.Err()
}