github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/remote/ssh_utils.go (about) 1 package remote 2 3 import ( 4 "io/ioutil" 5 6 "github.com/pkg/errors" 7 8 "golang.org/x/crypto/ssh" 9 ) 10 11 // Given a path to a file containing a PEM-encoded private key, 12 // read in the file and use the private key to create an ssh authenticator. 13 func authFromPrivKeyFile(file string) ([]ssh.AuthMethod, error) { 14 15 // read in the file 16 fileBytes, err := ioutil.ReadFile(file) 17 if err != nil { 18 return nil, errors.Wrapf(err, "error reading private key file `%v`", file) 19 } 20 21 // convert it to an ssh.Signer 22 signer, err := ssh.ParsePrivateKey(fileBytes) 23 if err != nil { 24 return nil, errors.Wrapf(err, "error parsing private key from file `%v`", file) 25 } 26 27 return []ssh.AuthMethod{ssh.PublicKeys(signer)}, nil 28 } 29 30 // Create a client config, using the appropriate user and PEM-encoded private 31 // key file. 32 func createClientConfig(user string, keyfile string) (*ssh.ClientConfig, error) { 33 34 // initialize the config, with the correct user but no authentication 35 config := &ssh.ClientConfig{ 36 User: user, 37 Auth: []ssh.AuthMethod{}, 38 } 39 40 // read in the keyfile, if specified, and set up authentication based on it 41 if keyfile != "" { 42 authMethods, err := authFromPrivKeyFile(keyfile) 43 if err != nil { 44 return nil, errors.Wrapf(err, "error using private key from file `%v`", keyfile) 45 } 46 config.Auth = authMethods 47 } 48 49 return config, nil 50 }