SSH client with identities support
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ssh-ident/identity.go

75 lines
1.4 KiB

4 years ago
package main
import (
"os"
"path"
"regexp"
"strings"
)
type Identity struct {
Name string
Path string
}
func newIdentity(config Config, name string) Identity {
return Identity{
Name: name,
Path: "",
}
}
var hostRegexps = map[string]*regexp.Regexp{
"ssh": regexp.MustCompile("(?P<user>.*@)?(?P<host>.*)"),
"scp": regexp.MustCompile("(?P<user>.*@)?(?P<host>.*):(?P<file>.*)"),
}
func extractHost(prog string, args []string) string {
args = removeOptions(prog, args)
switch prog {
case "ssh":
if len(args) == 0 {
return ""
}
re := hostRegexps["ssh"]
arg := args[0]
p := matchParams(re, arg)
return p["host"]
case "scp":
re := hostRegexps["scp"]
for _, arg := range args {
if p := matchParams(re, arg); p != nil {
return p["host"]
}
}
}
return ""
}
func findIdentityName(config Config, prog string, args []string) string {
name := os.Getenv("SSH_IDENTITY")
if name != "" {
return name
}
identities := config.Identities
host := extractHost(prog, args)
for _, identity := range identities {
match := identity.Key.(string)
name := identity.Value.(string)
4 years ago
if strings.Contains(host, match) {
return name
}
}
return config.DefaultIdentity
}
func FindIdentity(config Config, prog string, args []string) Identity {
name := findIdentityName(config, prog, args)
path := path.Join(config.IdentitiesDir, name)
return Identity{
Name: name,
Path: path,
}
}