从Go语言中查询WMI

huangapple go评论93阅读模式
英文:

Query WMI from Go

问题

我想要在Go语言中运行WMI查询。有一些方法可以从Go中调用DLL函数。我理解的是,必须有某个DLL,在正确的调用下,它将返回一些我可以解析和使用的数据。我更希望避免调用C或C++,特别是因为我猜想它们只是Windows API本身的包装器。

我已经检查了dumpbin.exe /exports c:\windows\system32\wmi.dll的输出,以下条目看起来很有希望:

WmiQueryAllDataA (forwarded to wmiclnt.WmiQueryAllDataA)

然而,我不确定接下来该怎么做。这个函数需要什么参数?它返回什么?搜索WmiQueryAllDataA没有帮助。而且这个名称只出现在c:\program files (x86)\windows kits\8.1\include\shared\wmistr.h的注释中,但没有函数签名。

有更好的方法吗?还有其他的DLL吗?我有什么遗漏吗?我应该只使用一个C包装器吗?

在Linqpad中使用.NET Reflector运行WMI查询显示了WmiNetUtilsHelper:ExecQueryWmi(还有一个_f版本),但都没有可查看的实现。

**更新:**使用github.com/StackExchange/wmi包,该包使用了被接受答案中的解决方案。

英文:

I would like to run WMI queries from Go. There are ways to call DLL functions from Go. My understanding is that there must be some DLL somewhere which, with the correct call, will return some data I can parse and use. I'd prefer to avoid calling into C or C++, especially since I would guess those are wrappers over the Windows API itself.

I've examined the output of dumpbin.exe /exports c:\windows\system32\wmi.dll, and the following entry looks promising:

WmiQueryAllDataA (forwarded to wmiclnt.WmiQueryAllDataA)

However I'm not sure what to do from here. What arguments does this function take? What does it return? Searching for WmiQueryAllDataA is not helpful. And that name only appears in a comment of c:\program files (x86)\windows kits\8.1\include\shared\wmistr.h, but with no function signature.

Are there better methods? Is there another DLL? Am I missing something? Should I just use a C wrapper?

Running a WMI query in Linqpad with .NET Reflector shows the use of WmiNetUtilsHelper:ExecQueryWmi (and a _f version), but neither have a viewable implementation.

Update: use the github.com/StackExchange/wmi package which uses the solution in the accepted answer.

答案1

得分: 21

欢迎来到COM的奇妙世界,这是关于C语言面向对象编程的,当时C++还是一个"年轻的新秀"。

在GitHub上,mattn创建了一个Go语言的小包装器,我用它来快速编写了一个示例程序。"这个存储库是为了实验目的而创建的,应被视为不稳定的。"这样的话让人信心满满。

我省略了很多错误检查。相信我,你会希望将它们添加回去。

package main

import (
        "github.com/mattn/go-ole"
        "github.com/mattn/go-ole/oleutil"
)

func main() {
    // 初始化COM,噢耶
    ole.CoInitialize(0)
    defer ole.CoUninitialize()

    unknown, _ := oleutil.CreateObject("WbemScripting.SWbemLocator")
    defer unknown.Release()

    wmi, _ := unknown.QueryInterface(ole.IID_IDispatch)
    defer wmi.Release()

    // service是一个SWbemServices
    serviceRaw, _ := oleutil.CallMethod(wmi, "ConnectServer")
    service := serviceRaw.ToIDispatch()
    defer service.Release()

    // result是一个SWBemObjectSet
    resultRaw, _ := oleutil.CallMethod(service, "ExecQuery", "SELECT * FROM Win32_Process")
    result := resultRaw.ToIDispatch()
    defer result.Release()

    countVar, _ := oleutil.GetProperty(result, "Count")
    count := int(countVar.Val)

    for i :=0; i < count; i++ {
        // item是一个SWbemObject,但实际上是Win32_Process
        itemRaw, _ := oleutil.CallMethod(result, "ItemIndex", i)
        item := itemRaw.ToIDispatch()
        defer item.Release()

        asString, _ := oleutil.GetProperty(item, "Name")

        println(asString.ToString())
    }
}

