wmi

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2021 License: Apache-2.0 Imports: 0 Imported by: 3

README

wmi

A wrapper for local and remote Windows WMI at both low level calls to COM, and at a high level Go object mapping.

There are a number of WMI library implementations around, but not many of them provide:

  • Both local and remote access to the WMI provider
  • A single session to execute many queries
  • Low level access to the WMI API
  • High level mapping of WMI objects to Go objects
  • WMI method execution

This presently only works on Windows. If there is ever a port of the Python Impacket to Go, it would be good to have this work on Linux and MacOS as well.

Build Status GoDoc

Examples

A Simple High-Level Example to Query Win32_ComputerSystem
package main

import (
	"fmt"

	"github.com/drtimf/wmi"
)

func main() {
	var service *wmi.Service
	var err error

	if service, err = wmi.NewLocalService(wmi.RootCIMV2); err != nil {
		panic(err)
	}

	defer service.Close()

	var computerSystem wmi.Win32_ComputerSystem
	if err = service.Query("SELECT * FROM Win32_ComputerSystem", &computerSystem); err != nil {
		panic(err)
	}

	fmt.Printf("%+v\n", computerSystem)
}
A Low-Level Example to Query Win32_NetworkAdapter
package main

import (
	"fmt"

	"github.com/drtimf/wmi"
)

func main() {
	var service *wmi.Service
	var err error

	if service, err = wmi.NewLocalService(wmi.RootCIMV2); err != nil {
		panic(err)
	}

	defer service.Close()

	var enum *wmi.Enum
	if enum, err = service.ExecQuery(`SELECT InterfaceIndex, Manufacturer, MACAddress, Name FROM Win32_NetworkAdapter`); err != nil {
		panic(err)
	}

	defer enum.Close()

	for {
		var instance *wmi.Instance
		if instance, err = enum.Next(); err != nil {
			panic(err)
		}

		if instance == nil {
			break
		}

		defer instance.Close()

		var val interface{}
		var interfaceIndex int32
		var manufacturer, MACAddress, name string

		if val, _, _, err = instance.Get("InterfaceIndex"); err != nil {
			panic(err)
		}

		if val != nil {
			interfaceIndex = val.(int32)
		}

		if val, _, _, err = instance.Get("Manufacturer"); err != nil {
			panic(err)
		}

		if val != nil {
			manufacturer = val.(string)
		}

		if val, _, _, err = instance.Get("MACAddress"); err != nil {
			panic(err)
		}

		if val != nil {
			MACAddress = val.(string)
		}

		if val, _, _, err = instance.Get("Name"); err != nil {
			panic(err)
		}

		if val != nil {
			name = val.(string)
		}

		fmt.Printf("%6d %-25s%20s\t%s\n", interfaceIndex, manufacturer, MACAddress, name)
	}
}

Usage

Objects in this API include a Close() method which should be called when the object is no longer required. This is important as it invokes the COM Release() to free the resources memory.

There are three high level objects:

  • Service: A connection to either a local or remote WMI service
  • Enum: An enumerator of WMI instances
  • Instance: An instance of a WMI class
Open a Connection to a WMI Service and Namespace

In each case a new *wmi.Service is created which can be used to obtain class instances and execute queries.

Open a connection to a local WMI service

func NewLocalService(namespace string) (s *Service, err error)

Open a connection to a remote WMI service with a username and a password:

func NewRemoteService(server string, namespace string, username string, password string) (s *Service, err error)

Create a new service that has the specified child namespace as its operating context. All operations through the new service, such as class or instance creation, only affect that namespace. The namespace must be a child namespace of the current object through which this method is called.

func (s *Service) OpenNamespace(namespace string) (newService *Service, err error)
Get a Single WMI Object

Obtain a single WMI class or instance given its path:

func (s *Service) GetObject(objectPath string) (instance *Instance, err error)
Query WMI Objects

Obtain a WMI enumerator that returns the instances of a specified class:

