Skip to main content

Python WMI Queries

Project description

CI Release Version

Python WMI

Windows Management Interface connector using asyncio for the Python language.

Supports:

  • NTLM Authentication
  • Kerberos Authentication
  • WMI Query (IWbemServices_ExecQuery)
  • Parsing of basic WMI Objects (int/float/str/datetime/array/references)
  • Optimized queries using the SmartEnum implementation

Todo:

  • Async WMI Query (IWbemServices_ExecQueryAsync)
  • Other DCOM/RPC/WMI calls?
  • Support for WMI Methods?
  • Improve documentation

Usage

The example below covers most of what is suppored by this library:

import asyncio
import logging
import time
from aiowmi.connection import Connection
from aiowmi.query import Query


async def main():

    host = '10.0.0.1'  # ip address or hostname or fqdn
    username = 'username'
    password = 'password'
    domain = ''  # optional domain name

    # Query has a default namespace 'root/cimv2'
    queries = (
        Query('SELECT * FROM Win32_OperatingSystem', namespace='root/cimv2'),
        Query('SELECT * FROM Win32_NetworkAdapter'),
        Query('SELECT * FROM Win32_LoggedOnUser'),
        Query('SELECT * FROM Win32_PnpEntity'),
        Query('SELECT Caption, Description, InstallDate, InstallDate2, '
              'InstallLocation, InstallSource, InstallState, Language, '
              'LocalPackage, Name, PackageCache, PackageCode, PackageName, '
              'ProductID, RegCompany, RegOwner, SKUNumber, Transforms, '
              'URLInfoAbout, URLUpdateInfo, Vendor, Version '
              'FROM Win32_Product'),
        Query('SELECT Name, DiskReadsPersec, DiskWritesPersec '
              'FROM Win32_PerfFormattedData_PerfDisk_LogicalDisk'),
    )

    start = time.time()

    conn = Connection(host, username, password, domain=domain)
    service = None
    await conn.connect()
    try:
        service = await conn.negotiate_ntlm()

        for query in queries:
            print(f"""
###############################################################################
# Start Query: {query.query}
###############################################################################
""")
            async with query.context(conn, service) as qc:
                async for props in qc.results():
                    # Function `get_properties(..)` accepts a few keyword
                    # arguments:
                    #
                    # ignore_defaults:
                    #        Ignore default values. Set missing values to None
                    #        if a value does not exist in the current class.
                    #        ignore_defaults will always be True if
                    #        ignore_missing is set to True.
                    # ignore_missing:
                    #       If set to True, values missing in the current class
                    #       will not be part of the result.
                    # load_qualifiers:
                    #       Load the qualifiers of the properties. If False,
                    #       the property qualifier_set will have the offset
                    #       in the heap where the qualifiers are stored.
                    #
                    for name, prop in props.items():
                        print(name, '\n\t', prop.value)

                        if prop.is_reference():
                            # References can easy be queried using the
                            # get_reference(..) function. The function accepts
                            # a keyword argument `filter_props=[..]` with an
                            # optional list of properties to query. If omitted,
                            #  the function returns all (*) properties.
                            res = await prop.get_reference(conn, service)
                            ref_props = res.get_properties(ignore_missing=True)
                            for name, prop in ref_props.items():
                                print('\t\t', name, '\n\t\t\t', prop.value)

                    print(f"""
----------------------------------- End Item ----------------------------------
""")
    finally:
        if service:
            service.close()
        conn.close()
        end = time.time()
        print('done in ', end-start)

if __name__ == '__main__':
    formatter = logging.Formatter(
            fmt='[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] ' +
                '%(message)s',
            datefmt='%y%m%d %H:%M:%S',
            style='%')

    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)

    logger = logging.getLogger('aiowmi')
    logger.addHandler(ch)
    logger.setLevel(logging.DEBUG)

    asyncio.run(main())

Kerberos

For Kerberos Authentication, make sure to use a FQDN as hostname and domain is no longer optional.

For caching TGT and TGS, a kerberos cache per connection can be kept.

from aiowmi.connection import Connection
from aiowmi.kerberos.cache import KerberosCache

# Example file cache (tgt, tgs are stored and loaded from file)
kcache = KerberosCache('/tmp/kcache.bin')

# Example mem-cache (tgt, tgs are stored in the cache which can be re-used)
kcache = KerberosCache()

conn = Connection(..., kerberos_cache=kcache)
# If different from the host, the kdc_host address may be provided
# for the Kerberos Key Distribution Center (KDC).
#
# Once connected (await conn.connect()), make the following negotiation call:
#   service = await conn.negotiate_kerberos()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aiowmi-1.1.1.tar.gz (94.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aiowmi-1.1.1-py3-none-any.whl (121.4 kB view details)

Uploaded Python 3

File details

Details for the file aiowmi-1.1.1.tar.gz.

File metadata

  • Download URL: aiowmi-1.1.1.tar.gz
  • Upload date:
  • Size: 94.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for aiowmi-1.1.1.tar.gz
Algorithm Hash digest
SHA256 c19ce940dd1a07a3d893fb433bb4293d3dd7e2134dab0f5bbbff72c7e25762b6
MD5 6208cb97840c713f1f1296e4593ceac3
BLAKE2b-256 f00bc53f95e14048a7a50d547b3d5bd4b021a37b8aebbdf83c1a357d42f256b7

See more details on using hashes here.

File details

Details for the file aiowmi-1.1.1-py3-none-any.whl.

File metadata

  • Download URL: aiowmi-1.1.1-py3-none-any.whl
  • Upload date:
  • Size: 121.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for aiowmi-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ca61b3a65736988cbfa2275457bb8017f541f17fb9ca369188f950b06cf4fd27
MD5 072f5f6f78797ed728649e0d468c7748
BLAKE2b-256 48761d9b28cfffb4a6df09a5035f8e94c7e64b48c301c386e7b34338e8682861

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page