真正的核心是对ExecQuery的调用,我恰好从可用的类中选择了Win32_Process,因为它易于理解和打印。

在我的机器上,这将打印出:

System Idle Process
System
smss.exe
csrss.exe
wininit.exe
services.exe
lsass.exe
svchost.exe
svchost.exe
atiesrxx.exe
svchost.exe
svchost.exe
svchost.exe
svchost.exe
svchost.exe
spoolsv.exe
svchost.exe
AppleOSSMgr.exe
AppleTimeSrv.exe
...以此类推
go.exe
main.exe

我没有以提升的权限或禁用UAC来运行它,但某些WMI提供程序需要特权用户。

我也不能百分之百确定这不会有一点泄漏,你需要深入研究一下。COM对象是引用计数的,所以defer应该是一个相当好的选择(前提是方法不会运行得太长时间),但是go-ole可能有一些我没有注意到的魔法。

英文:

Welcome to the wonderful world of COM, Object Oriented Programming in C from when C++ was "a young upstart".

On github mattn has thrown together a little wrapper in Go, which I used to throw together a quick example program. "This repository was created for experimentation and should be considered unstable." instills all sorts of confidence.

I'm leaving out a lot of error checking. Trust me when I say, you'll want to add it back.

package main

import (
        &quot;github.com/mattn/go-ole&quot;
        &quot;github.com/mattn/go-ole/oleutil&quot;
)

func main() {
    // init COM, oh yeah
    ole.CoInitialize(0)
    defer ole.CoUninitialize()

    unknown, _ := oleutil.CreateObject(&quot;WbemScripting.SWbemLocator&quot;)
    defer unknown.Release()

    wmi, _ := unknown.QueryInterface(ole.IID_IDispatch)
    defer wmi.Release()

    // service is a SWbemServices
    serviceRaw, _ := oleutil.CallMethod(wmi, &quot;ConnectServer&quot;)
    service := serviceRaw.ToIDispatch()
    defer service.Release()

    // result is a SWBemObjectSet
    resultRaw, _ := oleutil.CallMethod(service, &quot;ExecQuery&quot;, &quot;SELECT * FROM Win32_Process&quot;)
    result := resultRaw.ToIDispatch()
    defer result.Release()

    countVar, _ := oleutil.GetProperty(result, &quot;Count&quot;)
    count := int(countVar.Val)

    for i :=0; i &lt; count; i++ {
        // item is a SWbemObject, but really a Win32_Process
        itemRaw, _ := oleutil.CallMethod(result, &quot;ItemIndex&quot;, i)
        item := itemRaw.ToIDispatch()
        defer item.Release()

        asString, _ := oleutil.GetProperty(item, &quot;Name&quot;)

        println(asString.ToString())
    }
}

The real meat is the call to ExecQuery, I happen to grab Win32_Process from the available classes because it's easy to understand and print.

On my machine, this prints:

System Idle Process
System
smss.exe
csrss.exe
wininit.exe
services.exe
lsass.exe
svchost.exe
svchost.exe
atiesrxx.exe
svchost.exe
svchost.exe
svchost.exe
svchost.exe
svchost.exe
spoolsv.exe
svchost.exe
AppleOSSMgr.exe
AppleTimeSrv.exe
... and so on
go.exe
main.exe

I'm not running it elevated or with UAC disabled, but some WMI providers are gonna require a privileged user.

I'm also not 100% that this won't leak a little, you'll want to dig into that. COM objects are reference counted, so defer should be a pretty good fit there (provided the method isn't crazy long running) but go-ole may have some magic inside I didn't notice.

答案2

得分: 7

我是一个中文翻译助手,以下是你提供的代码的翻译:

// +build windows

/*
Package wmi provides a WQL interface for WMI on Windows.

Example code to print names of running processes:

	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)
		}
	}

*/
package wmi

import (
	"bytes"
	"errors"
	"fmt"
	"log"
	"os"
	"reflect"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/mattn/go-ole"
	"github.com/mattn/go-ole/oleutil"
)

var l = log.New(os.Stdout, "", log.LstdFlags)

var (
	ErrInvalidEntityType = errors.New("wmi: invalid entity type")
	lock                 sync.Mutex
)

// QueryNamespace invokes Query with the given namespace on the local machine.
func QueryNamespace(query string, dst interface{}, namespace string) error {
	return Query(query, dst, nil, namespace)
}

// Query runs the WQL query and appends the values to dst.
//
// dst must have type *[]S or *[]*S, for some struct type S. Fields selected in
// the query must have the same name in dst. Supported types are all signed and
// unsigned integers, time.Time, string, bool, or a pointer to one of those.
// Array types are not supported.
//
// By default, the local machine and default namespace are used. These can be
// changed using connectServerArgs. See
// http://msdn.microsoft.com/en-us/library/aa393720.aspx for details.
func Query(query string, dst interface{}, connectServerArgs ...interface{}) error {
	dv := reflect.ValueOf(dst)
	if dv.Kind() != reflect.Ptr || dv.IsNil() {
		return ErrInvalidEntityType
	}
	dv = dv.Elem()
	mat, elemType := checkMultiArg(dv)
	if mat == multiArgTypeInvalid {
		return ErrInvalidEntityType
	}

	lock.Lock()
	defer lock.Unlock()
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	err := ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED)
	if err != nil {
		oleerr := err.(*ole.OleError)
		// S_FALSE           = 0x00000001 // CoInitializeEx was already called on this thread
		if oleerr.Code() != ole.S_OK && oleerr.Code() != 0x00000001 {
			return err
		}
	} else {
		// Only invoke CoUninitialize if the thread was not initizlied before.
		// This will allow other go packages based on go-ole play along
		// with this library.
		defer ole.CoUninitialize()
	}

	unknown, err := oleutil.CreateObject("WbemScripting.SWbemLocator")
	if err != nil {
		return err
	}
	defer unknown.Release()

	wmi, err := unknown.QueryInterface(ole.IID_IDispatch)
	if err != nil {
		return err
	}
	defer wmi.Release()

	// service is a SWbemServices
	serviceRaw, err := oleutil.CallMethod(wmi, "ConnectServer", connectServerArgs...)
	if err != nil {
		return err
	}
	service := serviceRaw.ToIDispatch()
	defer serviceRaw.Clear()

	// result is a SWBemObjectSet
	resultRaw, err := oleutil.CallMethod(service, "ExecQuery", query)
	if err != nil {
		return err
	}
	result := resultRaw.ToIDispatch()
	defer resultRaw.Clear()

	count, err := oleInt64(result, "Count")
	if err != nil {
		return err
	}

	// Initialize a slice with Count capacity
	dv.Set(reflect.MakeSlice(dv.Type(), 0, int(count)))

	var errFieldMismatch error
	for i := int64(0); i < count; i++ {
		err := func() error {
			// item is a SWbemObject, but really a Win32_Process
			itemRaw, err := oleutil.CallMethod(result, "ItemIndex", i)
			if err != nil {
				return err
			}
			item := itemRaw.ToIDispatch()
			defer itemRaw.Clear()

			ev := reflect.New(elemType)
			if err = loadEntity(ev.Interface(), item); err != nil {
				if _, ok := err.(*ErrFieldMismatch); ok {
					// We continue loading entities even in the face of field mismatch errors.
					// If we encounter any other error, that other error is returned. Otherwise,
					// an ErrFieldMismatch is returned.
					errFieldMismatch = err
				} else {
					return err
				}
			}
			if mat != multiArgTypeStructPtr {
				ev = ev.Elem()
			}
			dv.Set(reflect.Append(dv, ev))
			return nil
		}()
		if err != nil {
			return err
		}
	}
	return errFieldMismatch
}

// ErrFieldMismatch is returned when a field is to be loaded into a different
// type than the one it was stored from, or when a field is missing or
// unexported in the destination struct.
// StructType is the type of the struct pointed to by the destination argument.
type ErrFieldMismatch struct {
	StructType reflect.Type
	FieldName  string
	Reason     string
}

func (e *ErrFieldMismatch) Error() string {
	return fmt.Sprintf("wmi: cannot load field %q into a %q: %s",
		e.FieldName, e.StructType, e.Reason)
}

var timeType = reflect.TypeOf(time.Time{})

// loadEntity loads a SWbemObject into a struct pointer.
func loadEntity(dst interface{}, src *ole.IDispatch) (errFieldMismatch error) {
	v := reflect.ValueOf(dst).Elem()
	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i)
		isPtr := f.Kind() == reflect.Ptr
		if isPtr {
			ptr := reflect.New(f.Type().Elem())
			f.Set(ptr)
			f = f.Elem()
		}
		n := v.Type().Field(i).Name
		if !f.CanSet() {
			return &ErrFieldMismatch{
				StructType: f.Type(),
				FieldName:  n,
				Reason:     "CanSet() is false",
			}
		}
		prop, err := oleutil.GetProperty(src, n)
		if err != nil {
			errFieldMismatch = &ErrFieldMismatch{
				StructType: f.Type(),
				FieldName:  n,
				Reason:     "no such struct field",
			}
			continue
		}
		defer prop.Clear()

		switch val := prop.Value().(type) {
		case int, int64:
			var v int64
			switch val := val.(type) {
			case int:
				v = int64(val)
			case int64:
				v = val
			default:
				panic("unexpected type")
			}
			switch f.Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				f.SetInt(v)
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
				f.SetUint(uint64(v))
			default:
				return &ErrFieldMismatch{
					StructType: f.Type(),
					FieldName:  n,
					Reason:     "not an integer class",
				}
			}
		case string:
			iv, err := strconv.ParseInt(val, 10, 64)
			switch f.Kind() {
			case reflect.String:
				f.SetString(val)
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				if err != nil {
					return err
				}
				f.SetInt(iv)
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
				if err != nil {
					return err
				}
				f.SetUint(uint64(iv))
			case reflect.Struct:
				switch f.Type() {
				case timeType:
					if len(val) == 25 {
						mins, err := strconv.Atoi(val[22:])
						if err != nil {
							return err
						}
						val = val[:22] + fmt.Sprintf("%02d%02d", mins/60, mins%60)
					}
					t, err := time.Parse("20060102150405.000000-0700", val)
					if err != nil {
						return err
					}
					f.Set(reflect.ValueOf(t))
				}
			}
		case bool:
			switch f.Kind() {
			case reflect.Bool:
				f.SetBool(val)
			default:
				return &ErrFieldMismatch{
					StructType: f.Type(),
					FieldName:  n,
					Reason:     "not a bool",
				}
			}
		default:
			typeof := reflect.TypeOf(val)
			if isPtr && typeof == nil {
				break
			}
			return &ErrFieldMismatch{
				StructType: f.Type(),
				FieldName:  n,
				Reason:     fmt.Sprintf("unsupported type (%T)", val),
			}
		}
	}
	return errFieldMismatch
}

type multiArgType int

const (
	multiArgTypeInvalid multiArgType = iota
	multiArgTypeStruct
	multiArgTypeStructPtr
)

// checkMultiArg checks that v has type []S, []*S for some struct type S.
//
// It returns what category the slice's elements are, and the reflect.Type
// that represents S.
func checkMultiArg(v reflect.Value) (m multiArgType, elemType reflect.Type) {
	if v.Kind() != reflect.Slice {
		return multiArgTypeInvalid, nil
	}
	elemType = v.Type().Elem()
	switch elemType.Kind() {
	case reflect.Struct:
		return multiArgTypeStruct, elemType
	case reflect.Ptr:
		elemType = elemType.Elem()
		if elemType.Kind() == reflect.Struct {
			return multiArgTypeStructPtr, elemType
		}
	}
	return multiArgTypeInvalid, nil
}

func oleInt64(item *ole.IDispatch, prop string) (int64, error) {
	v, err := oleutil.GetProperty(item, prop)
	if err != nil {
		return 0, err
	}
	defer v.Clear()

	i := int64(v.Val)
	return i, nil
}

