55 lines
1.6 KiB
Go
55 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
|
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
|
)
|
|
|
|
// preConnectRunner runs the hook; tests replace it to avoid spawning a shell.
|
|
var preConnectRunner = runPreConnectCommand
|
|
|
|
// preConnectEnv describes the host to the hook through environment variables.
|
|
func preConnectEnv(host resolvedHost, clientName string) []string {
|
|
instance, name := netbox.SplitTarget(host.Name)
|
|
return []string{
|
|
"NETSSH_HOST=" + name,
|
|
"NETSSH_TARGET=" + host.Name,
|
|
"NETSSH_INSTANCE=" + instance,
|
|
"NETSSH_IP=" + host.IP,
|
|
"NETSSH_KIND=" + host.Kind,
|
|
"NETSSH_TAGS=" + strings.Join(host.Tags, ","),
|
|
"NETSSH_CLIENT=" + clientName,
|
|
}
|
|
}
|
|
|
|
// runPreConnect runs the configured pre_connect hook for host. Its output goes
|
|
// to stderr so it never mixes with the output of a remote command or scp.
|
|
// A failing hook returns an error and the connection must not be opened.
|
|
func runPreConnect(command string, host resolvedHost, clientName string, dryRun bool) error {
|
|
if command == "" {
|
|
return nil
|
|
}
|
|
if dryRun {
|
|
fmt.Fprintf(os.Stderr, "# pre_connect (skipped in --dry-run): %s\n", command)
|
|
return nil
|
|
}
|
|
if err := preConnectRunner(command, preConnectEnv(host, clientName), os.Stdin, os.Stderr); err != nil {
|
|
return fmt.Errorf("pre_connect hook for %s failed: %w", host.Name, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func runPreConnectCommand(command string, env []string, stdin io.Reader, out io.Writer) error {
|
|
cmd := exec.Command("sh", "-c", command)
|
|
cmd.Env = append(os.Environ(), env...)
|
|
cmd.Stdin = stdin
|
|
cmd.Stdout = out
|
|
cmd.Stderr = out
|
|
return cmd.Run()
|
|
}
|