github.com/alouche/packer@v0.3.7/builder/virtualbox/ssh.go (about)

     1  package virtualbox
     2  
     3  import (
     4  	gossh "code.google.com/p/go.crypto/ssh"
     5  	"fmt"
     6  	"github.com/mitchellh/multistep"
     7  	"github.com/mitchellh/packer/communicator/ssh"
     8  	"io/ioutil"
     9  	"os"
    10  )
    11  
    12  func sshAddress(state multistep.StateBag) (string, error) {
    13  	sshHostPort := state.Get("sshHostPort").(uint)
    14  	return fmt.Sprintf("127.0.0.1:%d", sshHostPort), nil
    15  }
    16  
    17  func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) {
    18  	config := state.Get("config").(*config)
    19  
    20  	auth := []gossh.ClientAuth{
    21  		gossh.ClientAuthPassword(ssh.Password(config.SSHPassword)),
    22  		gossh.ClientAuthKeyboardInteractive(
    23  			ssh.PasswordKeyboardInteractive(config.SSHPassword)),
    24  	}
    25  
    26  	if config.SSHKeyPath != "" {
    27  		keyring, err := sshKeyToKeyring(config.SSHKeyPath)
    28  		if err != nil {
    29  			return nil, err
    30  		}
    31  
    32  		auth = append(auth, gossh.ClientAuthKeyring(keyring))
    33  	}
    34  
    35  	return &gossh.ClientConfig{
    36  		User: config.SSHUser,
    37  		Auth: auth,
    38  	}, nil
    39  }
    40  
    41  func sshKeyToKeyring(path string) (gossh.ClientKeyring, error) {
    42  	f, err := os.Open(path)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	defer f.Close()
    47  
    48  	keyBytes, err := ioutil.ReadAll(f)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	keyring := new(ssh.SimpleKeychain)
    54  	if err := keyring.AddPEMKey(string(keyBytes)); err != nil {
    55  		return nil, err
    56  	}
    57  
    58  	return keyring, nil
    59  }