ssh_config

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 22, 2025 License: MIT Imports: 14 Imported by: 0

README

ssh_config

Like https://github.com/kevinburke/ssh_config, but with some additional features:

  • Partial support for Match directive
  • Support for "+", "-" and "^" modifiers
  • Returns correct IdentityFiles
  • Adds a public MakeDefaultUserSettings function

Documentation

Overview

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.Blocks {
	fmt.Println("patterns:", host.Patterns)
	for _, node := range host.Nodes {
		fmt.Println(node.String())
	}
}

// Write the cfg back to disk:
fmt.Println(cfg.String())

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultUserSettings = MakeDefaultUserSettings()

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.

View Source
var ErrDepthExceeded = errors.New("ssh_config: max recurse depth exceeded")

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).

Functions

func Default

func Default(keyword string) string

Default returns the default value for the given keyword, for example "22" if the keyword is "Port". Default returns the empty string if the keyword has no default, or if the keyword is unknown. Keyword matching is case-insensitive.

Default values are provided by OpenSSH_7.4p1 on a Mac.

Example
package main

import (
	"fmt"

	"github.com/alebeck/ssh_config"
)

func main() {
	fmt.Println(ssh_config.Default("Port"))
	fmt.Println(ssh_config.Default("UnknownVar"))
}
Output:

22

func Get

func Get(alias, key, user string) string

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 GetAll

func GetAll(alias, key, user string) []string

GetAll retrieves zero or more directives for key for the given alias. GetAll returns nil if no value was found, or if IgnoreErrors is false and we could not parse the configuration file. Use GetAllStrict to disambiguate the latter cases.

In most cases you want to use Get or GetStrict, which returns a single value. However, a subset of ssh configuration values (IdentityFile, for example) allow you to specify multiple directives.

The match for key is case insensitive.

GetAll is a wrapper around DefaultUserSettings.GetAll.

func GetAllStrict

func GetAllStrict(alias, key, user string) ([]string, error)

GetAllStrict retrieves zero or more directives for key for the given alias.

In most cases you want to use Get or GetStrict, which returns a single value. However, a subset of ssh configuration values (IdentityFile, for example) allow you to specify multiple directives.

The returned 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.

GetAllStrict is a wrapper around DefaultUserSettings.GetAllStrict.

func GetStrict

func GetStrict(alias, key, user string) (string, error)

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.

The returned 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 SupportsMultiple

func SupportsMultiple(key string) bool

SupportsMultiple reports whether a directive can be specified multiple times.

Types

type Block

type Block interface {
	// GetNodes returns the nodes belonging to the Block
	GetNodes() []Node
	// SetNodes sets the nodes belonging to the Block
	SetNodes(nodes []Node)
	// Matches returns true if the Block matches the passed MatchContext
	Matches(ctx *MatchContext) bool
	// String prints the Block as it would appear in a config file
	String() string
	// IsFinal indicates whether this match block is final
	IsFinal() bool
}

Block describes either a Host or Match directive, which must implement a Matches and a String method.

type BlockData

type BlockData struct {
	// A Node is either a key/value pair or a comment line.
	Nodes []Node
	// EOLComment is the comment (if any) terminating the Host line.
	EOLComment string

	// Final indicates whether this match block is final
	Final bool
	// contains filtered or unexported fields
}

type Config

type Config struct {
	// A list of blocks to match against. The file begins with an implicit
	// "Host *" declaration matching all hosts.
	Blocks []Block
	// contains filtered or unexported fields
}

Config represents an SSH config file.

func Decode

func Decode(r io.Reader) (*Config, error)

Decode reads r into a Config, or returns an error if r could not be parsed as an SSH config file.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/alebeck/ssh_config"
)

func main() {
	var config = `
Host *.example.com
  Compression yes
`

	cfg, _ := ssh_config.Decode(strings.NewReader(config))
	ctx := ssh_config.NewMatchContext("test.example.com", "")
	val, _ := cfg.Get("Compression", ctx)
	fmt.Println(val)
}
Output:

yes

func DecodeBytes

func DecodeBytes(b []byte) (*Config, error)

DecodeBytes reads b into a Config, or returns an error if r could not be parsed as an SSH config file.

func (*Config) Get

func (c *Config) Get(key string, ctx *MatchContext) (string, error)

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) GetAll

func (c *Config) GetAll(key string, ctx *MatchContext) ([]string, error)

GetAll returns all values in the configuration that match the alias and contains key, or nil if none are present.

func (Config) MarshalText

func (c Config) MarshalText() ([]byte, error)

func (Config) String

func (c Config) String() string

String returns a string representation of the Config file.

type Empty

type Empty struct {
	Comment string
	// contains filtered or unexported fields
}

Empty is a line in the config file that contains only whitespace or comments.

func (*Empty) Pos

func (e *Empty) Pos() Position

Pos returns e's Position.

func (*Empty) String

func (e *Empty) String() string

String prints e as it was parsed in the config file.

type Host

type Host struct {
	// A list of host patterns that should match this host.
	Patterns []*Pattern
	*BlockData
}

Host describes a Host directive and the keywords that follow it.

func (*Host) GetNodes

func (h *Host) GetNodes() []Node

func (*Host) IsFinal

func (h *Host) IsFinal() bool

func (*Host) Matches

func (h *Host) Matches(ctx *MatchContext) bool

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.

Example
package main

import (
	"fmt"

	"github.com/alebeck/ssh_config"
)

func main() {
	pat, _ := ssh_config.NewPattern("test.*.example.com")
	host := &ssh_config.Host{Patterns: []*ssh_config.Pattern{pat}}
	fmt.Println(host.Matches(ssh_config.NewMatchContext("test.stage.example.com", "")))
	fmt.Println(host.Matches(ssh_config.NewMatchContext("othersubdomain.example.com", "")))
}
Output:

true
false

func (*Host) SetNodes

func (h *Host) SetNodes(nodes []Node)

func (*Host) String

func (h *Host) String() string

String prints h as it would appear in a config file. Minor tweaks may be present in the whitespace in the printed file.

type Include

type Include struct {
	// Comment is the contents of any comment at the end of the Include
	// statement.
	Comment string
	// contains filtered or unexported fields
}

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.

func NewInclude

func NewInclude(directives []string, hasEquals bool, pos Position, comment string, system bool, depth uint8) (*Include, error)

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 (*Include) Get

func (inc *Include) Get(key string, ctx *MatchContext) string

Get finds the first value in the Include statement matching the alias and the given key.

func (*Include) GetAll

func (inc *Include) GetAll(key string, ctx *MatchContext) ([]string, error)

GetAll finds all values in the Include statement matching the alias and the given key.

func (*Include) Pos

func (i *Include) Pos() Position

Pos returns the position of the Include directive in the larger file.

func (*Include) String

func (inc *Include) String() string

String prints out a string representation of this Include directive. Note included Config files are not printed as part of this representation.

type KV

type KV struct {
	Key   string
	Value string

	Comment string
	// contains filtered or unexported fields
}

KV is a line in the config file that contains a key, a value, and possibly a comment.

func (*KV) Pos

func (k *KV) Pos() Position

Pos returns k's Position.

func (*KV) String

func (k *KV) String() string

String prints k as it was parsed in the config file.

type Match

type Match struct {
	// Patterns is a map of key -> Pattern entries, e.g. "Address" -> Pattern("127.0.0.*")
	Patterns map[string]*Pattern
	*BlockData
}

func (*Match) GetNodes

func (m *Match) GetNodes() []Node

func (*Match) IsFinal

func (m *Match) IsFinal() bool

func (*Match) Matches

func (m *Match) Matches(ctx *MatchContext) bool

func (*Match) SetNodes

func (m *Match) SetNodes(nodes []Node)

func (*Match) String

func (m *Match) String() string

type MatchContext

type MatchContext struct {
	// Remote target user
	User string
	// Final host name
	Host string
	// Local user
	LocalUser string
	// Original Host, a.k.a. alias
	OriginalHost string
	// Final blocks to parse after matching
	FinalBlocks []Block
}

MatchContext holds information about previously matched values, to be used for Match block matching.

func NewMatchContext

func NewMatchContext(alias, user string) *MatchContext

type Node

type Node interface {
	Pos() Position
	String() string
}

Node represents a line in a Config.

type Pattern

type Pattern struct {
	// contains filtered or unexported fields
}

Pattern is a pattern in a Host declaration. Patterns are read-only values; create a new one with NewPattern().

Example
package main

import (
	"fmt"

	"github.com/alebeck/ssh_config"
)

func main() {
	pat, _ := ssh_config.NewPattern("*")
	host := &ssh_config.Host{Patterns: []*ssh_config.Pattern{pat}}
	fmt.Println(host.Matches(ssh_config.NewMatchContext("test.stage.example.com", "")))
	fmt.Println(host.Matches(ssh_config.NewMatchContext("othersubdomain.example.com", "")))
}
Output:

true
true

func NewPattern

func NewPattern(s string) (*Pattern, error)

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 (Pattern) String

func (p Pattern) String() string

String prints the string representation of the pattern.

type Position

type Position struct {
	Line int // line within the document
	Col  int // column within the line
}

Position of a document element within a SSH document.

Line and Col are both 1-indexed positions for the element's line number and column number, respectively. Values of zero or less will cause Invalid(), to return true.

func (Position) Invalid

func (p Position) Invalid() bool

Invalid returns whether or not the position is valid (i.e. with negative or null values)

func (Position) String

func (p Position) String() string

String representation of the position. Displays 1-indexed line and column numbers.

type UserSettings

type UserSettings struct {
	IgnoreErrors bool
	// contains filtered or unexported fields
}

UserSettings checks ~/.ssh and /etc/ssh for configuration files. The config files are parsed and cached the first time Get() or GetStrict() is called.

func MakeDefaultUserSettings added in v0.1.2

func MakeDefaultUserSettings() *UserSettings

MakeDefaultUserSettings creates a new UserSettings instance with default settings.

func (*UserSettings) ConfigFinder

func (u *UserSettings) ConfigFinder(f func() string)

ConfigFinder will invoke f to try to find a ssh config file in a custom location on disk, instead of in /etc/ssh or $HOME/.ssh. f should return the name of a file containing SSH configuration.

ConfigFinder must be invoked before any calls to Get or GetStrict and panics if f is nil. Most users should not need to use this function.

Example
package main

import (
	"path/filepath"

	"github.com/alebeck/ssh_config"
)

func main() {
	// This can be used to test SSH config parsing.
	u := ssh_config.UserSettings{}
	u.ConfigFinder(func() string {
		return filepath.Join("testdata", "test_config")
	})
	u.Get("example.com", "Host", "")
}

func (*UserSettings) Get

func (u *UserSettings) Get(alias, key, user string) string

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) GetAll

func (u *UserSettings) GetAll(alias, key, user string) []string

GetAll retrieves zero or more directives for key for the given alias. GetAll returns nil 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) GetAllStrict

func (u *UserSettings) GetAllStrict(alias, key, user string) ([]string, error)

GetAllStrict retrieves zero or more directives for key for the given 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.

The returned 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) GetStrict

func (u *UserSettings) GetStrict(alias, key, user string) (string, error)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL