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 = diskusage{Path: 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]}]

原文地址:https://www.cnblogs.com/saryli/p/11119033.html

时间: 2024-11-05 02:34:52

golang---获取windows系统相关信息的相关文章

获取Java系统相关信息

1 package com.test; 2 3 import java.util.Properties; 4 import java.util.Map.Entry; 5 6 import org.junit.Test; 7 8 public class SystemTest { 9 10 /** 11 * 获取Java系统相关信息 12 * @throws Exception 13 */ 14 @Test 15 public void testSys() throws Exception { 1

这段百度问答,对我相关有对啊!!!----如何获取Windows系统登陆用户名

如何获取Windows系统登陆用户名 http://zhidao.baidu.com/link?url=Hva9PkVwYZv8KSEWftSqTWe8fqM1dhoq59BurnfADmcOvFjFgJUONb2kQ4KrJUF5KjOTXjCf5SQKYNLhcU_dBMzGGBxFxJCRfxCmamIjUji ======================= 一般用 GetUserName(或 GetUserNameEx )函数可得到当前登陆登陆用户名(但不总会得到,下面会分析),此系统函

Linux sysinfo获取系统相关信息

Linux中,可以用sysinfo来获取系统相关信息. #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <linux/unistd.h> /* for _syscallX macros/related stuff */ #include <linux/kernel.h> /* for struct sysinfo */ //_syscall1(int, sysi

[源码]一键获取windows系统登陆密码vc6版源码

[源码]一键获取windows系统登陆密码vc6版源码支持:XP/2000/2003/WIN7/2008等 此版本编译出来的程序体积较小几十KB... 而vs版则1点几M,体积整整大了2-30倍对某些奇葩环境...1点几M可能要分几十次传过去 总是在关键的时候,发现自己以前弄过的东西突然不见了然后百度好不容易找到了一份..还是发到博客来 收藏需要修改输出TXT的或免杀啥的...上自己博客找源码 #include <windows.h>#include <stdio.h> // //

通过PowerShell获取Windows系统密码Hash

当你拿到了系统控制权之后如何才能更长的时间内控制已经拿到这台机器呢?作为白帽子,已经在对手防线上撕开一个口子,如果你需要进一步扩大战果,你首先需要做的就是潜伏下来,收集更多的信息便于你判断,便于有更大的收获.用什么方法才能有尽可能高的权限,同时能更有效的隐藏自己,是留webshell,留后门,种木马还是Rootkit?webshell,哪怕是一句话木马都很容易被管理员清除,放了木马,也容易被有经验的管理员查出,不管是早期自己创建进程,进程被干掉就完了,还是注入进程的木马,或者是以服务自启动的木马

Linux下使用fstatfs/statfs查询系统相关信息

Linux下使用fstatfs/statfs查询系统相关信息 1.   功能 #include < sys/statfs.h > int statfs(const char *path, struct statfs *buf); int fstatfs(int fd, struct statfs *buf); 查询文件系统相关的信息. 2.   參数 path: 须要查询信息的文件系统的文件路径名. fd: 须要查询信息的文件系统的文件描写叙述符. buf:下面结构体的指针变量,用于储存文件系

使用C语言获取linux系统相关信息

最近在写shell的时候,涉及到了获取环境变量参数和本地计算机相关信息,包括计算机设备名,用户名的信息,在这里简单总结一下.获取环境变量各项参数,可以直接使用getenv函数.man中关于getenv函数的声明如下: #include <stdlib.h> char *getenv(const char *name); 函数中,参数name 为环境变量的名称, 如果该变量存在则会返回指向该内容的指针. 环境变量的格式为name=value.执行成功则返回指向该内容的指针, 找不到符合的环境变量

C#:获取设备电量相关信息

[DllImport("kernel32.dll",EntryPoint="GetSystemPowerStatus")] //win32 api private static extern void GetSystemPowerStatus(ref SYSTEM_POWER_STATUS lpSystemPowerStatus); public struct SYSTEM_POWER_STATUS //结构体 { public Byte ACLineStatus;

C#获取程序文件相关信息的方法

本文实例讲述了C#获取程序文件相关信息的方法,分享给大家供大家参考. 具体实现方法如下: using System.Reflection; using System.Runtime.CompilerServices; // // 有关程序集的常规信息是通过下列 // 属性集控制的.更改这些属性值可修改与程序集 // 关联的信息. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")]