func (s *Service) CreateInstanceEnum(className string) (e *Enum, err error)

Enumerate a WMI class of a given name and map the objects to a structure or slice of structures:

func (s *Service) ClassInstances(className string, dst interface{}) (err error)

Execute a WMI Query Language (WQL) query and return a WMI enumerator for the queried class instances:

func (s *Service) ExecQuery(wqlQuery string) (e *Enum, err error)

Execute a WMI Query Language (WQL) query and map the results to a structure or slice of structures:

func (s *Service) Query(query string, dst interface{}) (err error)

The destination must be a pointer to a struct:

var dst Win32_ComputerSystem
err = service.Query("SELECT * FROM Win32_ComputerSystem", &dst)

Or a pointer to a slice:

var dst []CIM_DataFile
err = service.Query(`SELECT * FROM CIM_DataFile WHERE Drive = 'C:' AND Path = '\\'`, &dst)
Execute a WMI Method

Execute a method exported by a CIM object:

func (s *Service) ExecMethod(className string, methodName string, inParams *Instance) (outParam *Instance, err error)

The method call is forwarded to the appropriate provider where it executes. Information and status are returned to the caller, which blocks until the call is complete.

Enumerate WMI objects

Obtain the next WMI instance from a WMI enumerator:

func (e *Enum) Next() (instance *Instance, err error)

Obtain the next WMI instance from a WMI enumerator and map it to a Go object:

func (e *Enum) NextObject(dst interface{}) (done bool, err error)
Create Class Instances

Create a new instance of a WMI class:

func (i *Instance) SpawnInstance() (instance *Instance, err error)

The current object must be a class definition obtained from WMI using GetObject or CreateClassEnum.

Get Properties of a WMI Instance

Obtain the class name of the WMI instance:

func (i *Instance) GetClassName() (className string, err error)

Retrieve the names of the properties in the WMI instance:

func (i *Instance) GetNames() (names []string, err error)

Obtain a specified property value, if it exists:

func (i *Instance) Get(name string) (value interface{}, cimType CIMTYPE_ENUMERATION, flavor WBEM_FLAVOR_TYPE, err error)

Obtain a specificed property value as a string:

func (i *Instance) GetPropertyAsString(name string) (value string, err error)

Reset an enumeration of instance properties back to the beginning of the enumeration:

func (i *Instance) BeginEnumeration() (err error)

This must be called prior to the first call to Next to enumerate all of the properties on an object.

Retrieves the next property in an enumeration as a variant that started with BeginEnumeration:

func (i *Instance) NextAsVariant() (done bool, name string, value *ole.VARIANT, cimType CIMTYPE_ENUMERATION, flavor WBEM_FLAVOR_TYPE, err error)

This should be called repeatedly to enumerate all the properties until done returns true. If the enumeration is to be terminated early, then EndEnumeration should be called.

Retrieve the next property in an enumeration as a Go value that started with BeginEnumeration:

func (i *Instance) Next() (done bool, name string, value interface{}, cimType CIMTYPE_ENUMERATION, flavor WBEM_FLAVOR_TYPE, err error)

Terminate an enumeration sequence started with BeginEnumeration:

func (i *Instance) EndEnumeration() (err error)

This call is not required, but it is recommended because it releases resources associated with the enumeration. However, the resources are deallocated automatically when the next enumeration is started or the object is released.

Return all the properties and their values for the WMI instance

func (i *Instance) GetProperties() (properties []Property, err error)
Set Properties for a WMI Instance

Set a named property to a new value:

func (i *Instance) Put(name string, value interface{}) (err error)

This always overwrites the current value with a new one. When the instance is a CIM class definition, Put creates or updates the property value. When the instance is a CIM instance, Put updates a property value only. Put cannot create a property value.

Methods of a WMI Instance

Begin an enumeration of the methods available for the instance:

func (i *Instance) BeginMethodEnumeration() (err error)

Retrieve the next method in a method enumeration sequence that starts with a call to BeginMethodEnumeration:

