Signed-off-by: Vasiliy Tolstov <v.tolstov@selfip.ru>
This commit is contained in:
2015-03-26 10:23:27 +03:00
parent 4e54447b8e
commit 993af2705a
23 changed files with 306 additions and 48 deletions

View File

@@ -18,58 +18,35 @@ package system
import (
"fmt"
"io"
"io/ioutil"
"os/exec"
"os"
"strings"
)
// Add the provide SSH public key to the core user's list of
// authorized keys
func AuthorizeSSHKeys(user string, keysName string, keys []string) error {
for i, key := range keys {
keys[i] = strings.TrimSpace(key)
for name, key := range keys {
keys[name] = strings.TrimSpace(key)
}
// join all keys with newlines, ensuring the resulting string
// also ends with a newline
joined := fmt.Sprintf("%s\n", strings.Join(keys, "\n"))
cmd := exec.Command("update-ssh-keys", "-u", user, "-a", keysName)
stdin, err := cmd.StdinPipe()
authorized_file := ""
switch user {
case "root":
authorized_file = "/root/.ssh/authorized_keys"
default:
authorized_file = fmt.Sprintf("/home/%s/.ssh/authorized_keys", user)
}
f, err := os.OpenFile(authorized_file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(joined)
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
stdin.Close()
return err
}
_, err = io.WriteString(stdin, joined)
if err != nil {
return err
}
stdin.Close()
stdoutBytes, _ := ioutil.ReadAll(stdout)
stderrBytes, _ := ioutil.ReadAll(stderr)
err = cmd.Wait()
if err != nil {
return fmt.Errorf("Call to update-ssh-keys failed with %v: %s %s", err, string(stdoutBytes), string(stderrBytes))
}
return nil
return err
}

View File

@@ -79,6 +79,22 @@ func CreateUser(u *config.User) error {
output, err := exec.Command("useradd", args...).CombinedOutput()
if err != nil {
log.Printf("Command 'useradd %s' failed: %v\n%s", strings.Join(args, " "), err, output)
return err
}
args = []string{}
if u.LockPasswd {
args = append(args, "--lock")
} else {
args = append(args, "--unlock")
}
args = append(args, u.Name)
output, err = exec.Command("passwd", args...).CombinedOutput()
if err != nil {
log.Printf("Command 'passwd %s' failed: %v\n%s", strings.Join(args, " "), err, output)
}
return err
}