// CreateQuery returns a WQL query string that queries all columns of src. where
// is an optional string that is appended to the query, to be used with WHERE
// clauses. In such a case, the "WHERE" string should appear at the beginning.
func CreateQuery(src interface{}, where string) string {
	var b bytes.Buffer
	b.WriteString("SELECT ")
	s := reflect.Indirect(reflect.ValueOf(src))
	t := s.Type()
	if s.Kind() == reflect.Slice {
		t = t.Elem()
	}
	if t.Kind() != reflect.Struct {
		return ""
	}
	var fields []string
	for i := 0; i < t.NumField(); i++ {
		fields = append(fields, t.Field(i).Name)
	}
	b.WriteString(strings.Join(fields, ", "))
	b.WriteString(" FROM ")
	b.WriteString(t.Name())
	b.WriteString(" " + where)
	return b.String()
}

这是一个用于在Windows上提供WMI的WQL接口的包。它包含了一个用于打印运行中进程名称的示例代码。你可以使用wmi.Query函数运行WQL查询,并将结果追加到指定的目标中。查询的结果必须是*[]S*[]*S类型的切片,其中S是某个结构体类型。查询中选择的字段必须与目标中的字段名称相同。支持的字段类型包括有符号和无符号整数、time.Time、字符串、布尔值,或者它们的指针。不支持数组类型。

你可以使用wmi.CreateQuery函数创建一个查询字符串,该字符串查询了指定源的所有列。where参数是一个可选的字符串,用于在查询中添加WHERE子句。如果使用了WHERE子句,应该在字符串的开头包含"WHERE"。

你可以在这里的GitHub链接找到完整的代码。

英文:

I'm commenting over a year later, but there is a solution here on github (and posted below for posterity).

