@@ -12,6 +12,46 @@ import (
1212 "github.com/kevinburke/ssh_config"
1313)
1414
15+ func hostFromSSHConfig (hostConfig * ssh_config.Host ) (host * Host , err error ) {
16+ host = & Host {Patterns : make ([]string , 0 )}
17+
18+ // patterns
19+ for _ , pattern := range hostConfig .Patterns {
20+ host .Patterns = append (host .Patterns , pattern .String ())
21+ }
22+
23+ // host info
24+ for _ , node := range hostConfig .Nodes {
25+ switch node .(type ) {
26+ case * ssh_config.Empty :
27+ continue
28+ case * ssh_config.KV :
29+ kv := node .(* ssh_config.KV )
30+ switch kv .Key {
31+ case "HostName" :
32+ host .HostName = kv .Value
33+ case "User" :
34+ host .Username = kv .Value
35+ case "Port" :
36+ port , err := strconv .Atoi (kv .Value )
37+ if err != nil {
38+ return nil , err
39+ }
40+ if port <= 0 || port >= 65536 {
41+ return nil , fmt .Errorf ("invalid port: %s" , kv .Value )
42+ }
43+ host .Port = uint16 (port )
44+ case "ProxyJump" :
45+ host .ProxyJump = kv .Value
46+ case "IdentityFile" :
47+ host .IdentityFiles = append (host .IdentityFiles , kv .Value )
48+ }
49+ }
50+ }
51+
52+ return host , nil
53+ }
54+
1555func GetHostsFromSSHConfig () (hosts []* Host , err error ) {
1656 hosts = make ([]* Host , 0 )
1757
@@ -31,40 +71,9 @@ func GetHostsFromSSHConfig() (hosts []*Host, err error) {
3171 }
3272
3373 for _ , hostConfig := range sshConfig .Hosts {
34- host := & Host {Patterns : make ([]string , 0 )}
35-
36- // patterns
37- for _ , pattern := range hostConfig .Patterns {
38- host .Patterns = append (host .Patterns , pattern .String ())
39- }
40-
41- // host info
42- for _ , node := range hostConfig .Nodes {
43- switch node .(type ) {
44- case * ssh_config.Empty :
45- continue
46- case * ssh_config.KV :
47- kv := node .(* ssh_config.KV )
48- switch kv .Key {
49- case "HostName" :
50- host .HostName = kv .Value
51- case "User" :
52- host .Username = kv .Value
53- case "Port" :
54- port , err := strconv .Atoi (kv .Value )
55- if err != nil {
56- return hosts , err
57- }
58- if port <= 0 || port >= 65536 {
59- return hosts , fmt .Errorf ("invalid port: %s" , kv .Value )
60- }
61- host .Port = uint16 (port )
62- case "ProxyJump" :
63- host .ProxyJump = kv .Value
64- case "IdentityFile" :
65- host .IdentityFiles = append (host .IdentityFiles , kv .Value )
66- }
67- }
74+ host , err := hostFromSSHConfig (hostConfig )
75+ if err != nil {
76+ return hosts , err
6877 }
6978
7079 // 没有 HostName 的都是正则类型的配置
@@ -90,7 +99,6 @@ func GetHostsFromSSHConfig() (hosts []*Host, err error) {
9099 }
91100
92101 logger .Debugf ("host: %+#v" , host )
93-
94102 hosts = append (hosts , host )
95103 }
96104
0 commit comments