-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
79 lines (75 loc) · 1.98 KB
/
utils.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
package main
import (
"bufio"
"github.com/hanjm/errors"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strings"
)
// GetSSHHostList 从 ssh config文件中读取到所有的Host列表
func GetSSHHostList() (hosts []string, err error) {
filePath, err := GetSSHConfigFilePath()
if err != nil {
return hosts, errors.Errorf(err, "")
}
fp, err := os.Open(filePath)
if err != nil {
return hosts, errors.Errorf(err, "failed to open file:%s", filePath)
}
defer fp.Close()
sc := bufio.NewScanner(fp)
sc.Split(bufio.ScanLines)
const hostPrefix = "host"
const hostPrefixLen = len(hostPrefix)
const hostNamePrefix = "hostname"
const hostNamePrefixLen = len(hostNamePrefix)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
lineLen := len(line)
// is host prefix
if lineLen > hostPrefixLen && strings.ToLower(line[:hostPrefixLen]) == hostPrefix {
// not hostname prefix
if lineLen > hostNamePrefixLen && strings.ToLower(line[:hostNamePrefixLen]) == hostNamePrefix {
continue
}
host := strings.TrimSpace(line[hostPrefixLen:])
if host != "" && host != "*" {
hosts = append(hosts, host)
}
}
}
return hosts, nil
}
// GetSSHConfigFile 得到ssh配置文件的路径
func GetSSHConfigFilePath() (filePath string, err error) {
homeDir, err := GetHomeDir()
if err != nil {
return "", errors.Errorf(err, "")
}
filePath = filepath.Join(homeDir, ".ssh", "config")
return filePath, nil
}
// GetHomeDir 得到用户的家目录
func GetHomeDir() (homeDir string, err error) {
u, err := user.Current()
if nil == err {
return u.HomeDir, nil
}
// 环境变量
if v := os.Getenv("HOME"); v != "" {
return v, nil
}
// shell
cmd := exec.Command("sh", "-c", "eval echo ~$USER")
output, err := cmd.Output()
if err != nil {
return "", errors.Errorf(nil, "failed to get home from shell, os:%s", runtime.GOOS)
}
if v := strings.TrimSpace(string(output)); v != "" {
return v, nil
}
return "", errors.Errorf(nil, "failed to get home, os:%s", runtime.GOOS)
}