// +build windows
/*
Package wmi provides a WQL interface for WMI on Windows.
Example code to print names of running processes:
type Win32_Process struct {
Name string
}
func main() {
var dst []Win32_Process
q := wmi.CreateQuery(&amp;dst, &quot;&quot;)
err := wmi.Query(q, &amp;dst)
if err != nil {
log.Fatal(err)
}
for i, v := range dst {
println(i, v.Name)
}
}
*/
package wmi
import (
&quot;bytes&quot;
&quot;errors&quot;
&quot;fmt&quot;
&quot;log&quot;
&quot;os&quot;
&quot;reflect&quot;
&quot;runtime&quot;
&quot;strconv&quot;
&quot;strings&quot;
&quot;sync&quot;
&quot;time&quot;
&quot;github.com/mattn/go-ole&quot;
&quot;github.com/mattn/go-ole/oleutil&quot;
)
var l = log.New(os.Stdout, &quot;&quot;, log.LstdFlags)
var (
ErrInvalidEntityType = errors.New(&quot;wmi: invalid entity type&quot;)
lock                 sync.Mutex
)
// QueryNamespace invokes Query with the given namespace on the local machine.
func QueryNamespace(query string, dst interface{}, namespace string) error {
return Query(query, dst, nil, namespace)
}
// Query runs the WQL query and appends the values to dst.
//
// dst must have type *[]S or *[]*S, for some struct type S. Fields selected in
// the query must have the same name in dst. Supported types are all signed and
// unsigned integers, time.Time, string, bool, or a pointer to one of those.
// Array types are not supported.
//
// By default, the local machine and default namespace are used. These can be
// changed using connectServerArgs. See
// http://msdn.microsoft.com/en-us/library/aa393720.aspx for details.
func Query(query string, dst interface{}, connectServerArgs ...interface{}) error {
dv := reflect.ValueOf(dst)
if dv.Kind() != reflect.Ptr || dv.IsNil() {
return ErrInvalidEntityType
}
dv = dv.Elem()
mat, elemType := checkMultiArg(dv)
if mat == multiArgTypeInvalid {
return ErrInvalidEntityType
}
lock.Lock()
defer lock.Unlock()
runtime.LockOSThread()
defer runtime.UnlockOSThread()
err := ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED)
if err != nil {
oleerr := err.(*ole.OleError)
// S_FALSE           = 0x00000001 // CoInitializeEx was already called on this thread
if oleerr.Code() != ole.S_OK &amp;&amp; oleerr.Code() != 0x00000001 {
return err
}
} else {
// Only invoke CoUninitialize if the thread was not initizlied before.
// This will allow other go packages based on go-ole play along
// with this library.
defer ole.CoUninitialize()
}
unknown, err := oleutil.CreateObject(&quot;WbemScripting.SWbemLocator&quot;)
if err != nil {
return err
}
defer unknown.Release()
wmi, err := unknown.QueryInterface(ole.IID_IDispatch)
if err != nil {
return err
}
defer wmi.Release()
// service is a SWbemServices
serviceRaw, err := oleutil.CallMethod(wmi, &quot;ConnectServer&quot;, connectServerArgs...)
if err != nil {
return err
}
service := serviceRaw.ToIDispatch()
defer serviceRaw.Clear()
// result is a SWBemObjectSet
resultRaw, err := oleutil.CallMethod(service, &quot;ExecQuery&quot;, query)
if err != nil {
return err
}
result := resultRaw.ToIDispatch()
defer resultRaw.Clear()
count, err := oleInt64(result, &quot;Count&quot;)
if err != nil {
return err
}
// Initialize a slice with Count capacity
dv.Set(reflect.MakeSlice(dv.Type(), 0, int(count)))
var errFieldMismatch error
for i := int64(0); i &lt; count; i++ {
err := func() error {
// item is a SWbemObject, but really a Win32_Process
itemRaw, err := oleutil.CallMethod(result, &quot;ItemIndex&quot;, i)
if err != nil {
return err
}
item := itemRaw.ToIDispatch()
defer itemRaw.Clear()
ev := reflect.New(elemType)
if err = loadEntity(ev.Interface(), item); err != nil {
if _, ok := err.(*ErrFieldMismatch); ok {
// We continue loading entities even in the face of field mismatch errors.
// If we encounter any other error, that other error is returned. Otherwise,
// an ErrFieldMismatch is returned.
errFieldMismatch = err
} else {
return err
}
}
if mat != multiArgTypeStructPtr {
ev = ev.Elem()
}
dv.Set(reflect.Append(dv, ev))
return nil
}()
if err != nil {
return err
}
}
return errFieldMismatch
}
// ErrFieldMismatch is returned when a field is to be loaded into a different
// type than the one it was stored from, or when a field is missing or
// unexported in the destination struct.
// StructType is the type of the struct pointed to by the destination argument.
type ErrFieldMismatch struct {
StructType reflect.Type
FieldName  string
Reason     string
}
func (e *ErrFieldMismatch) Error() string {
return fmt.Sprintf(&quot;wmi: cannot load field %q into a %q: %s&quot;,
e.FieldName, e.StructType, e.Reason)
}
var timeType = reflect.TypeOf(time.Time{})
// loadEntity loads a SWbemObject into a struct pointer.
func loadEntity(dst interface{}, src *ole.IDispatch) (errFieldMismatch error) {
v := reflect.ValueOf(dst).Elem()
for i := 0; i &lt; v.NumField(); i++ {
f := v.Field(i)
isPtr := f.Kind() == reflect.Ptr
if isPtr {
ptr := reflect.New(f.Type().Elem())
f.Set(ptr)
f = f.Elem()
}
n := v.Type().Field(i).Name
if !f.CanSet() {
return &amp;ErrFieldMismatch{
StructType: f.Type(),
FieldName:  n,
Reason:     &quot;CanSet() is false&quot;,
}
}
prop, err := oleutil.GetProperty(src, n)
if err != nil {
errFieldMismatch = &amp;ErrFieldMismatch{
StructType: f.Type(),
FieldName:  n,
Reason:     &quot;no such struct field&quot;,
}
continue
}
defer prop.Clear()
switch val := prop.Value().(type) {
case int, int64:
var v int64
switch val := val.(type) {
case int:
v = int64(val)
case int64:
v = val
default:
panic(&quot;unexpected type&quot;)
}
switch f.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
f.SetInt(v)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
f.SetUint(uint64(v))
default:
return &amp;ErrFieldMismatch{
StructType: f.Type(),
FieldName:  n,
Reason:     &quot;not an integer class&quot;,
}
}
case string:
iv, err := strconv.ParseInt(val, 10, 64)
switch f.Kind() {
case reflect.String:
f.SetString(val)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if err != nil {
return err
}
f.SetInt(iv)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if err != nil {
return err
}
f.SetUint(uint64(iv))
case reflect.Struct:
switch f.Type() {
case timeType:
if len(val) == 25 {
mins, err := strconv.Atoi(val[22:])
if err != nil {
return err
}
val = val[:22] + fmt.Sprintf(&quot;%02d%02d&quot;, mins/60, mins%60)
}
t, err := time.Parse(&quot;20060102150405.000000-0700&quot;, val)
if err != nil {
return err
}
f.Set(reflect.ValueOf(t))
}
}
case bool:
switch f.Kind() {
case reflect.Bool:
f.SetBool(val)
default:
return &amp;ErrFieldMismatch{
StructType: f.Type(),
FieldName:  n,
Reason:     &quot;not a bool&quot;,
}
}
default:
typeof := reflect.TypeOf(val)
if isPtr &amp;&amp; typeof == nil {
break
}
return &amp;ErrFieldMismatch{
StructType: f.Type(),
FieldName:  n,
Reason:     fmt.Sprintf(&quot;unsupported type (%T)&quot;, val),
}
}
}
return errFieldMismatch
}
type multiArgType int
const (
multiArgTypeInvalid multiArgType = iota
multiArgTypeStruct
multiArgTypeStructPtr
)
// checkMultiArg checks that v has type []S, []*S for some struct type S.
//
// It returns what category the slice&#39;s elements are, and the reflect.Type
// that represents S.
func checkMultiArg(v reflect.Value) (m multiArgType, elemType reflect.Type) {
if v.Kind() != reflect.Slice {
return multiArgTypeInvalid, nil
}
elemType = v.Type().Elem()
switch elemType.Kind() {
case reflect.Struct:
return multiArgTypeStruct, elemType
case reflect.Ptr:
elemType = elemType.Elem()
if elemType.Kind() == reflect.Struct {
return multiArgTypeStructPtr, elemType
}
}
return multiArgTypeInvalid, nil
}
func oleInt64(item *ole.IDispatch, prop string) (int64, error) {
v, err := oleutil.GetProperty(item, prop)
if err != nil {
return 0, err
}
defer v.Clear()
i := int64(v.Val)
return i, nil
}
// CreateQuery returns a WQL query string that queries all columns of src. where
// is an optional string that is appended to the query, to be used with WHERE
// clauses. In such a case, the &quot;WHERE&quot; string should appear at the beginning.
func CreateQuery(src interface{}, where string) string {
var b bytes.Buffer
b.WriteString(&quot;SELECT &quot;)
s := reflect.Indirect(reflect.ValueOf(src))
t := s.Type()
if s.Kind() == reflect.Slice {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return &quot;&quot;
}
var fields []string
for i := 0; i &lt; t.NumField(); i++ {
fields = append(fields, t.Field(i).Name)
}
b.WriteString(strings.Join(fields, &quot;, &quot;))
b.WriteString(&quot; FROM &quot;)
b.WriteString(t.Name())
b.WriteString(&quot; &quot; + where)
return b.String()
}

