Code Monkey home page Code Monkey logo

wmi's Introduction

wmi

Package wmi provides a WQL interface to Windows WMI.

Note: It interfaces with WMI on the local machine, therefore it only runs on Windows.


NOTE: This project is no longer being actively maintained.

We recommend you refer to this fork: https://github.com/yusufpapurcu/wmi


wmi's People

Contributors

captncraig avatar czxcc avatar gbrayut avatar gesquive avatar kylebrandt avatar maddyblue avatar marianob85 avatar martinlindhe avatar mholt avatar mikewalker125 avatar mnewswanger avatar sokoloffa avatar st0nie avatar stefanschneider avatar stevenh avatar tlimoncelli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wmi's Issues

Hang on initial Query on older windows (pre-2016)

I haven't been able to write a succinct test case for this, but it's very reproducible in the context i'm running into it: a go binary windows service that uses https://github.com/shirou/gopsutil to gather cpu usage info. On first service start, the service is killed after the service timeout (30 seconds is the default, but after upping it to 70 seconds the hang persisted). Subsequent service starts work as expected. This behavior is the same whether the service is started by the system automatically, or with Start-Service in a privileged prompt.

Adding a 2-second timeout around the initial call to
DefaultClient.Query(query, dst, connectServerArgs...) seems to work around the problem (by failing the initial query, returning an error, and then working on subsequent calls).

Wmi class names invalid for golint

Hi,

First, thanks a lot for this library, it's pretty useful to access easily data through wmi query.

We have one issue with some wmi class (Win32_Fan in our case, but basically most of class) as the class name is invalid for golint as it contains an underscore. That's a blocker as CreateQuery use the type name to build the query.
This PR : #24 gives a solution to that, would it be possible to merge it?

Cheers,
Moe

Invoke the method of the class

How to call the method of the class
For example, Win32_NetworkAdapterConfiguration SetDNSServerSearchOrder

The following method is invalid
_, err = wmi.CallMethod([]interface{}{}, fmt.Sprintf(Win32_NetworkAdapterConfiguration.ServiceName="%s", iName), "SetDNSServerSearchOrder", params)
//

Invalid object path

Memory Leak

Hi,
I'm facing memory leak issues when querying the Windows Event Log through this lib.

I'm new to Golang so properly I'm just doing something wrong. I found the issues #27 and #3 and maybe there is still a memory issue around.

I created a little code snip you can execute which shows the issue: https://github.com/nook24/wmi_windows_eventlog/blob/main/main.go

This Code is running on Windows Server 2016

Bildschirmfoto 2021-03-22 um 17 30 02

Even if the numbers are different from what Task Manager reports the memory usage is rising in Task Manager as well.

memleak

[Helper] WMI Date to datetime conversion

There are some WMI properties like "Win32_PnPSignedDriver.DriverDate" or "Win32_OperatingSystem.InstallDate" and they are in WMI Date format.

Library detects them as string value. So if you need to convert it to golang date time, you can use following conversion:

func wmiDateToDate(s string) (time.Time, bool) {
	// yyyymmddhhnnss.zzzzzzsUUU  +60 means 60 mins of UTC time
	// 20030709091030.686000+060
	// 1234567890123456789012345

	// Check if value is WMI date
	if len(s) != 25 {
		return time.Time{}, false
	}

	// Check if value is WMI date
	wmiDate := strings.Split(s, ".")
	if len(wmiDate) != 2 {
		return time.Time{}, false
	}

	// Process Full Date
	layout := "20060102150405"
	t, err := time.Parse(layout, wmiDate[0])
	if err != nil {
		return time.Time{}, false
	}

	return t, true
}

I will close this issue so if someone searches it in the future, they can use the function.

safeArray.ToValueArray undefined

C:\...\src\project>go run main.go
# project/vendor/github.com/StackExchange/wmi
vendor\github.com\StackExchange\wmi\wmi.go:377:22: safeArray.ToValueArray undefined (type *ole.SafeArrayConversion has no field or method ToValueArray)

Getting "Not supported" as the error code when querying for data running as a windows service

Hi There,

Well, I am stumped. When I run the software from the command line, everything works properly. When I run the software as a windows service, I'll get the following line

2018-08-27T14:37:26Z I! ERROR [wmi.query]: Exception occurred. (Not supported )

