-
Notifications
You must be signed in to change notification settings - Fork 0
/
winDevices.py
353 lines (322 loc) · 11.8 KB
/
winDevices.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
"""
Info and utils about windows devices
"""
import typing
import time
import subprocess
from py_aduc_upload.powershellColonObjects import (
PowershellColonObject,PowershellColonObjects)
class WinDevice(PowershellColonObject):
"""
Info and utils for a single windows device
"""
def __init__(self,
rawFromPowershell:typing.Optional[str]=None):
""" """
self.FriendlyName:str=""
self.InstanceId:str=""
self.Problem:str=""
self.ConfigManagerErrorCode:str=""
self.ProblemDescription:str=""
self.Caption:str=""
self.Description:str=""
self.InstallDate:str=""
self.Name:str=""
self.Status:str=""
self.Availability:str=""
self.ConfigManagerUserConfig:str=""
self.CreationClassName:str=""
self.DeviceID:str=""
self.ErrorCleared:str=""
self.ErrorDescription:str=""
self.LastErrorCode:str=""
self.PNPDeviceID:str=""
self.PowerManagementCapabilities:str=""
self.PowerManagementSupported:str=""
self.StatusInfo:str=""
self.SystemCreationClassName:str=""
self.SystemName:str=""
self.ClassGuid:str=""
self.CompatibleID:str=""
self.HardwareID:str=""
self.Manufacturer:str=""
self.PNPClass:str=""
self.Present:str=""
self.Service:str=""
self.PSComputerName:str=""
self.CimClass:str=""
self.CimInstanceProperties:str=""
PowershellColonObject.__init__(self,rawFromPowershell)
@property
def properties(self)->PowershellColonObjects:
"""
Properties about the device
"""
return self.getProperties()
def getProperties(self)->PowershellColonObjects:
"""
Properties about the device
"""
psCommand=f"Get-PnpDeviceProperty -InstanceID '{self.InstanceId}' | Select-Object *" # noqa: E501 # pylint: disable=line-too-long
return PowershellColonObjects(psCommand=psCommand)
def reset(self,offTimeSec=1.0):
"""
Reset a device by power-cycling it
"""
self.disable()
time.sleep(offTimeSec)
self.enable()
powerCycle=reset
def enable(self):
"""
Enable a device
See also:
https://learn.microsoft.com/en-us/powershell/module/pnpdevice/enable-pnpdevice?view=windowsserver2022-ps
"""
psCmd=f"Enable-PnpDevice -Confirm:$false -InstanceID '{self.InstanceId}'" # noqa: E501 # pylint: disable=line-too-long
cmd=['powershell','-Command',psCmd]
po=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,err=po.communicate()
errStr=err.decode('utf-8',errors='ignore').strip()
if errStr:
raise Exception(errStr)
outStr=out.decode('utf-8',errors='ignore').strip().replace('\r','')
print(outStr)
on=enable
def disable(self):
"""
Disable a device
NOTE: you must be an administrator to do this, for obvious reasons
See also:
https://learn.microsoft.com/en-us/powershell/module/pnpdevice/disable-pnpdevice?view=windowsserver2022-ps
"""
psCmd=f"Disable-PnpDevice -Confirm:$false -InstanceID '{self.InstanceId}'" # noqa: E501 # pylint: disable=line-too-long
cmd=['powershell','-Command',psCmd]
#print('\n'.join(cmd))
po=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,err=po.communicate()
errStr=err.decode('utf-8',errors='ignore').strip()
if errStr:
raise Exception(errStr)
outStr=out.decode('utf-8',errors='ignore').strip().replace('\r','')
print(outStr)
off=disable
def __str__(self):
return f'"{self.FriendlyName}" ({self.PNPClass}) @ {self.InstanceId}'
class WinDevices(PowershellColonObjects):
"""
Info and utils about windows devices
Example:
# Find and power-cycle COM4
for device in WinDevices('Ports'):
if device.Name.find('COM4')>=0:
device.reset()
"""
def __init__(self,
loadDeviceClass:typing.Union[None,str,typing.Iterable[str]]=None):
"""
:param loadDeviceClass: device class/classes to auto-load at startup
you can always load more with getByDeviceClass()
"""
self._byDeviceClass:typing.Dict[str,typing.List[WinDevice]]={}
self._scannedAll:bool=False
self.loadedClasses:typing.Set[str]=set()
PowershellColonObjects.__init__(self)
if loadDeviceClass:
self.getByDeviceClass(loadDeviceClass)
@property
def jsonObj(self)->typing.List[typing.Dict[str,typing.Any]]:
"""
This object as a json-compatible object
"""
ret:typing.List[typing.Dict[str,typing.Any]]=[]
for device in self.loaded:
ret.append(device.jsonObj)
return ret
def __iter__(self)->typing.Iterator[WinDevice]:
"""
Iterate over all loaded devices
"""
return iter(self.getLoaded())
def getLoaded(self,refresh:bool=False)->typing.Iterable[WinDevice]:
"""
No, this isn't a wild frat party.
This function gets all currently loaded/scanned devices.
"""
if refresh:
self.refresh()
for vals in self._byDeviceClass.values():
for val in vals:
yield val
@property
def loaded(self)->typing.Iterable[WinDevice]:
"""
All of the currently loaded/scanned devices
"""
return self.getLoaded()
def getAll(self,refresh:bool=False)->typing.Iterable[WinDevice]:
"""
All of the devices on the computer
"""
if refresh or not self._scannedAll:
self.refresh()
return self.getLoaded()
@property
def all(self)->typing.Iterable[WinDevice]:
"""
All of the devices on the computer
"""
return self.getAll()
def getByDeviceClass(self,
deviceClass:str,
refresh:bool=False
)->typing.Iterable[WinDevice]:
"""
Get all devices of a certain device class (eg, "Ports")
"""
if refresh or not self._byDeviceClass:
self.refresh(deviceClass)
elif not self._scannedAll:
items=self._byDeviceClass.get(deviceClass)
if items is not None:
return items
self.refresh(deviceClass)
items=self._byDeviceClass.get(deviceClass,[])
return items
def refreshLoaded(self):
"""
Refresh only the loaded deviceClass(es)
"""
if self._scannedAll:
self.refresh()
else:
self.refresh(self.loadedClasses)
def refresh(self,
deviceClass:typing.Union[None,str,typing.Iterable[str]]=None):
"""
Refresh hardware list
:deviceClass: specific device class or classes to refresh
if None, then refresh all hardware on the system
"""
if deviceClass is None:
self._scannedAll=True
psCmd='Get-PnPDevice | Select-Object *'
elif not isinstance(deviceClass,str):
for dc in deviceClass:
self.refresh(dc)
return
else:
self.loadedClasses.add(deviceClass)
psCmd=f'Get-PnPDevice -Class {deviceClass} | Select-Object *'
cmd=['powershell','-Command',psCmd]
po=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,err=po.communicate()
errStr=err.decode('utf-8',errors='ignore').strip()
if errStr:
raise Exception(errStr)
outStr=out.decode('utf-8',errors='ignore').strip().replace('\r','')
for result in outStr.split('\n\n'):
dev=WinDevice(result)
lst=self._byDeviceClass.get(dev.PNPClass)
if lst is None:
self._byDeviceClass[dev.PNPClass]=[dev]
else:
lst.append(dev)
def __repr__(self):
return '\n-----------------------\n'.join(
[repr(item) for item in self.getLoaded()])
def __str__(self):
return '\n'.join(
[str(item) for item in self.getLoaded()])
def getDevice(comOrInstanceId:str)->typing.Optional[WinDevice]:
"""
get a device either by instance id or by com port name
"""
if comOrInstanceId.upper().startswith('COM'):
comOrInstanceId=comOrInstanceId.upper()
wd=WinDevices("Ports")
for dev in wd:
if dev.Name.find(comOrInstanceId)>=0:
return dev
return None
psCmd=f'Get-PnPDevice -InstanceId {comOrInstanceId} | Select-Object *'
cmd=['powershell','-Command',psCmd]
po=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,err=po.communicate()
errStr=err.decode('utf-8',errors='ignore').strip()
if errStr:
raise Exception(errStr)
outStr=out.decode('utf-8',errors='ignore').strip().replace('\r','')
for result in outStr.split('\n\n'):
dev=WinDevice(result)
return dev
def cmdline(args:typing.Iterable[str])->int:
"""
Run the command line
:param args: command line arguments (WITHOUT the filename)
"""
printHelp=False
if not args:
printHelp=True
else:
outFormat='short'
for arg in args:
if arg.startswith('-'):
arg=[a.strip() for a in arg.split('=',1)]
if arg[0] in ['-h','--help']:
printHelp=True
elif arg[0]=='--out':
outFormat=arg[1]
elif arg[0]=='--ls':
wd=WinDevices()
if len(arg)>1:
wd.refresh(
[a.strip() for a in arg[1].split(',')])
else:
wd.refresh()
if outFormat=='json':
print(wd.json)
else:
print(wd)
elif arg[0] in ('--dev','--device'):
dev=getDevice(arg[1])
if outFormat=='json':
print(dev.json)
else:
print(dev)
elif arg[0] in ('--start','--on'):
dev=getDevice(arg[1])
dev.on()
elif arg[0] in ('--stop','--off'):
dev=getDevice(arg[1])
dev.off()
elif arg[0] in ('--reset','--restart'):
dev=getDevice(arg[1])
dev.reset()
elif arg[0] in ('--properties','--props'):
dev=getDevice(arg[1])
print(dev.properties.json)
else:
print('ERR: unknown argument "'+arg[0]+'"')
else:
print('ERR: unknown argument "'+arg+'"')
if printHelp:
print('Usage:')
print(' winDevices.py [cmd] [options]')
print('Options:')
print(' -h ................... print this help')
print(' --out=[short|json] ... output format')
print(' --ls[=deviceClass] ... list all devices')
print(' optionally, only devices of a certain class')
print(' eg --ls=Ports')
print(' --dev=[comX|instanceId] ..... find a single device')
print(' --device=[comX|instanceId] .. find a single device')
print(' --start=[comX|instanceId] ... turn a device on')
print(' --on=[comX|instanceId] ...... turn a device on')
print(' --stop=[comX|instanceId] .... turn a device off')
print(' --off=[comX|instanceId] ..... turn a device off')
print(' --restart=[comX|instanceId] . restart a device')
print(' --properties=[comX|instanceId] ..... show device properties')
if __name__=='__main__':
import sys
cmdline(sys.argv[1:])