-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelper.go
More file actions
104 lines (92 loc) · 2.08 KB
/
Copy pathhelper.go
File metadata and controls
104 lines (92 loc) · 2.08 KB
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
package main
import (
"bufio"
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
)
type SSHConfig struct {
Host string
Hostname string
User string
Port string
Identity string
}
func GetDefaultSSHConfigPath() string {
usr, err := user.Current()
if err != nil {
return ""
}
return filepath.Join(usr.HomeDir, ".ssh", "config")
}
func ParseSSHConfig(path string) ([]SSHConfig, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var configs []SSHConfig
var currentConfig *SSHConfig
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.Fields(line)
if len(parts) >= 2 {
key := strings.ToLower(parts[0])
value := strings.Join(parts[1:], " ")
if key == "host" {
if currentConfig != nil {
configs = append(configs, *currentConfig)
}
currentConfig = &SSHConfig{Host: value}
} else if currentConfig != nil {
switch key {
case "hostname":
currentConfig.Hostname = value
case "user":
currentConfig.User = value
case "port":
currentConfig.Port = value
case "identityfile":
currentConfig.Identity = value
}
}
}
}
if currentConfig != nil {
configs = append(configs, *currentConfig)
}
return configs, scanner.Err()
}
func WriteSSHConfig(path string, configs []SSHConfig) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
for i, cfg := range configs {
writer.WriteString(fmt.Sprintf("Host %s\n", cfg.Host))
if cfg.Hostname != "" {
writer.WriteString(fmt.Sprintf(" HostName %s\n", cfg.Hostname))
}
if cfg.User != "" {
writer.WriteString(fmt.Sprintf(" User %s\n", cfg.User))
}
if cfg.Port != "" {
writer.WriteString(fmt.Sprintf(" Port %s\n", cfg.Port))
}
if cfg.Identity != "" {
writer.WriteString(fmt.Sprintf(" IdentityFile %s\n", cfg.Identity))
}
if i < len(configs)-1 {
writer.WriteString("\n")
}
}
return writer.Flush()
}