获取笔记本电脑序列号和制造商的 Golang 库?

huangapple go评论71阅读模式
英文:

Golang library to get the serial number and make of a laptop?

问题

想要了解使用一些 Golang 代码获取笔记本电脑的序列号和制造商的方法。

英文:

Want to know a way to get the serial number and make of a laptop using some golang code.

答案1

得分: 9

这个问题没有简单的答案,因为它与操作系统有关。一种选择是使用os/exec包并解析命令输出(对于Windows、Linux和OS X,使用不同的命令)。例如,要获取序列号:

  • Windows:wmic bios get serialnumber

  • Linux:dmidecode -t system

  • OS X:ioreg -l

然后结合适用于OS X的Go代码:

out, _ := exec.Command("/usr/sbin/ioreg", "-l").Output() // 忽略错误以简洁起见
for _, l := range strings.Split(string(out), "\n") {
    if strings.Contains(l, "IOPlatformSerialNumber") {
        s := strings.Split(l, " ")
        fmt.Printf("%s\n", s[len(s)-1])
    }
}
英文:

No easy answer for this, as this is OS-specific. One option is to use os/exec package and parse command output (different command for Windows, Linux and OS X). For example to obtain serial number on:

  • Windows: wmic bios get serialnumber

  • Linux: dmidecode -t system

  • OS X: ioreg -l

Then combined with Go code for OS X case:

out, _ := exec.Command("/usr/sbin/ioreg", "-l").Output() // err ignored for brevity
for _, l := range strings.Split(string(out), "\n") {
    if strings.Contains(l, "IOPlatformSerialNumber") {
        s := strings.Split(l, " ")
        fmt.Printf("%s\n", s[len(s)-1])
    }
}

答案2

得分: 1

在Pawel的回答基础上,我看到一个小的优化,因为在我的计算机上,信息在21,980行中的第31行。一旦找到并跳出for循环,我会立即返回它。

var serialNumber string
out, _ := exec.Command("/usr/sbin/ioreg", "-l").Output() // 为了简洁起见,忽略了错误
for _, l := range strings.Split(string(out), "\n") {
    if strings.Contains(l, "IOPlatformSerialNumber") {
        s := strings.Split(l, " ")
        serialNumber = s[len(s)-1]
        break
    }
}

前面的答案是可行的,但我不喜欢为了找到信息而遍历29,000行!😊

英文:

Working on what Pawel answered, I see a small optimization given that on my computer the information is on line 31 out of 21,980. I would return it as soon as it's found and break out of the for loop.

var serialNumber string
out, _ := exec.Command("/usr/sbin/ioreg", "-l").Output() // err ignored for brevity
for _, l := range strings.Split(string(out), "\n") {
    if strings.Contains(l, "IOPlatformSerialNumber") {
        s := strings.Split(l, " ")
        serialNumber = s[len(s)-1]
        break
    }
}

The previous answer works, but I don't like to go through 29,000 lines for nothing ! 🙂

huangapple
  • 本文由 发表于 2017年6月23日 15:07:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/44715177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定