README.md
1# ssh_config
2
3This is a Go parser for `ssh_config` files. Importantly, this parser attempts
4to preserve comments in a given file, so you can manipulate a `ssh_config` file
5from a program, if your heart desires.
6
7It's designed to be used with the excellent
8[x/crypto/ssh](https://golang.org/x/crypto/ssh) package, which handles SSH
9negotiation but isn't very easy to configure.
10
11The `ssh_config` `Get()` and `GetStrict()` functions will attempt to read values
12from `$HOME/.ssh/config` and fall back to `/etc/ssh/ssh_config`. The first
13argument is the host name to match on, and the second argument is the key you
14want to retrieve.
15
16```go
17port := ssh_config.Get("myhost", "Port")
18```
19
20Certain directives can occur multiple times for a host (such as `IdentityFile`),
21so you should use the `GetAll` or `GetAllStrict` directive to retrieve those
22instead.
23
24```go
25files := ssh_config.GetAll("myhost", "IdentityFile")
26```
27
28You can also load a config file and read values from it.
29
30```go
31var config = `
32Host *.test
33 Compression yes
34`
35
36cfg, err := ssh_config.Decode(strings.NewReader(config))
37fmt.Println(cfg.Get("example.test", "Port"))
38```
39
40Some SSH arguments have default values - for example, the default value for
41`KeyboardAuthentication` is `"yes"`. If you call Get(), and no value for the
42given Host/keyword pair exists in the config, we'll return a default for the
43keyword if one exists.
44
45### Manipulating SSH config files
46
47Here's how you can manipulate an SSH config file, and then write it back to
48disk.
49
50```go
51f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config"))
52cfg, _ := ssh_config.Decode(f)
53for _, host := range cfg.Hosts {
54 fmt.Println("patterns:", host.Patterns)
55 for _, node := range host.Nodes {
56 // Manipulate the nodes as you see fit, or use a type switch to
57 // distinguish between Empty, KV, and Include nodes.
58 fmt.Println(node.String())
59 }
60}
61
62// Print the config to stdout:
63fmt.Println(cfg.String())
64```
65
66## Spec compliance
67
68Wherever possible we try to implement the specification as documented in
69the `ssh_config` manpage. Unimplemented features should be present in the
70[issues][issues] list.
71
72Notably, the `Match` directive is currently unsupported.
73
74[issues]: https://github.com/kevinburke/ssh_config/issues
75
76## Errata
77
78This is the second [comment-preserving configuration parser][blog] I've written, after
79[an /etc/hosts parser][hostsfile]. Eventually, I will write one for every Linux
80file format.
81
82[blog]: https://kev.inburke.com/kevin/more-comment-preserving-configuration-parsers/
83[hostsfile]: https://github.com/kevinburke/hostsfile
84
85## Donating
86
87Donations free up time to make improvements to the library, and respond to
88bug reports. You can send donations via Paypal's "Send Money" feature to
89kev@inburke.com. Donations are not tax deductible in the USA.
90