英文:
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 ! 🙂
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论