ssh.go 2.1 KB
Newer Older
1 2 3
package common

import (
4 5
	"errors"
	"fmt"
6
	"io/ioutil"
7
	"log"
8 9
	"os"

10
	"github.com/mitchellh/multistep"
11
	commonssh "github.com/mitchellh/packer/common/ssh"
12
	"github.com/mitchellh/packer/communicator/ssh"
Mitchell Hashimoto's avatar
Mitchell Hashimoto committed
13
	gossh "golang.org/x/crypto/ssh"
14 15
)

16
func CommHost(config *SSHConfig) func(multistep.StateBag) (string, error) {
17 18 19 20
	return func(state multistep.StateBag) (string, error) {
		driver := state.Get("driver").(Driver)
		vmxPath := state.Get("vmx_path").(string)

21
		if config.Comm.SSHHost != "" {
22
			return config.Comm.SSHHost, nil
23 24
		}

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
		log.Println("Lookup up IP information...")
		f, err := os.Open(vmxPath)
		if err != nil {
			return "", err
		}
		defer f.Close()

		vmxBytes, err := ioutil.ReadAll(f)
		if err != nil {
			return "", err
		}

		vmxData := ParseVMX(string(vmxBytes))

		var ok bool
		macAddress := ""
		if macAddress, ok = vmxData["ethernet0.address"]; !ok || macAddress == "" {
			if macAddress, ok = vmxData["ethernet0.generatedaddress"]; !ok || macAddress == "" {
				return "", errors.New("couldn't find MAC address in VMX")
			}
		}

		ipLookup := &DHCPLeaseGuestLookup{
			Driver:     driver,
			Device:     "vmnet8",
			MACAddress: macAddress,
		}

		ipAddress, err := ipLookup.GuestIP()
		if err != nil {
			log.Printf("IP lookup failed: %s", err)
			return "", fmt.Errorf("IP lookup failed: %s", err)
		}

		if ipAddress == "" {
			log.Println("IP is blank, no IP yet.")
			return "", errors.New("IP is blank")
		}

		log.Printf("Detected IP: %s", ipAddress)
65
		return ipAddress, nil
66 67 68
	}
}

69
func SSHConfigFunc(config *SSHConfig) func(multistep.StateBag) (*gossh.ClientConfig, error) {
70
	return func(state multistep.StateBag) (*gossh.ClientConfig, error) {
71
		auth := []gossh.AuthMethod{
72
			gossh.Password(config.Comm.SSHPassword),
73
			gossh.KeyboardInteractive(
74
				ssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)),
75 76
		}

77 78
		if config.Comm.SSHPrivateKey != "" {
			signer, err := commonssh.FileSigner(config.Comm.SSHPrivateKey)
79 80 81 82
			if err != nil {
				return nil, err
			}

83
			auth = append(auth, gossh.PublicKeys(signer))
84 85 86
		}

		return &gossh.ClientConfig{
87
			User: config.Comm.SSHUsername,
88 89 90 91
			Auth: auth,
		}, nil
	}
}