recognize home dir

This commit is contained in:
pixiake 2020-05-26 02:59:35 +08:00
parent 06813abca1
commit cca115537d
2 changed files with 63 additions and 1 deletions

View File

@ -1,7 +1,10 @@
package v1alpha1
import (
"fmt"
"github.com/kubesphere/kubekey/pkg/util"
"strconv"
"strings"
)
const (
@ -74,6 +77,13 @@ func SetDefaultHostsCfg(cfg *ClusterSpec) []HostCfg {
if host.Port == "" {
host.Port = strconv.Itoa(22)
}
if host.Password == "" && host.PrivateKeyPath == "" {
host.PrivateKeyPath = "~/.ssh/id_rsa"
}
if host.PrivateKeyPath != "" && strings.HasPrefix(strings.TrimSpace(host.PrivateKeyPath), "~/") {
homeDir, _ := util.Home()
host.PrivateKeyPath = strings.Replace(host.PrivateKeyPath, "~/", fmt.Sprintf("%s/", homeDir), 1)
}
hostscfg = append(hostscfg, host)
}

View File

@ -1,18 +1,22 @@
package util
import (
"bytes"
"encoding/binary"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"net"
"os"
"os/exec"
"os/user"
"runtime"
"strconv"
"strings"
"text/template"
)
const (
VERSION = "KubeKey Version v1.0.0-dev\nKubernetes Version v1.17.6\nKubeSphere Version 3.0.0"
VERSION = "KubeKey Version v1.0.0-dev\nKubernetes Version v1.17.6\nKubeSphere Version 3.0.0"
VersionBig = 1
VersionSmall = 2
VersionEqual = 0
@ -293,3 +297,51 @@ func compareByBytes(verA, verB []byte) int {
return VersionEqual
}
// returns the home directory for the executing user.
func Home() (string, error) {
user, err := user.Current()
if nil == err {
return user.HomeDir, nil
}
if "windows" == runtime.GOOS {
return homeWindows()
}
return homeUnix()
}
func homeUnix() (string, error) {
if home := os.Getenv("HOME"); home != "" {
return home, nil
}
var stdout bytes.Buffer
cmd := exec.Command("sh", "-c", "eval echo ~$USER")
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return "", err
}
result := strings.TrimSpace(stdout.String())
if result == "" {
return "", errors.New("blank output when reading home directory")
}
return result, nil
}
func homeWindows() (string, error) {
drive := os.Getenv("HOMEDRIVE")
path := os.Getenv("HOMEPATH")
home := drive + path
if drive == "" || path == "" {
home = os.Getenv("USERPROFILE")
}
if home == "" {
return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")
}
return home, nil
}