func (i *Instance) NextMethod() (done bool, name string, err error)

Terminate a method enumeration sequence started with BeginMethodEnumeration:

func (i *Instance) EndMethodEnumeration() (err error)

Obtain all the method names for the WMI instance:

func (i *Instance) GetMethods() (methodNames []string, err error)

Obtain information about the requested method:

func (i *Instance) GetMethod(methodName string) (inSignature *Instance, outSignature *Instance, err error)

This is only supported if the current instance is a CIM class definition. Method information is not available from instances which are CIM instances.

Obtain the input parameters of a method so they can be filled out for calling the method:

func (i *Instance) GetMethodParameters(methodName string) (inParam *Instance, err error)

This is a variation of GetMethod which only returns in input parameters.

Documentation

Overview

+build windows

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CIM_DataFile

type CIM_DataFile struct {
	Caption               string
	Description           string
	InstallDate           string
	Status                string
	AccessMask            uint32
	Archive               bool
	Compressed            bool
	CompressionMethod     string
	CreationClassName     string
	CreationDate          string
	CSCreationClassName   string
	CSName                string
	Drive                 string
	EightDotThreeFileName string
	Encrypted             bool
	EncryptionMethod      string
	Name                  string
	Extension             string
	FileName              string
	FileSize              uint64
	FileType              string
	FSCreationClassName   string
	FSName                string
	Hidden                bool
	InUseCount            uint64
	LastAccessed          string
	LastModified          string
	Path                  string
	Readable              bool
	System                bool
	Writeable             bool
	Manufacturer          string
	Version               string
}

CIM_DataFile WMI class

type Win32_BIOS

type Win32_BIOS struct {
	BiosCharacteristics            []uint16
	BIOSVersion                    []string
	BuildNumber                    string
	Caption                        string
	CodeSet                        string
	CurrentLanguage                string
	Description                    string
	EmbeddedControllerMajorVersion uint8
	EmbeddedControllerMinorVersion uint8
	IdentificationCode             string
	InstallableLanguages           uint16
	InstallDate                    string
	LanguageEdition                string
	ListOfLanguages                []string
	Manufacturer                   string
	Name                           string
	OtherTargetOS                  string
	PrimaryBIOS                    bool
	ReleaseDate                    string
	SerialNumber                   string
	SMBIOSBIOSVersion              string
	SMBIOSMajorVersion             uint16
	SMBIOSMinorVersion             uint16
	SMBIOSPresent                  bool
	SoftwareElementID              string
	SoftwareElementState           uint16
	Status                         string
	SystemBiosMajorVersion         uint8
	SystemBiosMinorVersion         uint8
	TargetOperatingSystem          uint16
	Version                        string
}

Win32_BIOS WMI class

type Win32_ComputerSystem

type Win32_ComputerSystem struct {
	AdminPasswordStatus         uint16
	AutomaticManagedPagefile    bool
	AutomaticResetBootOption    bool
	AutomaticResetCapability    bool
	BootOptionOnLimit           uint16
	BootOptionOnWatchDog        uint16
	BootROMSupported            bool
	BootupState                 string
	BootStatus                  []uint16
	Caption                     string
	ChassisBootupState          uint16
	ChassisSKUNumber            string
	CreationClassName           string
	CurrentTimeZone             int16
	DaylightInEffect            bool
	Description                 string
	DNSHostName                 string
	Domain                      string
	DomainRole                  uint16
	EnableDaylightSavingsTime   bool
	FrontPanelResetStatus       uint16
	HypervisorPresent           bool
	InfraredSupported           bool
	InitialLoadInfo             []string
	InstallDate                 string
	KeyboardPasswordStatus      uint16
	LastLoadInfo                string
	Manufacturer                string
	Model                       string
	Name                        string
	NameFormat                  string
	NetworkServerModeEnabled    bool
	NumberOfLogicalProcessors   uint32
	NumberOfProcessors          uint32
	OEMLogoBitmap               []uint8
	OEMStringArray              []string
	PartOfDomain                bool
	PauseAfterReset             int64
	PCSystemType                uint16
	PCSystemTypeEx              uint16
	PowerManagementCapabilities []uint16
	PowerManagementSupported    bool
	PowerOnPasswordStatus       uint16
	PowerState                  uint16
	PowerSupplyState            uint16
	PrimaryOwnerContact         string
	PrimaryOwnerName            string
	ResetCapability             uint16
	ResetCount                  int16
	ResetLimit                  int16
	Roles                       []string
	Status                      string
	SupportContactDescription   []string
	SystemFamily                string
	SystemSKUNumber             string
	SystemStartupDelay          uint16
	SystemStartupOptions        []string
	SystemStartupSetting        uint8
	SystemType                  string
	ThermalState                uint16
	TotalPhysicalMemory         uint64
	UserName                    string
	WakeUpType                  uint16
	Workgroup                   string
}

