Skip to content

Commit

Permalink
fix: fix sn is empty && get sn fail (#943)
Browse files Browse the repository at this point in the history
* fix: filter the case when sn is empty

filter the case when sn is empty

* fix: add sn get method for darwin

add sn get method for darwin
  • Loading branch information
wudihechao authored May 21, 2024
1 parent 627a7cc commit 570455c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 15 deletions.
30 changes: 22 additions & 8 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,6 @@ func (c *ConfigType) GetHostIP() string {
}
func (c *ConfigType) GetHostSN() string {
ret := HostInfo.GetSN()
if ret == "" {
return c.GetHostname()
}

return ret
}
func GetEnv(key string) string {
Expand Down Expand Up @@ -310,8 +306,9 @@ func GetOutboundIP() (net.IP, error) {
}

func GetBiosSn() (string, error) {
sn := ""
if runtime.GOOS == "windows" {
var sn string
switch runtime.GOOS {
case "windows":
out, err := exec.Command("cmd", "/C", "wmic bios get serialnumber").Output()
if err != nil {
return "", fmt.Errorf("failed to get bios sn: %v", err)
Expand All @@ -322,12 +319,29 @@ func GetBiosSn() (string, error) {
// 获取第二行
sn = strings.TrimSpace(lines[1])
}
} else {
out, err := exec.Command("cat", "/sys/class/dmi/id/product_serial").Output()
case "darwin":
out, err := exec.Command("system_profiler", "SPHardwareDataType").Output()
if err != nil {
return "", fmt.Errorf("failed to get bios sn: %v", err)
}
lines := strings.Split(string(out), "\n")
for _, line := range lines {
if strings.Contains(line, "Serial Number (system)") {
parts := strings.Split(line, ":")
if len(parts) > 1 {
sn = strings.TrimSpace(parts[1])
break
}
}
}
case "linux":
out, err := exec.Command("dmidecode", "-s", "system-serial-number").Output()
if err != nil {
return "", fmt.Errorf("failed to get bios sn: %v", err)
}
sn = strings.TrimSpace(string(out))
default:
return "", fmt.Errorf("not support os to get sn")
}
return sn, nil
}
Expand Down
10 changes: 3 additions & 7 deletions config/hostname.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,8 @@ func InitHostInfo() error {
ip = fmt.Sprint(nip)
}
var sn string
sn, err = GetBiosSn()
if err != nil {
return err
}
// allow sn empty
sn, _ = GetBiosSn()
HostInfo = &HostInfoCache{
name: hostname,
ip: fmt.Sprint(ip),
Expand Down Expand Up @@ -114,9 +112,7 @@ func (c *HostInfoCache) update() {
HostInfo.SetIP(fmt.Sprint(ip))
}
sn, err := GetBiosSn()
if err != nil {
log.Println("E! failed to get sn:", err)
} else {
if err == nil {
HostInfo.SetSN(sn)
}
}
Expand Down

0 comments on commit 570455c

Please sign in to comment.