Documentation
¶
Overview ¶
Package wmi provides a pure-Go WMI client that communicates with Windows hosts over DCOM/RPC using either NTLM or Kerberos authentication.
Connect with NTLM and query using the convenience API:
client, err := wmi.DialNTLM(ctx, "10.0.0.1", "username", "password")
if err != nil {
log.Fatal(err)
}
defer client.Close()
var systems []OperatingSystem
if err := client.CollectDecoded(ctx, "SELECT Caption, Version FROM Win32_OperatingSystem", &systems); err != nil {
log.Fatal(err)
}
Index ¶
- Constants
- Variables
- func Decode(props map[string]*Property, dest any) error
- func DecodeAll(rows []map[string]*Property, dest any) error
- func DefaultQueryFlags() uint32
- func DisableDebug()
- func EnableDebug()
- func FormatWMIDateTime(t time.Time) string
- func ParseWMIDateTime(s string) any
- func SetDebug(enabled bool)
- func SetLogger(logger *slog.Logger)
- type Client
- func (c *Client) Close() error
- func (c *Client) Collect(ctx context.Context, wql string, opts ...QueryOption) ([]map[string]*Property, error)
- func (c *Client) CollectDecoded(ctx context.Context, wql string, dest any, opts ...QueryOption) error
- func (c *Client) Each(ctx context.Context, wql string, opts ...QueryOption) iter.Seq2[map[string]*Property, error]
- func (c *Client) Query(wql string, opts ...QueryOption) *QContext
- type DialOption
- type Error
- type KerberosCache
- type KerberosOption
- type NTLMOption
- type Property
- func (p *Property) CIMTypeName() string
- func (p *Property) GetArrayReferences(ctx context.Context, client *Client, filterProps []string, missingAsNil bool) ([]map[string]*Property, error)
- func (p *Property) GetReference(ctx context.Context, client *Client, filterProps []string) (map[string]*Property, error)
- func (p *Property) IsArray() bool
- func (p *Property) IsArrayReference() bool
- func (p *Property) IsReference() bool
- type QContext
- type Qualifier
- type Query
- type QueryOption
- type ResultOptions
Constants ¶
const ( WBEMInfinite = 0xffffffff WBEMNoWait = 0x0 )
WBEM timeout constants.
const ( WBEMFlagUseAmendedQualifiers = 0x00020000 WBEMFlagReturnImmediately = 0x00000010 WBEMFlagDirectRead = 0x00000200 WBEMFlagPrototype = 0x00000002 WBEMFlagForwardOnly = 0x00000020 WBEMFlagSendStatus = 0x00000080 )
WBEM query flag constants.
Variables ¶
var ( ErrServerNotOptimized = &Error{Msg: "server does not support smart enumeration"} ErrLegacyEncoding = &Error{Msg: "legacy object encoding is not supported"} ErrNotImplemented = &Error{Msg: "not implemented"} ErrKerberosPacketTooLarge = errors.New("kerberos KDC response too large") )
Sentinel errors.
Functions ¶
func Decode ¶
Decode maps WMI properties into a struct. Fields are matched by the "wmi" struct tag, or by exact field name when no tag is present. Use "-" to skip a field.
type OS struct {
Caption string `wmi:"Caption"`
Version string `wmi:"Version"`
}
var os OS
wmi.Decode(props, &os)
func DecodeAll ¶
DecodeAll decodes a slice of property maps into a slice of structs.
var procs []Process wmi.DecodeAll(rows, &procs)
func DefaultQueryFlags ¶
func DefaultQueryFlags() uint32
DefaultQueryFlags returns the default WBEM query flags.
func FormatWMIDateTime ¶
FormatWMIDateTime formats a time.Time as a WMI datetime string.
func ParseWMIDateTime ¶
ParseWMIDateTime parses a WMI datetime string into a time.Time or time.Duration.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a high-level WMI client that owns both the connection and the authenticated service. Create one with DialNTLM or DialKerberos:
client, err := wmi.DialNTLM(ctx, "10.0.0.1", "admin", "secret")
if err != nil { log.Fatal(err) }
defer client.Close()
func DialKerberos ¶
func DialKerberos( ctx context.Context, host, username, password, domain string, opts ...KerberosOption, ) (*Client, error)
DialKerberos connects to host and authenticates using Kerberos, returning a ready-to-use Client. Domain is required. Call Client.Close when done.
client, err := wmi.DialKerberos(ctx, "host.example.com", "admin", "secret", "EXAMPLE.COM")
client, err := wmi.DialKerberos(ctx, host, user, pass, domain, wmi.WithKDC("kdc.host", 88))
func DialNTLM ¶
func DialNTLM(ctx context.Context, host, username, password string, opts ...NTLMOption) (*Client, error)
DialNTLM connects to host and authenticates using NTLM, returning a ready-to-use Client. Call Client.Close when done.
client, err := wmi.DialNTLM(ctx, "10.0.0.1", "admin", "secret")
client, err := wmi.DialNTLM(ctx, host, user, pass, wmi.WithDomain("CORP"))
func (*Client) Collect ¶
func (c *Client) Collect(ctx context.Context, wql string, opts ...QueryOption) ([]map[string]*Property, error)
Collect executes wql and returns all result rows in a slice.
rows, err := client.Collect(ctx, "SELECT Name FROM Win32_Process", WithTimeout(120))
func (*Client) CollectDecoded ¶
func (c *Client) CollectDecoded(ctx context.Context, wql string, dest any, opts ...QueryOption) error
CollectDecoded executes wql and decodes all result rows into dest, which must be a non-nil pointer to a slice of structs (or pointers to structs).
type Proc struct{ Name string `wmi:"Name"` }
var procs []Proc
err := client.CollectDecoded(ctx, "SELECT Name FROM Win32_Process", &procs, WithTimeout(120))
func (*Client) Each ¶
func (c *Client) Each(ctx context.Context, wql string, opts ...QueryOption) iter.Seq2[map[string]*Property, error]
Each executes wql and returns an iterator over the result rows. Iteration stops on the first error; break out of the range loop to release resources early.
for props, err := range client.Each(ctx, "SELECT * FROM Win32_Process", WithTimeout(120)) {
if err != nil { ... }
fmt.Println(props["Name"].Value)
}
type DialOption ¶
type DialOption interface {
NTLMOption
KerberosOption
}
DialOption configures connection setup shared by DialNTLM and DialKerberos.
func WithConnectTimeout ¶
func WithConnectTimeout(timeout time.Duration) DialOption
WithConnectTimeout sets a timeout for the overall dial and authentication handshake. The caller's context is still honored and can cancel earlier.
type KerberosCache ¶
type KerberosCache struct {
// contains filtered or unexported fields
}
KerberosCache holds cached Kerberos TGT and TGS ticket material.
func NewKerberosCache ¶
func NewKerberosCache(filePath string) *KerberosCache
NewKerberosCache creates a new KerberosCache backed by the given file path.
func (*KerberosCache) FilePath ¶
func (k *KerberosCache) FilePath() string
FilePath returns the file path of the cache, or empty if in-memory only.
func (*KerberosCache) HasValidKeys ¶
func (k *KerberosCache) HasValidKeys(offset ...time.Duration) bool
HasValidKeys reports whether the cached keys are present and not yet expired.
func (*KerberosCache) Load ¶
func (k *KerberosCache) Load() error
Load reads cached ticket data from the file on disk.
func (*KerberosCache) Save ¶
func (k *KerberosCache) Save() error
Save persists the current ticket data to disk.
type KerberosOption ¶
type KerberosOption interface {
// contains filtered or unexported methods
}
KerberosOption configures DialKerberos.
func WithKDC ¶
func WithKDC(host string, port int) KerberosOption
WithKDC overrides the Kerberos KDC host and port. By default DialKerberos uses the target host on port 88.
func WithKerberosCache ¶
func WithKerberosCache(cache *KerberosCache) KerberosOption
WithKerberosCache sets a custom Kerberos ticket cache.
type NTLMOption ¶
type NTLMOption interface {
// contains filtered or unexported methods
}
NTLMOption configures DialNTLM.
func WithDomain ¶
func WithDomain(domain string) NTLMOption
WithDomain sets the domain for NTLM authentication.
type Property ¶
type Property struct {
Name string
Type uint16
Order uint16
Value any
Qualifiers []Qualifier
NullDefault bool
InheritedDefault bool
}
Property represents a single WMI property with its name, type, and decoded value.
func (*Property) CIMTypeName ¶
CIMTypeName returns the human-readable CIM type name for the property.
func (*Property) GetArrayReferences ¶
func (p *Property) GetArrayReferences( ctx context.Context, client *Client, filterProps []string, missingAsNil bool, ) ([]map[string]*Property, error)
GetArrayReferences resolves each element of an array-of-references property.
func (*Property) GetReference ¶
func (p *Property) GetReference( ctx context.Context, client *Client, filterProps []string, ) (map[string]*Property, error)
GetReference resolves a single reference property and returns the referenced object's properties.
func (*Property) IsArrayReference ¶
IsArrayReference reports whether the property is an array of CIM references.
func (*Property) IsReference ¶
IsReference reports whether the property is a CIM reference.
type QContext ¶
type QContext struct {
// contains filtered or unexported fields
}
QContext holds the state for an in-progress WMI query.
func (*QContext) CollectDecoded ¶
CollectDecoded executes the query and decodes all result rows into dest, which must be a non-nil pointer to a slice of structs (or pointers to structs).
type Query ¶
type Query struct {
Query string
Namespace string
Language string
Flags uint32
Timeout uint32
SkipOptimize bool
ResultOptions ResultOptions
// contains filtered or unexported fields
}
Query describes a WQL query to execute against a WMI namespace.
func NewQuery ¶
func NewQuery(query string, opts ...QueryOption) Query
NewQuery creates a Query with default namespace and language.
type QueryOption ¶
type QueryOption func(*Query)
QueryOption configures a Query.
func WithLanguage ¶
func WithLanguage(language string) QueryOption
WithLanguage overrides the query language. The default is WQL.
func WithNamespace ¶
func WithNamespace(namespace string) QueryOption
WithNamespace overrides the default WMI namespace for a query.
func WithResultOptions ¶
func WithResultOptions(options ResultOptions) QueryOption
WithResultOptions configures property shaping for query results.
func WithSkipOptimize ¶
func WithSkipOptimize(skip bool) QueryOption
WithSkipOptimize disables the smart-enum optimization when set to true.
func WithTimeout ¶
func WithTimeout(timeout uint32) QueryOption
WithTimeout sets the default per-row fetch timeout in milliseconds.
type ResultOptions ¶
type ResultOptions struct {
// IgnoreDefaults skips loading class-level default values.
// Properties whose values are missing in the instance data
// will have their Value set to nil instead of the class default.
// Automatically treated as true when IgnoreMissing is enabled.
IgnoreDefaults bool
// IgnoreMissing removes properties from the result map entirely
// when their values are not present in the instance data.
// This implies IgnoreDefaults.
IgnoreMissing bool
// LoadQualifiers controls whether property qualifiers (e.g. key,
// read, write) are populated on each Property. When false (the
// default), the Qualifiers slice is left empty.
LoadQualifiers bool
}
ResultOptions controls which properties are included in query results.
func DefaultResultOptions ¶
func DefaultResultOptions() ResultOptions
DefaultResultOptions returns the default ResultOptions.