Win32_ComputerSystem WMI class

type Win32_ComputerSystemProduct

type Win32_ComputerSystemProduct struct {
	Caption           string
	Description       string
	IdentifyingNumber string
	Name              string
	SKUNumber         string
	Vendor            string
	Version           string
	UUID              string
}

Win32_ComputerSystemProduct WMI class

type Win32_Directory

type Win32_Directory struct {
	Caption               string
	Description           string
	InstallDate           string
	Name                  string
	Status                string
	AccessMask            uint32
	Archive               bool
	Compressed            bool
	CompressionMethod     string
	CreationClassName     string
	CreationDate          string
	CSCreationClassName   string
	CSName                string
	Drive                 string
	EightDotThreeFileName string
	Encrypted             bool
	EncryptionMethod      string
	Extension             string
	FileName              string
	FileSize              uint64
	FileType              string
	FSCreationClassName   string
	FSName                string
	Hidden                bool
	InUseCount            uint64
	LastAccessed          string
	LastModified          string
	Path                  string
	Readable              bool
	System                bool
	Writeable             bool
}

Win32_Directory WMI class

type Win32_DiskDrive

type Win32_DiskDrive struct {
	Availability                uint16
	BytesPerSector              uint32
	Capabilities                []uint16
	CapabilityDescriptions      []string
	Caption                     string
	CompressionMethod           string
	ConfigManagerErrorCode      uint32
	ConfigManagerUserConfig     bool
	CreationClassName           string
	DefaultBlockSize            uint64
	Description                 string
	DeviceID                    string
	ErrorCleared                bool
	ErrorDescription            string
	ErrorMethodology            string
	FirmwareRevision            string
	Index                       uint32
	InstallDate                 string
	InterfaceType               string
	LastErrorCode               uint32
	Manufacturer                string
	MaxBlockSize                uint64
	MaxMediaSize                uint64
	MediaLoaded                 bool
	MediaType                   string
	MinBlockSize                uint64
	Model                       string
	Name                        string
	NeedsCleaning               bool
	NumberOfMediaSupported      uint32
	Partitions                  uint32
	PNPDeviceID                 string
	PowerManagementCapabilities []uint16
	PowerManagementSupported    bool
	SCSIBus                     uint32
	SCSILogicalUnit             uint16
	SCSIPort                    uint16
	SCSITargetId                uint16
	SectorsPerTrack             uint32
	SerialNumber                string
	Signature                   uint32
	Size                        uint64
	Status                      string
	StatusInfo                  uint16
	SystemCreationClassName     string
	SystemName                  string
	TotalCylinders              uint64
	TotalHeads                  uint32
	TotalSectors                uint64
	TotalTracks                 uint64
	TracksPerCylinder           uint32
}

Win32_DiskDrive WMI class

type Win32_NetworkAdapter

type Win32_NetworkAdapter struct {
	AdapterType                 string
	AdapterTypeID               uint16
	AutoSense                   bool
	Availability                uint16
	Caption                     string
	ConfigManagerErrorCode      uint32
	ConfigManagerUserConfig     bool
	CreationClassName           string
	Description                 string
	DeviceID                    string
	ErrorCleared                bool
	ErrorDescription            string
	GUID                        string
	Index                       uint32
	InstallDate                 string
	Installed                   bool
	InterfaceIndex              uint32
	LastErrorCode               uint32
	MACAddress                  string
	Manufacturer                string
	MaxNumberControlled         uint32
	MaxSpeed                    uint64
	Name                        string
	NetConnectionID             string
	NetConnectionStatus         uint16
	NetEnabled                  bool
	NetworkAddresses            []string
	PermanentAddress            string
	PhysicalAdapter             bool
	PNPDeviceID                 string
	PowerManagementCapabilities []uint16
	PowerManagementSupported    bool
	ProductName                 string
	ServiceName                 string
	Speed                       uint64
	Status                      string
	StatusInfo                  uint16
	SystemCreationClassName     string
	SystemName                  string
	TimeOfLastReset             string
}

Win32_NetworkAdapter WMI class

type Win32_OperatingSystem

type Win32_OperatingSystem struct {
	BootDevice                                string
	BuildNumber                               string
	BuildType                                 string
	Caption                                   string
	CodeSet                                   string
	CountryCode                               string
	CreationClassName                         string
	CSCreationClassName                       string
	CSDVersion                                string
	CSName                                    string
	CurrentTimeZone                           int16
	DataExecutionPrevention_Available         bool
	DataExecutionPrevention_32BitApplications bool
	DataExecutionPrevention_Drivers           bool
	DataExecutionPrevention_SupportPolicy     uint8
	Debug                                     bool
	Description                               string
	Distributed                               bool
	EncryptionLevel                           uint32
	ForegroundApplicationBoost                uint8
	FreePhysicalMemory                        uint64
	FreeSpaceInPagingFiles                    uint64
	FreeVirtualMemory                         uint64
	InstallDate                               string
	LargeSystemCache                          uint32
	LastBootUpTime                            string
	LocalDateTime                             string
	Locale                                    string
	Manufacturer                              string
	MaxNumberOfProcesses                      uint32
	MaxProcessMemorySize                      uint64
	MUILanguages                              []string
	Name                                      string
	NumberOfLicensedUsers                     uint32
	NumberOfProcesses                         uint32
	NumberOfUsers                             uint32
	OperatingSystemSKU                        uint32
	Organization                              string
	OSArchitecture                            string
	OSLanguage                                uint32
	OSProductSuite                            uint32
	OSType                                    uint16
	OtherTypeDescription                      string
	PAEEnabled                                bool
	PlusProductID                             string
	PlusVersionNumber                         string
	PortableOperatingSystem                   bool
	Primary                                   bool
	ProductType                               uint32
	RegisteredUser                            string
	SerialNumber                              string
	ServicePackMajorVersion                   uint16
	ServicePackMinorVersion                   uint16
	SizeStoredInPagingFiles                   uint64
	Status                                    string
	SuiteMask                                 uint32
	SystemDevice                              string
	SystemDirectory                           string
	SystemDrive                               string
	TotalSwapSpaceSize                        uint64
	TotalVirtualMemorySize                    uint64
	TotalVisibleMemorySize                    uint64
	Version                                   string
	WindowsDirectory                          string
	QuantumLength                             uint8
	QuantumType                               uint8
}

Win32_OperatingSystem WMI class

type Win32_Process