答案3

得分: 1

要访问winmgmts对象或命名空间(它们是相同的),您可以使用下面的代码。基本上,您需要将命名空间作为参数指定,这在go-ole中没有得到适当的文档说明。

在下面的代码中,您还可以看到如何访问此命名空间中的类并执行方法。

package main

import (
	"log"

	"github.com/go-ole/go-ole"
	"github.com/go-ole/go-ole/oleutil"
)

func main() {
	ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED)
	defer ole.CoUninitialize()

	unknown, err := oleutil.CreateObject("WbemScripting.SWbemLocator")
	if err != nil {
		log.Panic(err)
	}
	defer unknown.Release()

	wmi, err := unknown.QueryInterface(ole.IID_IDispatch)
	if err != nil {
		log.Panic(err)
	}
	defer wmi.Release()

	// 连接到命名空间
	// root/PanasonicPC = winmgmts:\\.\root\PanasonicPC
	serviceRaw, err := oleutil.CallMethod(wmi, "ConnectServer", nil, "root/PanasonicPC")
	if err != nil {
		log.Panic(err)
	}
	service := serviceRaw.ToIDispatch()
	defer serviceRaw.Clear()

	// 获取类
	setBiosRaw, err := oleutil.CallMethod(service, "Get", "SetBIOS4Conf")
	if err != nil {
		log.Panic(err)
	}
	setBios := setBiosRaw.ToIDispatch()
	defer setBiosRaw.Clear()

	// 执行方法
	resultRaw, err := oleutil.CallMethod(setBios, "AccessAuthorization", "letmein")
	resultVal := resultRaw.Value().(int32)

	log.Println("Return Code:", resultVal)
}

