user.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. "log"
  18. "os/exec"
  19. "os/user"
  20. "strings"
  21. "github.com/rancher/os/config/cloudinit/config"
  22. )
  23. func UserExists(u *config.User) bool {
  24. _, err := user.Lookup(u.Name)
  25. return err == nil
  26. }
  27. func CreateUser(u *config.User) error {
  28. args := []string{}
  29. if u.PasswordHash != "" {
  30. args = append(args, "--password", u.PasswordHash)
  31. } else {
  32. args = append(args, "--password", "*")
  33. }
  34. if u.GECOS != "" {
  35. args = append(args, "--comment", fmt.Sprintf("%q", u.GECOS))
  36. }
  37. if u.Homedir != "" {
  38. args = append(args, "--home-dir", u.Homedir)
  39. }
  40. if u.NoCreateHome {
  41. args = append(args, "--no-create-home")
  42. } else {
  43. args = append(args, "--create-home")
  44. }
  45. if u.PrimaryGroup != "" {
  46. args = append(args, "--gid", u.PrimaryGroup)
  47. }
  48. if len(u.Groups) > 0 {
  49. args = append(args, "--groups", strings.Join(u.Groups, ","))
  50. }
  51. if u.NoUserGroup {
  52. args = append(args, "--no-user-group")
  53. }
  54. if u.System {
  55. args = append(args, "--system")
  56. }
  57. if u.NoLogInit {
  58. args = append(args, "--no-log-init")
  59. }
  60. if u.Shell != "" {
  61. args = append(args, "--shell", u.Shell)
  62. }
  63. args = append(args, u.Name)
  64. output, err := exec.Command("useradd", args...).CombinedOutput()
  65. if err != nil {
  66. log.Printf("Command 'useradd %s' failed: %v\n%s", strings.Join(args, " "), err, output)
  67. }
  68. return err
  69. }
  70. func SetUserPassword(user, hash string) error {
  71. cmd := exec.Command("/usr/sbin/chpasswd", "-e")
  72. stdin, err := cmd.StdinPipe()
  73. if err != nil {
  74. return err
  75. }
  76. err = cmd.Start()
  77. if err != nil {
  78. return err
  79. }
  80. arg := fmt.Sprintf("%s:%s", user, hash)
  81. _, err = stdin.Write([]byte(arg))
  82. if err != nil {
  83. return err
  84. }
  85. stdin.Close()
  86. err = cmd.Wait()
  87. if err != nil {
  88. return err
  89. }
  90. return nil
  91. }