Created
June 18, 2013 22:11
-
-
Save rothwerx/5809932 to your computer and use it in GitHub Desktop.
Python: Query given WMI class on Windows host from Linux and output to easy-to-read JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from optparse import OptionParser | |
from subprocess import Popen, PIPE | |
# Requires wmic from Samba project, or here: | |
# http://dev.zenoss.org/trac/browser/tags/zenoss-3.2.1/inst/externallibs | |
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", | |
help="Password") | |
(options, args) = parser.parse_args() | |
if options.host is None: | |
print "Please specify a target server with -server or -s" | |
parser.print_help() | |
exit(-1) | |
if options.winclass is None: | |
print "Please specify a WMI class with --class or -c" | |
parser.print_help() | |
exit(-1) | |
if options.user is None: | |
user = 'Administrator' | |
else: | |
user = options.user | |
if options.passwd is None: | |
passwd = 'password' | |
else: | |
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( options.host ) | |
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