I've tried running the service as both Administrator, as well as Local System. Both have the same results. I've changed the permissions for WMI to be open to everything. Still, no dice.

Ideas?

Tag new release?

Hi, thank you for making and maintaining this library.

Is there any way you could tag a new release?

I'm particularly concerned about this commit not being in the latest release, but maybe I'm misunderstanding it:

b12b22c

I like using semantic versions where possible so I'd really appreciate it.

Thank you!

Global mutex necessary?

Hi,

Thanks for this tool. Can you confirm why this global mutex is necessary? It was hampering efforts at parallelism. Is it strictly necessary if you are the querying wmi services on remote hosts?

safeArray.ToValueArray undefined

Hi,

I'm getting the following error when trying to compile an application using this package.

vendor\github.com\StackExchange\wmi\wmi.go:377: safeArray.ToValueArray undefined (type *ole.SafeArrayConversion has no field or method ToValueArray)

I've used this package in the past and the same message hasn't appeared previously.

For reference I'm using Glide to import dependencies, and am using the following versions of this package and go-ole.

  • stackexchange/wmi : commit ea383cf3ba6ec950874b8486cd72356d007c768f
  • go-ole : 1.2.0

Has anyone come across this issue before?

thanks.

Checksum Mismatch

Hello!

While fetching a Golang lib that depends on this one, I encountered a warning that indicated a mismatch between the checksum downloaded, and that of the checksum server:

$ go get github.com/StackExchange/wmi
github.com/StackExchange/[email protected]: verifying module: checksum mismatch
        downloaded: h1:BfLCNdXnvwgy5RrRI3IyQ64ZItZngXHN+7PxU5RvKxA=
        sum.golang.org: h1:noJEYkMQVlFCEAc+2ma5YyRhlfjcWfZqk5sBRYozdyM=

SECURITY ERROR
This download does NOT match the one reported by the checksum server.
The bits may have been replaced on the origin server, or an attacker may
have intercepted the download attempt.

I know this project is no longer maintained, but if this is a security issue, figured it was worth bringing it up anyway. Thanks yall

get package Failed

go get github.com/StackExchange/wmi failed, the error is:

go: github.com/StackExchange/wmi upgrade => v0.0.0-20210708210415-b284ef6ab838
go get: github.com/StackExchange/[email protected]: parsing go.mod:
module declares its path as: wmi
but was required as: github.com/StackExchange/wmi

can you help me fix up this ?

tests doesn't run on Windows XP

--- FAIL: TestQuery (0.08s)
    wmi_test.go:21: Unknown name.
--- FAIL: TestFieldMismatch (0.03s)
    wmi_test.go:34: Expected err field mismatch
Disabling GC
--- FAIL: TestStrings (0.07s)
    wmi_test.go:47: Unknown name. SELECT CSCreationClassName, CSName, Caption, CommandLine, CreationClassName, CreationDate, Description, ExecutablePath, ExecutionState, Handle, HandleCount, InstallDate, KernelModeTime, MaximumWorkingSetSize, MinimumWorkingSetSize, Name, OSCreationClassName, OSName, OtherOperationCount, OtherTransferCount, PageFaults, PageFileUsage, ParentProcessId, PeakPageFileUsage, PeakVirtualSize, PeakWorkingSetSize, Priority, PrivatePageCount, ProcessId, QuotaNonPagedPoolUsage, QuotaPagedPoolUsage, QuotaPeakNonPagedPoolUsage, QuotaPeakPagedPoolUsage, ReadOperationCount, ReadTransferCount, SessionId, Status, TerminationDate, ThreadCount, UserModeTime, VirtualSize, WindowsVersion, WorkingSetSize, WriteOperationCount, WriteTransferCount FROM Win32_Process 
--- FAIL: TestNamespace (0.04s)
    wmi_test.go:87: Unknown name.
FAIL
exit status 1
FAIL    github.com/StackExchange/wmi    0.351s

Windows XP
go version go1.4.2 windows/386

The tests works on Windows 7 64-bit.

Tag a 1.0.0 release please

It seems like this package is pretty stable. It would be helpful if you could tag a 1.0.0 release with "git tag 1.0.0 && git push --tags" so that if you want to make breaking API changes later, my dep will stay locked on 1.0.x. Thanks.

