Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python: Query given WMI class on Windows host from Linux and output to easy-to-read JSON
#!/usr/bin/env python
from optparse import OptionParser
from subprocess import Popen, PIPE
# Requires wmic from Samba project, or here:
wmic = '/vagrant/wmic'
parser = OptionParser()
parser.add_option("-s", "--server", dest="host", action="store",
help="Windows Server to query" )
parser.add_option("-c", "--class", dest="winclass", action="store",
help="WMI class")
parser.add_option("-u", "--username", dest="user", action="store",
help="Administrative user name")
parser.add_option("-p", "--password", dest="passwd", action="store",
(options, args) = parser.parse_args()
if is None:
print "Please specify a target server with -server or -s"
if options.winclass is None:
print "Please specify a WMI class with --class or -c"
if options.user is None:
user = 'Administrator'
user = options.user
if options.passwd is None:
passwd = 'password'
passwd = options.passwd
def wmi_query( host ):
"Query a given host with wmic"
query = "'SELECT * FROM %s'" % options.winclass
cmd = wmic + " --delimiter=^ -U " + user + "%" + passwd + " //" + host + " " + query
process = Popen(cmd, shell=True, stderr=PIPE, stdout=PIPE )
(out, derr) = process.communicate()
if process.returncode is not 0:
print "Something went wrong with host:" + host
print derr
return None
lines = out.split('\n')
junk = lines.index('CLASS: %s' % options.winclass)
# Get rid of the junk. Should be left with Keys and the rest are values
del lines[0:junk+1]
keys = lines[0].split('^')
del lines[0]
ind = 0
infodict = {}
for line in lines:
vals = line.split('^')
infodict[ind] = dict(zip(keys, vals))
return infodict
if __name__ == '__main__':
from json import dumps
hostinfo = wmi_query( )
print dumps(hostinfo, sort_keys=True, indent=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment