ssh_key.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package system
  15. import (
  16. "fmt"
  17. "io"
  18. "io/ioutil"
  19. "os/exec"
  20. "strings"
  21. )
  22. // AuthorizeSSHKeys adds the provided SSH public key to the core user's list of
  23. // authorized keys
  24. func AuthorizeSSHKeys(user string, keysName string, keys []string) error {
  25. for i, key := range keys {
  26. keys[i] = strings.TrimSpace(key)
  27. }
  28. // join all keys with newlines, ensuring the resulting string
  29. // also ends with a newline
  30. joined := fmt.Sprintf("%s\n", strings.Join(keys, "\n"))
  31. cmd := exec.Command("update-ssh-keys", "-u", user, "-a", keysName)
  32. stdin, err := cmd.StdinPipe()
  33. if err != nil {
  34. return err
  35. }
  36. stdout, err := cmd.StdoutPipe()
  37. if err != nil {
  38. return err
  39. }
  40. stderr, err := cmd.StderrPipe()
  41. if err != nil {
  42. return err
  43. }
  44. err = cmd.Start()
  45. if err != nil {
  46. stdin.Close()
  47. return err
  48. }
  49. _, err = io.WriteString(stdin, joined)
  50. if err != nil {
  51. return err
  52. }
  53. stdin.Close()
  54. stdoutBytes, _ := ioutil.ReadAll(stdout)
  55. stderrBytes, _ := ioutil.ReadAll(stderr)
  56. err = cmd.Wait()
  57. if err != nil {
  58. return fmt.Errorf("Call to update-ssh-keys failed with %v: %s %s", err, string(stdoutBytes), string(stderrBytes))
  59. }
  60. return nil
  61. }