SWbemObjectSet does not have ItemIndex on some systems

SWbemObjectSet does not have ItemIndex on my system (windows xp).

//
// Dispatch ISWbemObjectSet 0.0:
// A collection of Classes or Instances
// {76A6415F-CB41-11D1-8B02-00600806D9B6}
//
0: QueryInterface(riid _GUID /in/, ppvObj *_VT_VOID /out/) VT_VOID
1: AddRef() VT_UI4
2: Release() VT_UI4
3: GetTypeInfoCount(pctinfo _VT_UINT /out/) VT_VOID
4: GetTypeInfo(itinfo VT_UINT /in/, lcid VT_UI4 /in/, pptinfo *_VT_VOID /out/) VT_VOID
5: GetIDsOfNames(riid _GUID /in/, rgszNames *_VT_I1 /in/, cNames VT_UINT /in/, lcid VT_UI4 /in/, rgdispid VT_I4 /out/) VT_VOID
6: Invoke(dispidMember VT_I4 /in/, riid *GUID /in/, lcid VT_UI4 /in/, wFlags VT_UI2 /in/, pdispparams *DISPPARAMS /in/, pvarResult *VT_VARIANT /out/, pexcepinfo *EXCEPINFO /out/, puArgErr VT_UINT /out/) VT_VOID
7: get _NewEnum() VT_UNKNOWN
// Get an Object with a specific path from this collection
8: Item(strObjectPath VT_BSTR /in/, iFlags VT_I4 /_in,opt,def
/) *ISWbemObject
// The number of items in this collection
9: get Count() VT_I4
// The Security Configurator for this Object
10: get Security
() *ISWbemSecurity

I think you should use _NewEnum instead. But I am not expert.

Above from: https://code.google.com/p/go/issues/detail?id=8293#c8

failed to print string array

I am trying to print the gateway of each NetAdapter by following code,
It print [] for all netadapters, not sure if this is a bug.

package main

import "github.com/StackExchange/wmi"
import "fmt"

// https://msdn.microsoft.com/en-us/library/aa394217(v=vs.85).aspx
type Win32_NetworkAdapterConfiguration struct {
	IPAddress []string
	DHCPServer string
	MACAddress string
	DefaultIPGateway []string
}

func main() {
	var dst2 []Win32_NetworkAdapterConfiguration
	query := fmt.Sprintf("")
	q := wmi.CreateQuery(&dst2, query)
	err := wmi.Query(q, &dst2)
	if err != nil {
		fmt.Println(err)
	}
	for _, v := range dst2 {
		fmt.Println(v.MACAddress, v.IPAddress, v.DHCPServer, v.DefaultIPGateway)
	}	
}

Issue with string field in WMI class, if no value results in error "string": unsupported type (<nil>)

I am retrieving OS Info using StackExchange/wmi package and getting error on windows machine where there is no service pack. Error is "wmi: cannot load field "CSDVersion" into a "string": unsupported type ()". So issue with CSDVersion which is string field and if there is no value then returning error, https://github.com/StackExchange/wmi/blob/master/wmi.go#L395.

To fix this we should move to next field instead of returning error. Let me know your thought on this.

Below is go code snippet.

type Win32_OperatingSystem struct {
Caption string
Version string
CSDVersion string
OSArchitecture string
Manufacturer string
SerialNumber string
InstallDate time.Time
}

// GetOSInfo returns OS information using wmi
func GetOSInfo() (Win32_OperatingSystem, error) {
var dst []Win32_OperatingSystem
q := wmi.CreateQuery(&dst, "")
err := wmi.Query(q, &dst)
if err != nil {
return Win32_OperatingSystem{}, err
}
return dst[0], nil
}

Memory leak

There's a memory leak. Run WMI queries in a loop and it'll just go up. My guess is the syscalls allocate memory but then don't free it when done.

Support for calling methods on WMI Classes

In addition to WMI queries it would be very helpful if I could call specific methods on WMI classes. This would allow access to a bunch of things that cannot be directly accessed via WQL. For instance, the following Powershell can be used to call a WMI method on a class to get details about DSC (Run on ny-rdp01 for example).

