github.com/sneal/packer@v0.5.2/builder/vmware/common/ssh.go (about) 1 package common 2 3 import ( 4 gossh "code.google.com/p/go.crypto/ssh" 5 "errors" 6 "fmt" 7 "io/ioutil" 8 "log" 9 "os" 10 11 "github.com/mitchellh/multistep" 12 "github.com/mitchellh/packer/communicator/ssh" 13 ) 14 15 func SSHAddressFunc(config *SSHConfig) func(multistep.StateBag) (string, error) { 16 return func(state multistep.StateBag) (string, error) { 17 driver := state.Get("driver").(Driver) 18 vmxPath := state.Get("vmx_path").(string) 19 20 log.Println("Lookup up IP information...") 21 f, err := os.Open(vmxPath) 22 if err != nil { 23 return "", err 24 } 25 defer f.Close() 26 27 vmxBytes, err := ioutil.ReadAll(f) 28 if err != nil { 29 return "", err 30 } 31 32 vmxData := ParseVMX(string(vmxBytes)) 33 34 var ok bool 35 macAddress := "" 36 if macAddress, ok = vmxData["ethernet0.address"]; !ok || macAddress == "" { 37 if macAddress, ok = vmxData["ethernet0.generatedaddress"]; !ok || macAddress == "" { 38 return "", errors.New("couldn't find MAC address in VMX") 39 } 40 } 41 42 ipLookup := &DHCPLeaseGuestLookup{ 43 Driver: driver, 44 Device: "vmnet8", 45 MACAddress: macAddress, 46 } 47 48 ipAddress, err := ipLookup.GuestIP() 49 if err != nil { 50 log.Printf("IP lookup failed: %s", err) 51 return "", fmt.Errorf("IP lookup failed: %s", err) 52 } 53 54 if ipAddress == "" { 55 log.Println("IP is blank, no IP yet.") 56 return "", errors.New("IP is blank") 57 } 58 59 log.Printf("Detected IP: %s", ipAddress) 60 return fmt.Sprintf("%s:%d", ipAddress, config.SSHPort), nil 61 } 62 } 63 64 func SSHConfigFunc(config *SSHConfig) func(multistep.StateBag) (*gossh.ClientConfig, error) { 65 return func(state multistep.StateBag) (*gossh.ClientConfig, error) { 66 auth := []gossh.ClientAuth{ 67 gossh.ClientAuthPassword(ssh.Password(config.SSHPassword)), 68 gossh.ClientAuthKeyboardInteractive( 69 ssh.PasswordKeyboardInteractive(config.SSHPassword)), 70 } 71 72 if config.SSHKeyPath != "" { 73 keyring, err := sshKeyToKeyring(config.SSHKeyPath) 74 if err != nil { 75 return nil, err 76 } 77 78 auth = append(auth, gossh.ClientAuthKeyring(keyring)) 79 } 80 81 return &gossh.ClientConfig{ 82 User: config.SSHUser, 83 Auth: auth, 84 }, nil 85 } 86 } 87 88 func sshKeyToKeyring(path string) (gossh.ClientKeyring, error) { 89 f, err := os.Open(path) 90 if err != nil { 91 return nil, err 92 } 93 defer f.Close() 94 95 keyBytes, err := ioutil.ReadAll(f) 96 if err != nil { 97 return nil, err 98 } 99 100 keyring := new(ssh.SimpleKeychain) 101 if err := keyring.AddPEMKey(string(keyBytes)); err != nil { 102 return nil, err 103 } 104 105 return keyring, nil 106 }