From 887e6945345397dfa8f7efbf7da4c8cdad0013b4 Mon Sep 17 00:00:00 2001 From: rsclarke Date: Fri, 27 Jul 2018 20:24:06 +0800 Subject: [PATCH] add ssh agent support for qemu builder --- builder/qemu/ssh.go | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/builder/qemu/ssh.go b/builder/qemu/ssh.go index 9c565eb32..1ee44ddb0 100644 --- a/builder/qemu/ssh.go +++ b/builder/qemu/ssh.go @@ -1,10 +1,15 @@ package qemu import ( + "fmt" + "net" + "os" + commonssh "github.com/hashicorp/packer/common/ssh" - "github.com/hashicorp/packer/communicator/ssh" + packerssh "github.com/hashicorp/packer/communicator/ssh" "github.com/hashicorp/packer/helper/multistep" gossh "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" ) func commHost(state multistep.StateBag) (string, error) { @@ -19,10 +24,29 @@ func commPort(state multistep.StateBag) (int, error) { func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) { config := state.Get("config").(*Config) - auth := []gossh.AuthMethod{ - gossh.Password(config.Comm.SSHPassword), - gossh.KeyboardInteractive( - ssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)), + var auth []gossh.AuthMethod + + if config.Comm.SSHAgentAuth { + authSock := os.Getenv("SSH_AUTH_SOCK") + if authSock == "" { + return nil, fmt.Errorf("SSH_AUTH_SOCK is not set") + } + + sshAgent, err := net.Dial("unix", authSock) + if err != nil { + return nil, fmt.Errorf("Cannot connect to SSH Agent socket %q: %s", authSock, err) + } + auth = []gossh.AuthMethod{ + gossh.PublicKeysCallback(agent.NewClient(sshAgent).Signers), + } + } + + if config.Comm.SSHPassword != "" { + auth = append(auth, + gossh.Password(config.Comm.SSHPassword), + gossh.KeyboardInteractive( + packerssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)), + ) } if config.Comm.SSHPrivateKey != "" {