$Result = Invoke-WmiMethod -Class MSFT_DSCLocalConfigurationManager -Namespace ROOT\Microsoft\Windows\DesiredStateConfiguration -Name GetConfigurationStatus 
$Result.ConfigurationStatus #Instance of MSFT_DSCConfigurationStatus

I would like to to be able to create a MSFT_DSCConfigurationStatus struct in go that has the properties I want, then populate that struct using something like the current wmi.Query function.

Looking at the current code this should be possible using SWbemObject and SWbemMethod

I'll see if I am able to create something that works and then create a pull request for discussion.

Invalid class when querying Win32_Process

As part of troubleshooting an issue encountered with wmi_exporter, I tried running the provided code example which queries Win32_Process:

package main

import (
	"github.com/StackExchange/wmi"
	"log"
)

type Win32_Process struct {
	Name string
}

func main() {
	var dst []Win32_Process
	q := wmi.CreateQuery(&dst, "")
	err := wmi.Query(q, &dst)
	if err != nil {
		log.Fatal(err)
	}
	for i, v := range dst {
		println(i, v.Name)
	}
}

It fails on an instance of Windows Server 2012 Standard, 64-bit with the following error:

2019/09/05 10:32:37 Exception occurred. (Invalid class )

However the following PowerShell snippet works:

Get-WmiObject -Query "SELECT Name FROM Win32_Process"

The output looks like:

__GENUS          : 2
__CLASS          : Win32_Process
__SUPERCLASS     :
__DYNASTY        :
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
Name             : System Idle Process
PSComputerName   :
...

In addition, if I run

winmgmt /verifyrepository

the result is

WMI repository is consistent

Also, if I run wmimgmt.msc and open the properties for WMI Control (Local), no errors are shown.

Any ideas of how to proceed?

Calling a method after a query

Interested in doing something like

wmic.exe volume WHERE (DeviceID='\\\\?\\Volume{d9b257fc-684e-4dcb-ab79-03cfa2f6b750}\\') CALL format QuickFormat=True

using this library, without calling wmic. Is it possible? Doesn't look like it, but better ask.

Can you do a new "release" for v1.2.1

shirou/gopsutil#1099

I that when the v1.2.0 tag briefly was pointing at the wrong commit, some people may have cached that and it's now causing issues. In theory if you just add a new tag for v1.2.1 then theoretically that will fix the problem once packages reference that version?

Can't query from Win32_VolumeChangeEvent

type Win32_VolumeChangeEvent struct {
	EventType uint16
	DriveName string
}

func main() {
	var dst []Win32_VolumeChangeEvent
	q := wmi.CreateQuery(&dst, "")
	fmt.Println(q)

	for {
		err := wmi.Query(q, &dst)
		if err != nil {
			log.Fatal(err)
		}
		if len(dst) == 0 {
			continue
		}
		for _, v := range dst {
			fmt.Println(v)
		}

	}
}

but the result always be empty. when the example run well, i don't know why :(

Invilad class of Win32_PerfRawData_HvStats_HyperVHypervisor

I have found some property about HyperV in Win32_PerfRawData, such as
Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor,
Win32_PerfRawData_HvStats_HyperVHypervisor, etc.