以上是翻译好的代码。

英文:

To access the winmgmts object or a namespace (which is the same), you can use the code below. Basically, you need to specify the namespace as parameter, which is not documented properly in go-ole.

In the code below, you can also see how to access a class within this namespace and execute a method.

package main
import (
&quot;log&quot;
&quot;github.com/go-ole/go-ole&quot;
&quot;github.com/go-ole/go-ole/oleutil&quot;
)
func main() {
ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED)
defer ole.CoUninitialize()
unknown, err := oleutil.CreateObject(&quot;WbemScripting.SWbemLocator&quot;)
if err != nil {
log.Panic(err)
}
defer unknown.Release()
wmi, err := unknown.QueryInterface(ole.IID_IDispatch)
if err != nil {
log.Panic(err)
}
defer wmi.Release()
// Connect to namespace
// root/PanasonicPC = winmgmts:\\.\root\PanasonicPC
serviceRaw, err := oleutil.CallMethod(wmi, &quot;ConnectServer&quot;, nil, &quot;root/PanasonicPC&quot;)
if err != nil {
log.Panic(err)
}
service := serviceRaw.ToIDispatch()
defer serviceRaw.Clear()
// Get class
setBiosRaw, err := oleutil.CallMethod(service, &quot;Get&quot;, &quot;SetBIOS4Conf&quot;)
if err != nil {
log.Panic(err)
}
setBios := setBiosRaw.ToIDispatch()
defer setBiosRaw.Clear()
// Run method
resultRaw, err := oleutil.CallMethod(setBios, &quot;AccessAuthorization&quot;, &quot;letmein&quot;)
resultVal := resultRaw.Value().(int32)
log.Println(&quot;Return Code:&quot;, resultVal)
}

答案4

得分: 0

import (
  "os/exec"
)

func (lcu *LCU) GrabToken() {
  cmd := exec.Command("powershell", "$cmdline = Get-WmiObject -Class Win32_Process")
  
  out, err := cmd.CombinedOutput()
  if err != nil {
    fmt.Println(err)
  }
  
  outstr := string(out)
}
import (
  "os/exec"
)

func (lcu *LCU) GrabToken() {
  cmd := exec.Command("powershell", "$cmdline = Get-WmiObject -Class Win32_Process")
  
  out, err := cmd.CombinedOutput()
  if err != nil {
    fmt.Println(err)
  }
  
  outstr := string(out)
}
英文:
import(
  &quot;os/exec&quot;
)

 
 func&#160;(lcu&#160;*LCU)&#160;GrabToken()&#160;{ 
 &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;cmd&#160;:=&#160;exec.Command(&quot;powershell&quot;,&#160;&quot;$cmdline&#160;=&#160;Get-WmiObject&#160;-Class&#160;Win32_Process&quot;) 
 &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;
 &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;out,&#160;err&#160;:=&#160;cmd.CombinedOutput() 
 &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;if&#160;err&#160;!=&#160;nil&#160;{ 
 &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;fmt.Println(err) 
 &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;} 
 &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;outstr&#160;:=&#160;string(out)
 }

huangapple
  • 本文由 发表于 2013年12月4日 09:44:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/20365286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定