package main import ( "fmt" "os" "strings" "github.com/spf13/cobra" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh" ) func knownHostsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "known-hosts", Short: "Clean up host keys of re-deployed hosts", } cmd.AddCommand(knownHostsResetCmd()) return cmd } func knownHostsResetCmd() *cobra.Command { var yes, dryRun bool cmd := &cobra.Command{ Use: "reset HOST...", Short: "Remove the known_hosts entries of hosts (name, current and previous address)", Long: `Remove the stored host keys of hosts with ssh-keygen -R, after a host was re-installed or got a new address. Removed are the hostname, the address netssh connects to, the previously cached address if NetBox changed it, and [name]:port / [address]:port for a non-standard port. ssh-keygen keeps the previous file as known_hosts.old.`, Example: " netssh known-hosts reset web01\n netssh known-hosts reset --dry-run web01 web02", Args: cobra.MinimumNArgs(1), ValidArgsFunction: hostCompletion, RunE: func(cmd *cobra.Command, args []string) error { cfg, err := config.Load() if err != nil { return err } c := newCache(cfg) _ = c.Load() type plan struct { keys []string file string } var plans []plan var all []string for _, target := range args { previous, _ := c.Get(target) h, err := resolveTargetE(cfg, target, false) if err != nil { return err } addresses := []string{h.IP} if h.PreviousIP != "" { addresses = append(addresses, h.PreviousIP) } if previous.IP != "" && previous.IP != h.IP { addresses = append(addresses, previous.IP) } _, port := hostDefaults(cfg, h) if port <= 0 { port = 22 } opts := hostOptions(cfg, h) p := plan{keys: knownHostsKeys(h.Name, addresses, port), file: knownHostsFile(opts)} plans = append(plans, p) all = append(all, p.keys...) } if dryRun { for _, p := range plans { for _, key := range p.keys { argv := []string{"ssh-keygen", "-R", key} if p.file != "" { argv = append(argv, "-f", p.file) } fmt.Fprintln(cmd.OutOrStdout(), internalssh.Quote(argv)) } } return nil } if err := confirmAction("Remove known_hosts entries for "+strings.Join(all, ", "), yes); err != nil { return err } for _, p := range plans { if err := removeKnownHosts(p.keys, p.file); err != nil { return err } } fmt.Fprintln(os.Stderr, "Done. The next connection asks to confirm the new host key.") return nil }, } cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the ssh-keygen commands without running them") return cmd }