But when I use the WMI interface to query those property it occurs error.
I use it this way:

	var dst []Win32_PerfRawData_HvStats_HyperVHypervisor
	q := wmi.CreateQuery(&dst, "")
	if err := wmi.Query(q, &dst); err != nil {
		return nil, err

It return this: nil 发生意外。 (无效类 ).

The WQL I printed is:

SELECT LogicalProcessors, MonitoredNotifications, Partitions, TotalPages, VirtualProcessors FROM Win32_PerfRawData_HvStats_HyperVHypervisor

So I query it in windows power shell with the command winrm just like this:
winrm enum wmi\root\cimv2\* -filter:"select * from Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor where name='LogicalProcessor'";

PS C:\Users\kallen> winrm enum wmi\root\cimv2\* -filter:"select * from Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor where name='LogicalProcessor'";
WSManFault
    Message = WS-Management 服务无法处理该请求。在 WS-Management 编录中找不到资源 URI (wmi\root\cimv2\*)。 该编录包含描述资源或逻辑终结点的元数据。

错误编号: -2144108485 0x8033803B
WS-Management 服务无法处理该请求。缺少资源 URI 或其格式不正确。 请检查文档或使用以下命令以获取有关如何创建资源 URI 的信息: "winrm help uris"。
PS C:\Users\kallen> winrm enum wmi/root/cimv2/* -filter:"select * from Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor where name='LogicalProcessor'";
Fault
    Code
        Value = s:Sender
        Subcode
            Value = n:CannotProcessFilter
    Reason
        Text = 数据源无法处理筛选器。该筛选器可能丢失或无效。 更改筛选器,然后重试请求。
    Detail
        MSFT_WmiError
            CIMStatusCode = 5
            CIMStatusCodeDescription = null
            ErrorSource = null
            ErrorSourceFormat = 0
            ErrorType = 0
            Message = 给定命名空间中没有指定类。
            MessageID = HRESULT 0x8033801a
            OtherErrorSourceFormat = null
            OtherErrorType = null
            OwningEntity = null
            PerceivedSeverity = 0
            ProbableCause = 0
            ProbableCauseDescription = null
            error_Category = 5
            error_Code = 2150858778
            error_Type = HRESULT
            error_WindowsErrorMessage = 给定命名空间中没有指定类。

错误编号: -2144108518 0x8033801A
数据源无法处理筛选器。该筛选器可能丢失或无效。 更改筛选器,然后重试请求。
PS C:\Users\kallen>

I have start the service of HyperV on Windows 10 yet.

should be `runtime.UnlockOSThread()`

This appears to be a typo:

wmi/swbemservices.go

Lines 76 to 80 in cdffdb3

func (s *SWbemServices) process(initError chan error) {
//fmt.Println("process: starting background thread initialization")
//All OLE/WMI calls must happen on the same initialized thead, so lock this goroutine
runtime.LockOSThread()
defer runtime.LockOSThread()

Cannot load LoadPercentage

I have a script with next part:

type Win32_Processor struct {
	LoadPercentage            uint16
	L2CacheSize               uint32
	Family                    uint16
	Manufacturer              string
	Name                      string
	NumberOfLogicalProcessors uint32
	ProcessorId               string
	Stepping                  *string
	MaxClockSpeed             uint32
}
....
        var dst []Win32_Processor
	q := wmi.CreateQuery(&dst, "")
	err := wmi.Query(q, &dst)
	fmt.Println(err)

And when this script is called too often (~26 iteration) I get error:
wmi cannot load field "loadpercentage" into a "uint16" unsupported type (<nil>)
Could you please help, why I get this error?

I use GoLang 1.16, Windows 10(64)

Can't build on windows amd64 with golang 1.9.2

Got error:

github.com/xiaonanln/goworld/vendor/github.com/StackExchange/wmi

vendor\github.com\StackExchange\wmi\wmi.go:377:22: safeArray.ToValueArray undefined (type *ole.SafeArrayConversion has no field or method ToValueArray)

Memory leak?

Hi!
We're using this library in the Prometheus wmi_exporter, thanks alot for open sourcing it! We are investigating a memory leak, and after quite a bit of digging around, it seems like it comes from this library.
I've read #3 and the associated work, but it seems to me those should have been fixed long ago?

The memory that is leaked seems to be native, Go's pprof does not recognize that the memory is allocated any more. How can I help figure this out? I've been trying to learn windbg and debugdiag for a few hours now, without really having much to show for it.

The leak is on the order of around a hundred megabytes per week when doing 50 calls to CreateQuery/Query per minute, if that gives any indication of what could be going wrong.

Make it Buildable in linux

IT fails to build in linux. Can it be made buildable in linux as our jenkins environment is a linux environment? Although we understand its runnable only in windows. But it should be buildable in linux. Because the build environment cannot be always windows.

go test hangs

I wanted to contribute a change but I couldn't run unit tests...

On go 1.10.1 (built myself)

go get github.com/StackExchange/wmi
go test github.com/StackExchange/wmi

@cdffdb33acae0e14efff

Expected:
Tests pass quickly.

Actual:
Tests hang.

Running with -v prints out error about exception in GetMemoryUsage.

WBEM Flags

Is it possible to allow for flags when calling ExecQuery e.g. WBEM_FLAG_RETURN_IMMEDIATELY & WBEM_FLAG_FORWARD_ONLY, as this can significantly improve query performance?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.