DBD/WMI.pm untested

filter: Statementstmt 0.0% 0 / 133 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 221 CC 21 SCAR 27.5
CC
21
Cov
0%
execute
42.0
fetchrow_arrayref
30.0
STORE
20.0
CRAP 15.6
1 package DBD::WMI;
2 use strict;
3 use parent 'DBD::File';
4 use DBI;
5  
6 our $ATTRIBUTION = 'DBD::WMI by Max Maischein <dbd-wmi@corion.net>';
7 our $VERSION = '0.11';
8  
9 =head1 NAME
10  
11 DBD::WMI - interface to the Windows WMI
12  
13 =head1 ABSTRACT
14  
15 This module allows you to issue WQL queries
16 through the DBI.
17  
18 =head1 SYNOPSIS
19  
20 use DBI;
21 my $dbh = DBI->connect('dbi:WMI:');
22  
23 my $sth = $dbh->prepare(<<WQL);
24 SELECT * FROM Win32_Process
25 WQL
26  
27 $sth->execute();
28 while (my @row = $sth->fetchrow) {
29 my $proc = $row[0];
30 print join "\t", $proc->{Caption}, $proc->{ExecutablePath} || "<system>";
31 # $proc->Terminate();
32 print "\n";
33 }
34  
35 The WMI
36 allows you to query various tables ("namespaces"), like the filesystem,
37 currently active processes and events:
38  
39 SELECT * FROM Win32_Process
40  
41 The driver/WMI implements two kinds of queries, finite queries like the
42 query above and potentially infinite queries for events as they occur in
43 the system:
44  
45 my $query = q{
46
47 SELECT * FROM __instanceoperationevent
48 WITHIN 1
49 WHERE TargetInstance ISA 'Win32_DiskDrive'
50
51 }
52  
53 This query returns one row (via ->fetchrow_arrayref() ) whenever a disk
54 drive gets added to or removed from the system (think of an USB stick).
55  
56 There is currently no support for selecting specific
57 columns instead of C<*>. Support for selecting columns that
58 then get returned as plain Perl scalars is planned.
59  
60 =cut
61  
62 # Investigate System.Management.MethodData to get at the methods and properties
63  
64 my $drh;
65 sub driver {
66 return $drh if $drh;
67  
68 my ($package,$attr) = @_;
69  
70 $package .= "::dr";
71 $drh = DBI::_new_drh( $package, {
72 Attribution => $ATTRIBUTION,
73 Version => $VERSION,
74 Name => 'WMI',
75 },
76 );
77  
78 $drh
79 };
80  
81 package DBD::WMI::dr;
82 use strict;
83 use Win32::WQL;
84  
85 our $imp_data_size = 0;
86  
87 sub connect {
88 my ($drh, $dr_dsn, $user, $auth, $attr) = @_;
89  
90 $dr_dsn ||= ".";
91 $dr_dsn =~ /^([^;]*)/i
92 or die "Invalid DSN '$dr_dsn'";
93 my $machine = $1 || ".";
94  
95 my @args;
96 if ( defined $user and $user ne '') {
97 my $locator = Win32::OLE->new("WbemScripting.SWbemLocator");
98 my $ole_con=$locator->ConnectServer($machine,'root/cimV2',$user,$auth);
99 @args = $ole_con;
100 } else {
101 @args = (machine => $machine);
102 }
103 my $wmi = Win32::WQL->new(@args);
104  
105 my ($outer, $dbh) = DBI::_new_dbh(
106 $drh,
107 { Name => $dr_dsn },
108 );
109 $dbh->{wmi_wmi} = $wmi;
110  
111 #$dbh->STORE('Active',1);
112 $outer
113 }
114  
115 sub data_sources {
116 my ($drh) = @_;
117  
118 my $wmi = Win32::WQL->new();
119 my $sth = $wmi->prepare(<<WQL);
120 SELECT * FROM meta_class
121 WQL
122  
123 my $sources = $sth->execute();
124 my @res;
125 while (my $ev = $sources->fetchrow()) {
126 push @res, $ev->Path_->Class
127 };
128 @res
129 }
130  
131 package DBD::WMI::db;
132 use strict;
133  
134 our $imp_data_size = 0;
135  
136 sub prepare {
137 my ($dbh, $statement, @attribs) = @_;
138  
139 my $own_sth = $dbh->{wmi_wmi}->prepare($statement);
140 my ($outer, $sth) = DBI::_new_sth($dbh,
141 { Statement => $statement,
142 wmi_sth => $own_sth,
143 wmi_params => [],
144 },
145 );
146  
147 my $columns = __PACKAGE__->parse_columns($statement);
148 $sth->STORE('wmi_return_columns', $columns);
149  
150 $sth->STORE('NUM_OF_PARAMS', ($statement =~ tr/?//));
151  
152 return $outer;
153 }
154  
155 =head2 C<< DBD::WMI::db::parse_columns STATEMENT >>
156  
157 This routine parses out the requested columns
158 from the WQL statement and returns an array reference
159 with the names of the columns.
160  
161 Currently, this only works for C<SELECT> statements.
162 All other statements get an implicit column
163 of C<*>, meaning that the Win32::OLE objects
164 will be returned.
165  
166 =cut
167  
168 sub parse_columns {
169 my ($dbh, $statement) = @_;
170 my @columns;
171 if ($statement =~ /^\s*SELECT \s*(.*?)\s+FROM\b/mi) {
172 @columns = map { s/^\s*//; s/\s*$//; $_ } split /,/, $1; # verrry simplicistic parsing
173 } else {
174 @columns = ('*');
175 };
176
177 \@columns
178 };
179  
180 sub STORE
181 {
182 my ($dbh, $attr, $val) = @_;
183 if ($attr eq 'AutoCommit') {
184 # AutoCommit is currently the only standard attribute we have
185 # to consider.
186 if (!$val) { die "Can't disable AutoCommit"; }
187 return 1;
188 }
189 if ($attr =~ m/^wmi_/) {
190 # Handle only our private attributes here
191 # Note that we could trigger arbitrary actions.
192 # Ideally we should warn about unknown attributes.
193 $dbh->{$attr} = $val; # Yes, we are allowed to do this,
194 return 1; # but only for our private attributes
195 }
196 # Else pass up to DBI to handle for us
197 $dbh->SUPER::STORE($attr, $val);
198 }
199  
200 sub FETCH
201 {
202 my ($dbh, $attr) = @_;
203 if ($attr eq 'AutoCommit') { return 1; }
204 if ($attr =~ m/^wmi_/) {
205 # Handle only our private attributes here
206 # Note that we could trigger arbitrary actions.
207 return $dbh->{$attr}; # Yes, we are allowed to do this,
208 # but only for our private attributes
209 }
210 # Else pass up to DBI to handle
211 $dbh->SUPER::FETCH($attr);
212 }
213  
214 package DBD::WMI::st;
215 use strict;
216 use Carp qw(croak);
217  
218 our $imp_data_size = 0;
219  
220 sub execute {
221 my $sth = shift;
222  
223 # Recycle if we're still active
224 $sth->finish if $sth->FETCH('Active');
225  
226 my $params = (@_) ?
227 \@_ : $sth->{wmi_params};
228 my $numParam = $sth->FETCH('NUM_OF_PARAMS');
229 return $sth->set_err(1, "Wrong number of parameters")
230 if @$params != $numParam;
231 if ($numParam > 0) {
232 return $sth->set_err(1, "DBD::WMI doesn't support parameters yet")
233 if @$params > 0;
234 };
235 #my $statement = $sth->{'Statement'};
236 #for (my $i = 0; $i < $numParam; $i++) {
237 # $statement =~ s/?/$params->[$i]/; # doesn't deal with quoting etc!
238 #
239 #};
240  
241 my $iter = $sth->{wmi_sth}->execute(@$params);
242  
243 #$sth->STORE('Active',1);
244  
245 $sth->{'wmi_data'} = $iter;
246 $sth->{'wmi_rows'} = 1; # we don't know/can't know
247 $sth->STORE('NUM_OF_FIELDS', scalar @{$sth->FETCH('wmi_return_columns')});# $numFields;
248 $sth->{'wmi_rows'} || '0E0';
249 }
250  
251 sub fetchrow_arrayref
252 {
253 my ($sth) = @_;
254 my $data = $sth->{wmi_data};
255 my @row = $data->fetchrow();
256  
257 if (! @row) {
258 $sth->finish;
259 return undef;
260 }
261  
262 # Transform row objects into requested query columns
263 if (my $columns = $sth->FETCH('wmi_return_columns')) {
264 my $r = $row[0];
265 @row = map { $_ eq '*' ? $r : $r->{$_} } @$columns;
266 };
267  
268 if ($sth->FETCH('ChopBlanks')) {
269 map { $_ =~ s/\s+$//; } @row;
270 }
271 return $sth->_set_fbav(\@row);
272 }
273  
274 { no warnings 'once';
275 *fetch = \&fetchrow_arrayref; # required alias for fetchrow_arrayref
276 }
277  
278 sub STORE
279 {
280 my ($sth, $attr, $val) = @_;
281 if ($attr =~ m/^wmi_/) {
282 # Handle only our private attributes here
283 # Note that we could trigger arbitrary actions.
284 # Ideally we should warn about unknown attributes.
285 $sth->{$attr} = $val; # Yes, we are allowed to do this,
286 return 1; # but only for our private attributes
287 }
288 # Else pass up to DBI to handle for us
289 $sth->SUPER::STORE($attr, $val);
290 }
291  
292 sub FETCH
293 {
294 my ($sth, $attr) = @_;
295 if ($attr eq 'AutoCommit') { return 1; }
296 if ($attr =~ m/^wmi_/) {
297 # Handle only our private attributes here
298 # Note that we could trigger arbitrary actions.
299 return $sth->{$attr}; # Yes, we are allowed to do this,
300 # but only for our private attributes
301 }
302 # Else pass up to DBI to handle
303 $sth->SUPER::FETCH($attr);
304 }
305  
306 1;
307  
308 =head1 HANDLING OF QUERY COLUMNS
309  
310 The WMI and WQL return full objects instead of single columns. The specification
311 of columns is merely a hint to the object what properties to preload. The
312 DBD interface deviates from that approach in that it returns objects
313 for queries of the form C<SELECT *> and the values of the object
314 properties when columns are specified. These columns are then case sensitive.
315  
316 =head1 FUN QUERIES
317  
318 =head2 List all printers
319  
320 SELECT * FROM Win32_Printer
321  
322 =head2 List all print jobs on a printer
323  
324 SELECT * FROM Win32_PrintJob
325 WHERE DriverName = 'HP Deskjet 6122'
326  
327 =head2 Return a new row whenever a new print job is started
328  
329 SELECT * FROM __InstanceCreationEvent
330 WITHIN 10
331 WHERE
332 TargetInstance ISA 'Win32_PrintJob'
333  
334 =head2 Finding the default printer
335  
336 SELECT * FROM Win32_Printer
337 WHERE Default = TRUE
338  
339 =head2 Setting the default printer (untested, WinXP, Win2003)
340  
341 use DBI;
342 my $dbh = DBI->connect('dbi:WMI:');
343 my $sth = $dbh->prepare(<<WQL);
344 SELECT * FROM Win32_Printer
345 WQL
346  
347 $sth->execute;
348 while (my @row = $sth->fetchrow) {
349 # We get Win32::OLE objects back:
350 my $printer = $row[0];
351 printf "Making %s the default printer\n", $printer->{Name};
352 $printer->SetDefaultPrinter;
353 };
354  
355 =head2 Find all network adapters with IP enabled
356  
357 SELECT * from Win32_NetworkAdapterConfiguration
358 WHERE IPEnabled = True
359  
360 =head2 Find files in a directory
361  
362 ASSOCIATORS OF {Win32_Directory.Name='C:\WINNT'}
363 WHERE ResultClass = CIM_DataFile
364  
365 =head2 Find printers on a remote machine
366  
367 use DBI;
368 my $machine = 'dawn';
369 my $dbh = DBI->connect('dbi:WMI:'.$machine);
370 my $sth = $dbh->prepare(<<WQL);
371 SELECT * FROM Win32_Printer
372 WQL
373  
374 $sth->execute;
375 while (my @row = $sth->fetchrow) {
376 my $printer = $row[0];
377 printf "Making %s the default printer on %s\n", $printer->{Name}, $machine;
378 $printer->SetDefaultPrinter;
379 };
380  
381 =head2 Get method names of objects
382  
383 use Win32::OLE qw(in);
384 ...
385  
386 SELECT * FROM Win32_Process
387  
388 $sth->execute;
389  
390 while (my @row = $sth->fetchrow) {
391 for my $method (in $row[0]->Methods_) {
392 print "Can call $method() on the object\n"
393 };
394 };
395  
396 =head1 TODO
397  
398 =over 4
399  
400 =item * Implement placeholders and proper interpolation of values
401  
402 =item * Need to implement DSN parameters for remote computers, credentials
403  
404 =back
405  
406 =head1 SEE ALSO
407  
408 WMI is Microsofts implementation of the WBEM standard (L<http://www.dmtf.org/standards/wbem/>) except that it uses DCOM and not CIM-XML as the transport medium.
409  
410 The MS WMI main page at L<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/wmi_start_page.asp>
411  
412 The WQL documentation at L<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/wql_sql_for_wmi.asp>
413  
414 The "Hey Scripting Guy" column at L<http://www.microsoft.com/technet/scriptcenter/resources/qanda/default.mspx>
415  
416 Wikipedia on WMI at L<http://en.wikipedia.org/wiki/Windows_Management_Instrumentation>
417  
418 List of available Win32 WMI classes at L<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_classes.asp>
419  
420 =head1 REPOSITORY
421  
422 The public repository of this module is
423 L<https://github.com/Corion/dbd-wmi>.
424  
425 =head1 SUPPORT
426  
427 The public support forum of this module is
428 L<https://perlmonks.org/>.
429  
430 =head1 BUG TRACKER
431  
432 Please report bugs in this module via the RT CPAN bug queue at
433 L<https://rt.cpan.org/Public/Dist/Display.html?Name=DBD-WMI>
434 or via mail to L<dbd-wmi-Bugs@rt.cpan.org>.
435  
436 =head1 AUTHOR
437  
438 Max Maischein C<corion@cpan.org>
439  
440 =head1 COPYRIGHT (c)
441  
442 Copyright 2009-2018 by Max Maischein C<corion@cpan.org>.
443  
444 =head1 LICENSE
445  
446 This module is released under the same terms as Perl itself.
447  
448 =cut