Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement sshs config generator from known_hosts files #8

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 184 additions & 0 deletions cmd/generate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package cmd

import (
"fmt"
"log"
"os"
"regexp"
"strings"

valid "github.com/asaskevich/govalidator"
"github.com/mitchellh/go-homedir"
"github.com/quantumsheep/sshconfig"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)

var generateCmd = &cobra.Command{
Use: "generate",
Short: "Generate a ssh configuration from different sources",
Version: rootCmd.Version,
Run: runGenerate,
}

func init() {
flags := generateCmd.Flags()
flags.Bool("known-hosts", false, "Generate from known_hosts file")
flags.String("known-hosts-file", "~/.ssh/known_hosts", "Path of known_hosts file")
flags.Bool("known-hosts-allow-single-ip", true, "Allow single IP addresses (without hostname)")

viper.SetDefault("author", "quantumsheep <[email protected]>")
viper.SetDefault("license", "MIT")
}

func runGenerate(cmd *cobra.Command, args []string) {
flags := cmd.Flags()

knownHosts, e := flags.GetBool("known-hosts")
if e != nil {
log.Fatal(e)
}

if !knownHosts {
cmd.Help()
os.Exit(0)
}

configs := make([]*KnownHostConfig, 0)

if knownHosts {
configs = append(configs, generateFromKnownHosts(flags)...)
}

config := strings.Join(KnownHostConfigStrings(KnownHostConfigUniques(configs)), "\n\n")
fmt.Println(config)
}

func generateFromKnownHosts(flags *pflag.FlagSet) []*KnownHostConfig {
knownHostsFile := "~/.ssh/known_hosts"

if str, e := flags.GetString("known-hosts-file"); e == nil && str != "" {
knownHostsFile = str
}

knownHostsFile, e := homedir.Expand(knownHostsFile)
if e != nil {
log.Fatal(e)
}

// open file
bytes, e := os.ReadFile(knownHostsFile)
if e != nil {
log.Fatal(e)
}

data := string(bytes)
lines := strings.Split(data, "\n")

rx := regexp.MustCompile(`^(\[(?P<Host>.*?)\]:(?P<Port>\d+))|(?P<SingleHost>.*?)$`)

configs := make([]*KnownHostConfig, 0)

for _, line := range lines {
if line == "" {
continue
}

lineConfigs := make([]*KnownHostConfig, 0)

targets := strings.Split(strings.Split(line, " ")[0], ",")
for _, target := range targets {
config := NewKnownHostConfig()

matches := rx.FindStringSubmatch(target)

if host := matches[rx.SubexpIndex("Host")]; host != "" {
port := matches[rx.SubexpIndex("Port")]

config.Host = host + ":" + port
config.HostName = host
config.Port = port
} else if host := matches[rx.SubexpIndex("SingleHost")]; host != "" {
config.Host = host
config.HostName = host
}

lineConfigs = append(lineConfigs, config)
}

allowSingleIp, e := flags.GetBool("known-hosts-allow-single-ip")
if e != nil {
log.Fatal(e)
}

var config *KnownHostConfig = nil

// Select the first config with a valid domain name (defaults to the first config)
for _, lineConfig := range lineConfigs {
if valid.IsDNSName(lineConfig.HostName) {
config = lineConfig
break
}
}

if config != nil {
configs = append(configs, config)
} else if allowSingleIp && len(lineConfigs) > 0 {
configs = append(configs, lineConfigs[0])
}
}

return configs
}

type KnownHostConfig struct {
*sshconfig.SSHHost

Host string
Port string
}

func NewKnownHostConfig() *KnownHostConfig {
return &KnownHostConfig{
SSHHost: &sshconfig.SSHHost{},
Port: "22",
}
}

func (c *KnownHostConfig) String() string {
return "Host " + c.Host +
"\n Hostname " + c.HostName +
"\n Port " + c.Port
}

func KnownHostConfigStrings(configs []*KnownHostConfig) []string {
list := make([]string, 0)

for _, item := range configs {
list = append(list, item.String())
}

return list
}

func KnownHostConfigUniques(configs []*KnownHostConfig) []*KnownHostConfig {
list := make([]*KnownHostConfig, 0)

for _, item := range configs {
found := false

for _, item2 := range list {
if item.Host == item2.Host && item.HostName == item2.HostName && item.Port == item2.Port {
found = true
break
}
}

if !found {
list = append(list, item)
}
}

return list
}
40 changes: 21 additions & 19 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,29 @@ var rootCmd = &cobra.Command{
Use: "sshs",
Short: "ssh clients manager",
Version: Version,
Run: run,
Run: runRoot,
}

func run(cmd *cobra.Command, args []string) {
func init() {
flags := rootCmd.Flags()
flags.StringP("search", "s", "", "Host search filter")
flags.StringP("config", "c", "~/.ssh/config", "SSH config file")
flags.BoolP("proxy", "p", false, "Display full ProxyCommand")

viper.SetDefault("author", "quantumsheep <[email protected]>")
viper.SetDefault("license", "MIT")

rootCmd.AddCommand(generateCmd)
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

func runRoot(cmd *cobra.Command, args []string) {
flags := cmd.Flags()

sshConfigPath, e := flags.GetString("config")
Expand Down Expand Up @@ -95,20 +114,3 @@ func createFileRecursive(filename string) error {

return nil
}

func Execute() {
if e := rootCmd.Execute(); e != nil {
fmt.Println(e)
os.Exit(1)
}
}

func init() {
flags := rootCmd.PersistentFlags()
flags.StringP("search", "s", "", "Host search filter")
flags.StringP("config", "c", "~/.ssh/config", "SSH config file")
flags.BoolP("proxy", "p", false, "Display full ProxyCommand")

viper.SetDefault("author", "quantumsheep <[email protected]>")
viper.SetDefault("license", "MIT")
}
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/quantumsheep/sshs

go 1.17
go 1.18

require (
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d
Expand All @@ -9,6 +9,7 @@ require (
github.com/quantumsheep/sshconfig v1.1.0
github.com/rivo/tview v0.0.0-20220129131435-1f7581b67bd1
github.com/spf13/cobra v1.3.0
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.10.1
)

Expand All @@ -26,7 +27,6 @@ require (
github.com/spf13/afero v1.6.0 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d // indirect
Expand Down
4 changes: 0 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,6 @@ github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pf
github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/hashicorp/consul/api v1.11.0/go.mod h1:XjsvQN+RJGWI2TWy1/kqaE16HrR2J/FWgkYjdZQsX9M=
github.com/hashicorp/consul/api v1.12.0/go.mod h1:6pVBMo0ebnYdt2S3H87XhekM/HHrUoTD2XXb/VrZVy0=
github.com/hashicorp/consul/sdk v0.8.0/go.mod h1:GBvyrGALthsZObzUGsfgHZQDXjg4lOjagTIwIR1vPms=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
Expand Down Expand Up @@ -322,7 +321,6 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sagikazarmark/crypt v0.3.0/go.mod h1:uD/D+6UF4SrIR1uGEv7bBNkNqLGqUr43MRiaGWX1Nig=
github.com/sagikazarmark/crypt v0.4.0/go.mod h1:ALv2SRj7GxYV4HO9elxH9nS6M9gW+xDNxqmyJ6RfDFM=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
Expand Down Expand Up @@ -662,7 +660,6 @@ google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdr
google.golang.org/api v0.59.0/go.mod h1:sT2boj7M9YJxZzgeZqXogmhfmRWDtPzT31xkieUbuZU=
google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I=
google.golang.org/api v0.62.0/go.mod h1:dKmwPCydfsad4qCH08MSdgWjfHOyfpd4VtDGgRFdavw=
google.golang.org/api v0.63.0/go.mod h1:gs4ij2ffTRXwuzzgJl/56BdwJaA194ijkfn++9tDuPo=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
Expand Down Expand Up @@ -760,7 +757,6 @@ google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnD
google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34=
google.golang.org/grpc v1.40.1/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34=
google.golang.org/grpc v1.42.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU=
google.golang.org/grpc v1.43.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU=
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
Expand Down