type Win32_Process struct {
	CreationClassName          string
	Caption                    string
	CommandLine                string
	CreationDate               string
	CSCreationClassName        string
	CSName                     string
	Description                string
	ExecutablePath             string
	ExecutionState             uint16
	Handle                     string
	HandleCount                uint32
	InstallDate                string
	KernelModeTime             uint64
	MaximumWorkingSetSize      uint32
	MinimumWorkingSetSize      uint32
	Name                       string
	OSCreationClassName        string
	OSName                     string
	OtherOperationCount        uint64
	OtherTransferCount         uint64
	PageFaults                 uint32
	PageFileUsage              uint32
	ParentProcessId            uint32
	PeakPageFileUsage          uint32
	PeakVirtualSize            uint64
	PeakWorkingSetSize         uint32
	Priority                   uint32
	PrivatePageCount           uint64
	ProcessId                  uint32
	QuotaNonPagedPoolUsage     uint32
	QuotaPagedPoolUsage        uint32
	QuotaPeakNonPagedPoolUsage uint32
	QuotaPeakPagedPoolUsage    uint32
	ReadOperationCount         uint64
	ReadTransferCount          uint64
	SessionId                  uint32
	Status                     string
	TerminationDate            string
	ThreadCount                uint32
	UserModeTime               uint64
	VirtualSize                uint64
	WindowsVersion             string
	WorkingSetSize             uint64
	WriteOperationCount        uint64
	WriteTransferCount         uint64
}

Win32_Process WMI class

type Win32_Processor

type Win32_Processor struct {
	AddressWidth                            uint16
	Architecture                            uint16
	AssetTag                                string
	Availability                            uint16
	Caption                                 string
	Characteristics                         uint32
	ConfigManagerErrorCode                  uint32
	ConfigManagerUserConfig                 bool
	CpuStatus                               uint16
	CreationClassName                       string
	CurrentClockSpeed                       uint32
	CurrentVoltage                          uint16
	DataWidth                               uint16
	Description                             string
	DeviceID                                string
	ErrorCleared                            bool
	ErrorDescription                        string
	ExtClock                                uint32
	Family                                  uint16
	InstallDate                             string
	L2CacheSize                             uint32
	L2CacheSpeed                            uint32
	L3CacheSize                             uint32
	L3CacheSpeed                            uint32
	LastErrorCode                           uint32
	Level                                   uint16
	LoadPercentage                          uint16
	Manufacturer                            string
	MaxClockSpeed                           uint32
	Name                                    string
	NumberOfCores                           uint32
	NumberOfEnabledCore                     uint32
	NumberOfLogicalProcessors               uint32
	OtherFamilyDescription                  string
	PartNumber                              string
	PNPDeviceID                             string
	PowerManagementCapabilities             []uint16
	PowerManagementSupported                bool
	ProcessorId                             string
	ProcessorType                           uint16
	Revision                                uint16
	Role                                    string
	SecondLevelAddressTranslationExtensions bool
	SerialNumber                            string
	SocketDesignation                       string
	Status                                  string
	StatusInfo                              uint16
	Stepping                                string
	SystemCreationClassName                 string
	SystemName                              string
	ThreadCount                             uint32
	UniqueId                                string
	UpgradeMethod                           uint16
	Version                                 string
	VirtualizationFirmwareEnabled           bool
	VMMonitorModeExtensions                 bool
	VoltageCaps                             uint32
}

Win32_Processor WMI class

type Win32_Product

type Win32_Product struct {
	AssignmentType    uint16
	Caption           string
	Description       string
	IdentifyingNumber string
	InstallDate       string
	InstallDate2      string
	InstallLocation   string
	InstallState      int16
	HelpLink          string
	HelpTelephone     string
	InstallSource     string
	Language          string
	LocalPackage      string
	Name              string
	PackageCache      string
	PackageCode       string
	PackageName       string
	ProductID         string
	RegOwner          string
	RegCompany        string
	SKUNumber         string
	Transforms        string
	URLInfoAbout      string
	URLUpdateInfo     string
	Vendor            string
	WordCount         uint32
	Version           string
}

Win32_Product WMI class

type Win32_Registry

type Win32_Registry struct {
	Caption      string
	Description  string
	InstallDate  string
	Status       string
	CurrentSize  uint32
	MaximumSize  uint32
	Name         string
	ProposedSize uint32
}

Win32_Registry WMI class

Directories

Path Synopsis
example
network_adapter command
root_namespace command
simple command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL