golang---获取windows系统相关信息

Posted saryli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang---获取windows系统相关信息相关的知识,希望对你有一定的参考价值。

package main

import (
	"fmt"
	"net"
	"runtime"
	"strings"
	"syscall"
	"time"
	"unsafe"

	"github.com/StackExchange/wmi"
)

var (
	advapi = syscall.NewLazyDLL("Advapi32.dll")
	kernel = syscall.NewLazyDLL("Kernel32.dll")
)

func main() 
	fmt.Printf("开机时长:%s\n", GetStartTime())
	fmt.Printf("当前用户:%s\n", GetUserName())
	fmt.Printf("当前系统:%s\n", runtime.GOOS)
	fmt.Printf("系统版本:%s\n", GetSystemVersion())
	fmt.Printf("%s\n", GetBiosInfo())
	fmt.Printf("Motherboard:\t%s\n", GetMotherboardInfo())

	fmt.Printf("CPU:\t%s\n", GetCpuInfo())
	fmt.Printf("Memory:\t%s\n", GetMemory())
	fmt.Printf("Disk:\t%v\n", GetDiskInfo())
	fmt.Printf("Interfaces:\t%v\n", GetIntfs())


//开机时间
func GetStartTime() string 
	GetTickCount := kernel.NewProc("GetTickCount")
	r, _, _ := GetTickCount.Call()
	if r == 0 
		return ""
	
	ms := time.Duration(r * 1000 * 1000)
	return ms.String()


//当前用户名
func GetUserName() string 
	var size uint32 = 128
	var buffer = make([]uint16, size)
	user := syscall.StringToUTF16Ptr("USERNAME")
	domain := syscall.StringToUTF16Ptr("USERDOMAIN")
	r, err := syscall.GetEnvironmentVariable(user, &buffer[0], size)
	if err != nil 
		return ""
	
	buffer[r] = ‘@‘
	old := r + 1
	if old >= size 
		return syscall.UTF16ToString(buffer[:r])
	
	r, err = syscall.GetEnvironmentVariable(domain, &buffer[old], size-old)
	return syscall.UTF16ToString(buffer[:old+r])


//系统版本
func GetSystemVersion() string 
	version, err := syscall.GetVersion()
	if err != nil 
		return ""
	
	return fmt.Sprintf("%d.%d (%d)", byte(version), uint8(version>>8), version>>16)


type diskusage struct 
	Path  string `json:"path"`
	Total uint64 `json:"total"`
	Free  uint64 `json:"free"`


func usage(getDiskFreeSpaceExW *syscall.LazyProc, path string) (diskusage, error) 
	lpFreeBytesAvailable := int64(0)
	var info = diskusagePath: path
	diskret, _, err := getDiskFreeSpaceExW.Call(
		uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(info.Path))),
		uintptr(unsafe.Pointer(&lpFreeBytesAvailable)),
		uintptr(unsafe.Pointer(&(info.Total))),
		uintptr(unsafe.Pointer(&(info.Free))))
	if diskret != 0 
		err = nil
	
	return info, err


//硬盘信息
func GetDiskInfo() (infos []diskusage) 
	GetLogicalDriveStringsW := kernel.NewProc("GetLogicalDriveStringsW")
	GetDiskFreeSpaceExW := kernel.NewProc("GetDiskFreeSpaceExW")
	lpBuffer := make([]byte, 254)
	diskret, _, _ := GetLogicalDriveStringsW.Call(
		uintptr(len(lpBuffer)),
		uintptr(unsafe.Pointer(&lpBuffer[0])))
	if diskret == 0 
		return
	
	for _, v := range lpBuffer 
		if v >= 65 && v <= 90 
			path := string(v) + ":"
			if path == "A:" || path == "B:" 
				continue
			
			info, err := usage(GetDiskFreeSpaceExW, string(v)+":")
			if err != nil 
				continue
			
			infos = append(infos, info)
		
	
	return infos


//CPU信息
//简单的获取方法fmt.Sprintf("Num:%d Arch:%s\n", runtime.NumCPU(), runtime.GOARCH)
func GetCpuInfo() string 
	var size uint32 = 128
	var buffer = make([]uint16, size)
	var index = uint32(copy(buffer, syscall.StringToUTF16("Num:")) - 1)
	nums := syscall.StringToUTF16Ptr("NUMBER_OF_PROCESSORS")
	arch := syscall.StringToUTF16Ptr("PROCESSOR_ARCHITECTURE")
	r, err := syscall.GetEnvironmentVariable(nums, &buffer[index], size-index)
	if err != nil 
		return ""
	
	index += r
	index += uint32(copy(buffer[index:], syscall.StringToUTF16(" Arch:")) - 1)
	r, err = syscall.GetEnvironmentVariable(arch, &buffer[index], size-index)
	if err != nil 
		return syscall.UTF16ToString(buffer[:index])
	
	index += r
	return syscall.UTF16ToString(buffer[:index+r])


type memoryStatusEx struct 
	cbSize                  uint32
	dwMemoryLoad            uint32
	ullTotalPhys            uint64 // in bytes
	ullAvailPhys            uint64
	ullTotalPageFile        uint64
	ullAvailPageFile        uint64
	ullTotalVirtual         uint64
	ullAvailVirtual         uint64
	ullAvailExtendedVirtual uint64


//内存信息
func GetMemory() string 
	GlobalMemoryStatusEx := kernel.NewProc("GlobalMemoryStatusEx")
	var memInfo memoryStatusEx
	memInfo.cbSize = uint32(unsafe.Sizeof(memInfo))
	mem, _, _ := GlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&memInfo)))
	if mem == 0 
		return ""
	
	return fmt.Sprint(memInfo.ullTotalPhys / (1024 * 1024))


type intfInfo struct 
	Name string
	Ipv4 []string
	Ipv6 []string


//网卡信息
func GetIntfs() []intfInfo 
	intf, err := net.Interfaces()
	if err != nil 
		return []intfInfo
	
	var is = make([]intfInfo, len(intf))
	for i, v := range intf 
		ips, err := v.Addrs()
		if err != nil 
			continue
		
		is[i].Name = v.Name
		for _, ip := range ips 
			if strings.Contains(ip.String(), ":") 
				is[i].Ipv6 = append(is[i].Ipv6, ip.String())
			 else 
				is[i].Ipv4 = append(is[i].Ipv4, ip.String())
			
		
	
	return is


//主板信息
func GetMotherboardInfo() string 
	var s = []struct 
		Product string
	
	err := wmi.Query("SELECT  Product  FROM Win32_BaseBoard WHERE (Product IS NOT NULL)", &s)
	if err != nil 
		return ""
	
	return s[0].Product


//BIOS信息
func GetBiosInfo() string 
	var s = []struct 
		Name string
	
	err := wmi.Query("SELECT Name FROM Win32_BIOS WHERE (Name IS NOT NULL)", &s) // WHERE (BIOSVersion IS NOT NULL)
	if err != nil 
		return ""
	
	return s[0].Name

  输出结果:

开机时长:27h3m55.042s

当前用户:[email protected]

当前系统:windows

系统版本:6.1 (7601)

BIOS Date: 04/08/14 13:08:33 Ver: 04.06.05

Motherboard: Z97 GAMING 5 (MS-7917)

CPU: Num:8 Arch:AMD64

Memory: 16264

Disk: [C: 127928365056 69651759104 D: 858994503680 799115214848 E: 536871956480 445582901248 F: 249998340096 249896194048 G: 1141402234880 896679825408 H: 963427430400 881289777152 J: 128033222656 118774480896]

Interfaces: [Local Area Connection [192.168.6.45/24 192.168.6.100/24 192.168.6.102/24] [fe80::91f7:d107:7d92:e971/64] VMware Network Adapter VMnet1 [192.168.46.1/24] [fe80::9c79:462d:6831:8c27/64] VMware Network Adapter VMnet8 [192.168.153.1/24] [fe80::8055:efa0:615c:4814/64] Loopback Pseudo-Interface 1 [127.0.0.1/8] [::1/128] isatap.DEAC948E-CFD8-4CF7-9B40-C1AB75D37536 [] [fe80::5efe:c0a8:62d/128 fe80::5efe:c0a8:664/128 fe80::5efe:c0a8:666/128] isatap.localdomain [] [fe80::5efe:c0a8:2e01/128 fe80::5efe:c0a8:9901/128]]

 

以上是关于golang---获取windows系统相关信息的主要内容,如果未能解决你的问题,请参考以下文章

Golang实践录:获取系统信息

Golang 反射

golang windows程序获取管理员权限(UAC )

QStorageInfo获取磁盘信息(非常详细)

golang二进制文件没有在mips上运行

Golang服务器中级开发(游戏开发公司)