Package ssh_config provides tools for manipulating SSH config files. Importantly, this parser attempts to preserve comments in a given file, so you can manipulate a `ssh_config` file from a program, if your heart desires. The Get() and GetStrict() functions will attempt to read values from $HOME/.ssh/config, falling back to /etc/ssh/ssh_config. The first argument is the host name to match on ("example.com"), and the second argument is the key you want to retrieve ("Port"). The keywords are case insensitive. port := ssh_config.Get("myhost", "Port") You can also manipulate an SSH config file and then print it or write it back to disk. f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config")) cfg, _ := ssh_config.Decode(f) for _, host := range cfg.Hosts { fmt.Println("patterns:", host.Patterns) for _, node := range host.Nodes { fmt.Println(node.String()) } } // Write the cfg back to disk: fmt.Println(cfg.String()) BUG: the Match directive is currently unsupported; parsing a config with a Match directive will trigger an error.
package ssh_config

import (
	
	
	
	
	
	
	osuser 
	
	
	
	
	
)

const version = "1.0"

var _ = version

type configFinder func() string
UserSettings checks ~/.ssh and /etc/ssh for configuration files. The config files are parsed and cached the first time Get() or GetStrict() is called.
type UserSettings struct {
	IgnoreErrors       bool
	systemConfig       *Config
	systemConfigFinder configFinder
	userConfig         *Config
	userConfigFinder   configFinder
	loadConfigs        sync.Once
	onceErr            error
}

func () string {
	,  := osuser.Current()
	if  == nil {
		return .HomeDir
	} else {
		return os.Getenv("HOME")
	}
}

func () string {
	return filepath.Join(homedir(), ".ssh", "config")
}
DefaultUserSettings is the default UserSettings and is used by Get and GetStrict. It checks both $HOME/.ssh/config and /etc/ssh/ssh_config for keys, and it will return parse errors (if any) instead of swallowing them.
var DefaultUserSettings = &UserSettings{
	IgnoreErrors:       false,
	systemConfigFinder: systemConfigFinder,
	userConfigFinder:   userConfigFinder,
}

func () string {
	return filepath.Join("/", "etc", "ssh", "ssh_config")
}

func ( *Config, ,  string) (string, error) {
	if  == nil {
		return "", nil
	}
	,  := .Get(, )
	if  != nil ||  == "" {
		return "", 
	}
	if  := validate(, );  != nil {
		return "", 
	}
	return , nil
}
Get finds the first value for key within a declaration that matches the alias. Get returns the empty string if no value was found, or if IgnoreErrors is false and we could not parse the configuration file. Use GetStrict to disambiguate the latter cases. The match for key is case insensitive. Get is a wrapper around DefaultUserSettings.Get.
func (,  string) string {
	return DefaultUserSettings.Get(, )
}
GetStrict finds the first value for key within a declaration that matches the alias. If key has a default value and no matching configuration is found, the default will be returned. For more information on default values and the way patterns are matched, see the manpage for ssh_config. error will be non-nil if and only if a user's configuration file or the system configuration file could not be parsed, and u.IgnoreErrors is false. GetStrict is a wrapper around DefaultUserSettings.GetStrict.
func (,  string) (string, error) {
	return DefaultUserSettings.GetStrict(, )
}
Get finds the first value for key within a declaration that matches the alias. Get returns the empty string if no value was found, or if IgnoreErrors is false and we could not parse the configuration file. Use GetStrict to disambiguate the latter cases. The match for key is case insensitive.
func ( *UserSettings) (,  string) string {
	,  := .GetStrict(, )
	if  != nil {
		return ""
	}
	return 
}
GetStrict finds the first value for key within a declaration that matches the alias. If key has a default value and no matching configuration is found, the default will be returned. For more information on default values and the way patterns are matched, see the manpage for ssh_config. error will be non-nil if and only if a user's configuration file or the system configuration file could not be parsed, and u.IgnoreErrors is false.
func ( *UserSettings) (,  string) (string, error) {
can't parse user file, that's ok.
		var  string
		if .userConfigFinder == nil {
			 = userConfigFinder()
		} else {
			 = .userConfigFinder()
		}
		var  error
lint:ignore S1002 I prefer it this way
		if  != nil && os.IsNotExist() == false {
			.onceErr = 
			return
		}
		if .systemConfigFinder == nil {
			 = systemConfigFinder()
		} else {
			 = .systemConfigFinder()
		}
lint:ignore S1002 I prefer it this way
		if  != nil && os.IsNotExist() == false {
			.onceErr = 
			return
		}
lint:ignore S1002 I prefer it this way
	if .onceErr != nil && .IgnoreErrors == false {
		return "", .onceErr
	}
	,  := findVal(.userConfig, , )
	if  != nil ||  != "" {
		return , 
	}
	,  := findVal(.systemConfig, , )
	if  != nil ||  != "" {
		return , 
	}
	return Default(), nil
}

func ( string) (*Config, error) {
	return parseWithDepth(, 0)
}

func ( string,  uint8) (*Config, error) {
	,  := ioutil.ReadFile()
	if  != nil {
		return nil, 
	}
	return decodeBytes(, isSystem(), )
}

TODO: not sure this is the best way to detect a system repo
	return strings.HasPrefix(filepath.Clean(), "/etc/ssh")
}
Decode reads r into a Config, or returns an error if r could not be parsed as an SSH config file.
func ( io.Reader) (*Config, error) {
	,  := ioutil.ReadAll()
	if  != nil {
		return nil, 
	}
	return decodeBytes(, false, 0)
}

func ( []byte,  bool,  uint8) ( *Config,  error) {
	defer func() {
		if  := recover();  != nil {
			if ,  := .(runtime.Error);  {
				panic()
			}
			if ,  := .(error);  &&  == ErrDepthExceeded {
				 = 
				return
			}
			 = errors.New(.(string))
		}
	}()

	 = parseSSH(lexSSH(), , )
	return , 
}
Config represents an SSH config file.
A list of hosts to match against. The file begins with an implicit "Host *" declaration matching all hosts.
Get finds the first value in the configuration that matches the alias and contains key. Get returns the empty string if no value was found, or if the Config contains an invalid conditional Include value. The match for key is case insensitive.
func ( *Config) (,  string) (string, error) {
	 := strings.ToLower()
	for ,  := range .Hosts {
		if !.Matches() {
			continue
		}
		for ,  := range .Nodes {
			switch t := .(type) {
			case *Empty:
				continue
"keys are case insensitive" per the spec
				 := strings.ToLower(.Key)
				if  == "match" {
					panic("can't handle Match directives")
				}
				if  ==  {
					return .Value, nil
				}
			case *Include:
				 := .Get(, )
				if  != "" {
					return , nil
				}
			default:
				return "", fmt.Errorf("unknown Node type %v", )
			}
		}
	}
	return "", nil
}
String returns a string representation of the Config file.
func ( Config) () string {
	return marshal().String()
}

func ( Config) () ([]byte, error) {
	return marshal().Bytes(), nil
}

func ( Config) *bytes.Buffer {
	var  bytes.Buffer
	for  := range .Hosts {
		.WriteString(.Hosts[].String())
	}
	return &
}
Pattern is a pattern in a Host declaration. Patterns are read-only values; create a new one with NewPattern().
type Pattern struct {
	str   string // Its appearance in the file, not the value that gets compiled.
	regex *regexp.Regexp
	not   bool // True if this is a negated match
}
String prints the string representation of the pattern.
func ( Pattern) () string {
	return .str
}
Copied from regexp.go with * and ? removed.
var specialBytes = []byte(`\.+()|[]{}^$`)

func ( byte) bool {
	return bytes.IndexByte(specialBytes, ) >= 0
}
NewPattern creates a new Pattern for matching hosts. NewPattern("*") creates a Pattern that matches all hosts. From the manpage, a pattern consists of zero or more non-whitespace characters, `*' (a wildcard that matches zero or more characters), or `?' (a wildcard that matches exactly one character). For example, to specify a set of declarations for any host in the ".co.uk" set of domains, the following pattern could be used: Host *.co.uk The following pattern would match any host in the 192.168.0.[0-9] network range: Host 192.168.0.?
func ( string) (*Pattern, error) {
	if  == "" {
		return nil, errors.New("ssh_config: empty pattern")
	}
	 := false
	if [0] == '!' {
		 = true
		 = [1:]
	}
	var  bytes.Buffer
	.WriteByte('^')
A byte loop is correct because all metacharacters are ASCII.
		switch  := [];  {
		case '*':
			.WriteString(".*")
		case '?':
			.WriteString(".?")
borrowing from QuoteMeta here.
			if special() {
				.WriteByte('\\')
			}
			.WriteByte()
		}
	}
	.WriteByte('$')
	,  := regexp.Compile(.String())
	if  != nil {
		return nil, 
	}
	return &Pattern{str: , regex: , not: }, nil
}
Host describes a Host directive and the keywords that follow it.
A list of host patterns that should match this host.
A Node is either a key/value pair or a comment line.
EOLComment is the comment (if any) terminating the Host line.
The file starts with an implicit "Host *" declaration.
Matches returns true if the Host matches for the given alias. For a description of the rules that provide a match, see the manpage for ssh_config.
func ( *Host) ( string) bool {
	 := false
	for  := range .Patterns {
		if .Patterns[].regex.MatchString() {
Negated match. "A pattern entry may be negated by prefixing it with an exclamation mark (`!'). If a negated entry is matched, then the Host entry is ignored, regardless of whether any other patterns on the line match. Negated matches are therefore useful to provide exceptions for wildcard matches."
				return false
			}
			 = true
		}
	}
	return 
}
String prints h as it would appear in a config file. Minor tweaks may be present in the whitespace in the printed file.
func ( *Host) () string {
lint:ignore S1002 I prefer to write it this way
	if .implicit == false {
		.WriteString(strings.Repeat(" ", int(.leadingSpace)))
		.WriteString("Host")
		if .hasEquals {
			.WriteString(" = ")
		} else {
			.WriteString(" ")
		}
		for ,  := range .Patterns {
			.WriteString(.String())
			if  < len(.Patterns)-1 {
				.WriteString(" ")
			}
		}
		if .EOLComment != "" {
			.WriteString(" #")
			.WriteString(.EOLComment)
		}
		.WriteByte('\n')
	}
	for  := range .Nodes {
		.WriteString(.Nodes[].String())
		.WriteByte('\n')
	}
	return .String()
}
Node represents a line in a Config.
type Node interface {
	Pos() Position
	String() string
}
KV is a line in the config file that contains a key, a value, and possibly a comment.
type KV struct {
	Key          string
	Value        string
	Comment      string
	hasEquals    bool
	leadingSpace int // Space before the key. TODO handle spaces vs tabs.
	position     Position
}
Pos returns k's Position.
func ( *KV) () Position {
	return .position
}
String prints k as it was parsed in the config file. There may be slight changes to the whitespace between values.
func ( *KV) () string {
	if  == nil {
		return ""
	}
	 := " "
	if .hasEquals {
		 = " = "
	}
	 := fmt.Sprintf("%s%s%s%s", strings.Repeat(" ", int(.leadingSpace)), .Key, , .Value)
	if .Comment != "" {
		 += " #" + .Comment
	}
	return 
}
Empty is a line in the config file that contains only whitespace or comments.
type Empty struct {
	Comment      string
	leadingSpace int // TODO handle spaces vs tabs.
	position     Position
}
Pos returns e's Position.
func ( *Empty) () Position {
	return .position
}
String prints e as it was parsed in the config file.
func ( *Empty) () string {
	if  == nil {
		return ""
	}
	if .Comment == "" {
		return ""
	}
	return fmt.Sprintf("%s#%s", strings.Repeat(" ", int(.leadingSpace)), .Comment)
}
Include holds the result of an Include directive, including the config files that have been parsed as part of that directive. At most 5 levels of Include statements will be parsed.
Comment is the contents of any comment at the end of the Include statement.
an include directive can include several different files, and wildcards
1:1 mapping between matches and keys in files array; matches preserves ordering
actual filenames are listed here
ErrDepthExceeded is returned if too many Include directives are parsed. Usually this indicates a recursive loop (an Include directive pointing to the file it contains).
var ErrDepthExceeded = errors.New("ssh_config: max recurse depth exceeded")

Use map to record duplicates as we find them.
	 := make(map[string]bool, len())
	 := make([]string, 0)

lint:ignore S1002 I prefer it this way
		if [[]] == false {
			[[]] = true
			 = append(, [])
		}
	}
	return 
}
NewInclude creates a new Include with a list of file globs to include. Configuration files are parsed greedily (e.g. as soon as this function runs). Any error encountered while parsing nested configuration files will be returned.
func ( []string,  bool,  Position,  string,  bool,  uint8) (*Include, error) {
	if  > maxRecurseDepth {
		return nil, ErrDepthExceeded
	}
	 := &Include{
		Comment:      ,
		directives:   ,
		files:        make(map[string]*Config),
		position:     ,
		leadingSpace: .Col - 1,
		depth:        ,
		hasEquals:    ,
no need for inc.mu.Lock() since nothing else can access this inc
	 := make([]string, 0)
	for  := range  {
		var  string
		if filepath.IsAbs([]) {
			 = []
		} else if  {
			 = filepath.Join("/etc/ssh", [])
		} else {
			 = filepath.Join(homedir(), ".ssh", [])
		}
		,  := filepath.Glob()
		if  != nil {
			return nil, 
		}
		 = append(, ...)
	}
	 = removeDups()
	.matches = 
	for  := range  {
		,  := parseWithDepth([], )
		if  != nil {
			return nil, 
		}
		.files[[]] = 
	}
	return , nil
}
Pos returns the position of the Include directive in the larger file.
func ( *Include) () Position {
	return .position
}
Get finds the first value in the Include statement matching the alias and the given key.
func ( *Include) (,  string) string {
	.mu.Lock()
TODO: we search files in any order which is not correct
	for  := range .matches {
		 := .files[.matches[]]
		if  == nil {
			panic("nil cfg")
		}
		,  := .Get(, )
		if  == nil &&  != "" {
			return 
		}
	}
	return ""
}
String prints out a string representation of this Include directive. Note included Config files are not printed as part of this representation.
func ( *Include) () string {
	 := " "
	if .hasEquals {
		 = " = "
	}
	 := fmt.Sprintf("%sInclude%s%s", strings.Repeat(" ", int(.leadingSpace)), , strings.Join(.directives, " "))
	if .Comment != "" {
		 += " #" + .Comment
	}
	return 
}

var matchAll *Pattern

func () {
	var  error
	matchAll,  = NewPattern("*")
	if  != nil {
		panic()
	}
}

func () *Config {
	return &Config{
		Hosts: []*Host{
			&Host{
				implicit: true,
				Patterns: []*Pattern{matchAll},
				Nodes:    make([]Node, 0),
			},
		},
		depth: 0,
	}