/
win_reg.py
953 lines (746 loc) · 29.6 KB
/
win_reg.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
# -*- coding: utf-8 -*-
'''
Manage the Windows registry
-----
Hives
-----
Hives are the main sections of the registry and all begin with the word HKEY.
- HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER
- HKEY_USER
----
Keys
----
Keys are the folders in the registry. Keys can have many nested subkeys. Keys
can have a value assigned to them under the (Default) value name
-----------------
Values or Entries
-----------------
Values/Entries are name/data pairs. There can be many values in a key. The
(Default) value corresponds to the Key itself, the rest are their own name/value
pairs.
:depends: - PyWin32
'''
# When production windows installer is using Python 3, Python 2 code can be removed
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import sys
import logging
from salt.ext.six.moves import range # pylint: disable=W0622,import-error
# Import third party libs
try:
import win32gui
import win32api
import win32con
import pywintypes
HAS_WINDOWS_MODULES = True
except ImportError:
HAS_WINDOWS_MODULES = False
# Import Salt libs
import salt.utils.platform
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
PY2 = sys.version_info[0] == 2
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'reg'
def __virtual__():
'''
Only works on Windows systems with the PyWin32
'''
if not salt.utils.platform.is_windows():
return (False, 'reg execution module failed to load: '
'The module will only run on Windows systems')
if not HAS_WINDOWS_MODULES:
return (False, 'reg execution module failed to load: '
'One of the following libraries did not load: '
'win32gui, win32con, win32api')
return __virtualname__
def _to_mbcs(vdata):
'''
Converts unicode to to current users character encoding. Use this for values
returned by reg functions
'''
return salt.utils.stringutils.to_unicode(vdata, 'mbcs')
def _to_unicode(vdata):
'''
Converts from current users character encoding to unicode. Use this for
parameters being pass to reg functions
'''
# None does not convert to Unicode
if vdata is None:
return None
return salt.utils.stringutils.to_unicode(vdata, 'utf-8')
class Registry(object): # pylint: disable=R0903
'''
This was put in a class to delay usage until this module is actually used
This class contains all the lookup dicts for working with the registry
'''
def __init__(self):
self.hkeys = {
'HKEY_CURRENT_CONFIG': win32con.HKEY_CURRENT_CONFIG,
'HKEY_CLASSES_ROOT': win32con.HKEY_CLASSES_ROOT,
'HKEY_CURRENT_USER': win32con.HKEY_CURRENT_USER,
'HKEY_LOCAL_MACHINE': win32con.HKEY_LOCAL_MACHINE,
'HKEY_USERS': win32con.HKEY_USERS,
'HKCC': win32con.HKEY_CURRENT_CONFIG,
'HKCR': win32con.HKEY_CLASSES_ROOT,
'HKCU': win32con.HKEY_CURRENT_USER,
'HKLM': win32con.HKEY_LOCAL_MACHINE,
'HKU': win32con.HKEY_USERS,
}
self.vtype = {
'REG_BINARY': win32con.REG_BINARY,
'REG_DWORD': win32con.REG_DWORD,
'REG_EXPAND_SZ': win32con.REG_EXPAND_SZ,
'REG_MULTI_SZ': win32con.REG_MULTI_SZ,
'REG_SZ': win32con.REG_SZ,
'REG_QWORD': win32con.REG_QWORD
}
self.opttype = {
'REG_OPTION_NON_VOLATILE': 0,
'REG_OPTION_VOLATILE': 1
}
# Return Unicode due to from __future__ import unicode_literals
self.vtype_reverse = {
win32con.REG_BINARY: 'REG_BINARY',
win32con.REG_DWORD: 'REG_DWORD',
win32con.REG_EXPAND_SZ: 'REG_EXPAND_SZ',
win32con.REG_MULTI_SZ: 'REG_MULTI_SZ',
win32con.REG_SZ: 'REG_SZ',
win32con.REG_QWORD: 'REG_QWORD'
}
self.opttype_reverse = {
0: 'REG_OPTION_NON_VOLATILE',
1: 'REG_OPTION_VOLATILE'
}
# delete_key_recursive uses this to check the subkey contains enough \
# as we do not want to remove all or most of the registry
self.subkey_slash_check = {
win32con.HKEY_CURRENT_USER: 0,
win32con.HKEY_LOCAL_MACHINE: 1,
win32con.HKEY_USERS: 1,
win32con.HKEY_CURRENT_CONFIG: 1,
win32con.HKEY_CLASSES_ROOT: 1
}
self.registry_32 = {
True: win32con.KEY_READ | win32con.KEY_WOW64_32KEY,
False: win32con.KEY_READ,
}
def __getattr__(self, k):
try:
return self.hkeys[k]
except KeyError:
msg = 'No hkey named \'{0}. Try one of {1}\''
hkeys = ', '.join(self.hkeys)
raise CommandExecutionError(msg.format(k, hkeys))
def key_exists(hive, key, use_32bit_registry=False):
'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs. To check value/data pairs, use ``value_exists``
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
Usage:
.. code-block:: python
import salt.utils.win_reg
winreg.key_exists(hive='HKLM', key='SOFTWARE\\Microsoft')
'''
local_hive = _to_unicode(hive)
local_key = _to_unicode(key)
registry = Registry()
try:
hkey = registry.hkeys[local_hive]
except KeyError:
raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive))
access_mask = registry.registry_32[use_32bit_registry]
handle = None
try:
handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
return True
except pywintypes.error as exc:
if exc.winerror == 2:
return False
raise
finally:
if handle:
win32api.RegCloseKey(handle)
def value_exists(hive, key, vname, use_32bit_registry=False):
'''
Check that the value/data pair is found in the registry.
.. version-added:: 2018.3.4
Args:
hive (str): The hive to connect to
key (str): The key to check in
vname (str): The name of the value/data pair you're checking
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
Usage:
.. code-block:: python
import salt.utils.win_reg
winreg.key_exists(hive='HKLM', key='SOFTWARE\\Microsoft')
'''
local_hive = _to_unicode(hive)
local_key = _to_unicode(key)
local_vname = _to_unicode(vname)
registry = Registry()
try:
hkey = registry.hkeys[local_hive]
except KeyError:
raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive))
access_mask = registry.registry_32[use_32bit_registry]
try:
handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
except pywintypes.error as exc:
if exc.winerror == 2:
# The key containing the value/data pair does not exist
return False
raise
try:
# RegQueryValueEx returns and accepts unicode data
_, _ = win32api.RegQueryValueEx(handle, local_vname)
# value/data pair exists
return True
except pywintypes.error as exc:
if exc.winerror == 2 and vname is None:
# value/data pair exists but is empty
return True
else:
# value/data pair not found
return False
finally:
win32api.RegCloseKey(handle)
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
Usage:
.. code-block:: python
import salt.utils.win_reg
winreg.broadcast_change()
'''
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms644952(v=vs.85).aspx
_, res = win32gui.SendMessageTimeout(
win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 0,
win32con.SMTO_ABORTIFHUNG, 5000)
return not bool(res)
def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USERS or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
Usage:
.. code-block:: python
import salt.utils.win_reg
winreg.list_keys(hive='HKLM', key='SOFTWARE\\Microsoft')
'''
local_hive = _to_unicode(hive)
local_key = _to_unicode(key)
registry = Registry()
try:
hkey = registry.hkeys[local_hive]
except KeyError:
raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive))
access_mask = registry.registry_32[use_32bit_registry]
subkeys = []
handle = None
try:
handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
for i in range(win32api.RegQueryInfoKey(handle)[0]):
subkey = win32api.RegEnumKey(handle, i)
if PY2:
subkeys.append(_to_mbcs(subkey))
else:
subkeys.append(subkey)
except Exception: # pylint: disable=E0602
log.debug(r'Cannot find key: %s\%s', hive, key, exc_info=True)
return False, r'Cannot find key: {0}\{1}'.format(hive, key)
finally:
if handle:
handle.Close()
return subkeys
def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
Usage:
.. code-block:: python
import salt.utils.win_reg
winreg.list_values(hive='HKLM', key='SYSTEM\\CurrentControlSet\\Services\\Tcpip')
'''
local_hive = _to_unicode(hive)
local_key = _to_unicode(key)
registry = Registry()
try:
hkey = registry.hkeys[local_hive]
except KeyError:
raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive))
access_mask = registry.registry_32[use_32bit_registry]
handle = None
values = list()
try:
handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
for i in range(win32api.RegQueryInfoKey(handle)[1]):
vname, vdata, vtype = win32api.RegEnumValue(handle, i)
if not vname:
vname = "(Default)"
value = {'hive': local_hive,
'key': local_key,
'vname': _to_mbcs(vname),
'vtype': registry.vtype_reverse[vtype],
'success': True}
# Only convert text types to unicode
if vtype == win32con.REG_MULTI_SZ:
value['vdata'] = [_to_mbcs(i) for i in vdata]
elif vtype in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]:
value['vdata'] = _to_mbcs(vdata)
else:
value['vdata'] = vdata
values.append(value)
except Exception as exc: # pylint: disable=E0602
log.debug(r'Cannot find key: %s\%s', hive, key, exc_info=True)
return False, r'Cannot find key: {0}\{1}'.format(hive, key)
finally:
if handle:
handle.Close()
return values
def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
Usage:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: python
import salt.utils.win_reg
winreg.read_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version')
Usage:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: python
import salt.utils.win_reg
winreg.read_value(hive='HKLM', key='SOFTWARE\\Salt')
'''
# If no name is passed, the default value of the key will be returned
# The value name is Default
# Setup the return array
local_hive = _to_unicode(hive)
local_key = _to_unicode(key)
local_vname = _to_unicode(vname)
ret = {'hive': local_hive,
'key': local_key,
'vname': local_vname,
'vdata': None,
'success': True}
if not vname:
ret['vname'] = '(Default)'
registry = Registry()
try:
hkey = registry.hkeys[local_hive]
except KeyError:
raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive))
access_mask = registry.registry_32[use_32bit_registry]
try:
handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
try:
# RegQueryValueEx returns and accepts unicode data
vdata, vtype = win32api.RegQueryValueEx(handle, local_vname)
if vdata or vdata in [0, '']:
# Only convert text types to unicode
ret['vtype'] = registry.vtype_reverse[vtype]
if vtype == win32con.REG_MULTI_SZ:
ret['vdata'] = [_to_mbcs(i) for i in vdata]
elif vtype in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]:
ret['vdata'] = _to_mbcs(vdata)
else:
ret['vdata'] = vdata
else:
ret['comment'] = 'Empty Value'
except Exception as exc:
if exc.winerror == 2 and vname is None:
ret['vdata'] = ('(value not set)')
ret['vtype'] = 'REG_SZ'
else:
msg = 'Cannot find {0} in {1}\\{2}' \
''.format(local_vname, local_hive, local_key)
log.trace(exc)
log.trace(msg)
ret['comment'] = msg
ret['success'] = False
except Exception as exc: # pylint: disable=E0602
msg = 'Cannot find key: {0}\\{1}'.format(local_hive, local_key)
log.trace(exc)
log.trace(msg)
ret['comment'] = msg
ret['success'] = False
return ret
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary. You can pass base64 encoded using the ``binascii``
built-in module. Use ``binascii.b2a_base64('your data')``
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If not passed, the Key will be
created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
Usage:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: python
import salt.utils.win_reg
winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version', vdata='2015.5.2')
Usage:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: python
import salt.utils.win_reg
winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata=1.2)
Usage:
In this next example vdata is properly quoted and should succeed.
.. code-block:: python
import salt.utils.win_reg
winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='str_data', vdata='1.2')
Usage:
This is an example of using vtype REG_BINARY. Both ``set_value``
commands will set the same value ``Salty Test``
.. code-block:: python
import salt.utils.win_reg
winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data', vdata='Salty Test', vtype='REG_BINARY')
import binascii
bin_data = binascii.b2a_base64('Salty Test')
winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='bin_data_encoded', vdata=bin_data, vtype='REG_BINARY')
Usage:
An example using vtype REG_MULTI_SZ is as follows:
.. code-block:: python
import salt.utils.win_reg
winreg.set_value(hive='HKLM', key='SOFTWARE\\Salt', vname='list_data', vdata=['Salt', 'is', 'great'], vtype='REG_MULTI_SZ')
'''
local_hive = _to_unicode(hive)
local_key = _to_unicode(key)
local_vname = _to_unicode(vname)
local_vtype = _to_unicode(vtype)
registry = Registry()
try:
hkey = registry.hkeys[local_hive]
except KeyError:
raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive))
vtype_value = registry.vtype[local_vtype]
access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS
local_vdata = cast_vdata(vdata=vdata, vtype=local_vtype)
if volatile:
create_options = registry.opttype['REG_OPTION_VOLATILE']
else:
create_options = registry.opttype['REG_OPTION_NON_VOLATILE']
handle = None
try:
handle, _ = win32api.RegCreateKeyEx(hkey, local_key, access_mask,
Options=create_options)
win32api.RegSetValueEx(handle, local_vname, 0, vtype_value, local_vdata)
win32api.RegFlushKey(handle)
broadcast_change()
return True
except (win32api.error, SystemError, ValueError, TypeError): # pylint: disable=E0602
log.exception('Encountered error setting registry value')
return False
finally:
if handle:
win32api.RegCloseKey(handle)
def cast_vdata(vdata=None, vtype='REG_SZ'):
'''
Cast the ``vdata` value to the appropriate data type for the registry type
specified in ``vtype``
Args:
vdata (str, int, list, bytes): The data to cast
vtype (str):
The type of data to be written to the registry. Must be one of the
following:
- REG_BINARY
- REG_DWORD
- REG_EXPAND_SZ
- REG_MULTI_SZ
- REG_QWORD
- REG_SZ
Returns:
The vdata cast to the appropriate type. Will be unicode string, binary,
list of unicode strings, or int
Usage:
.. code-block:: python
import salt.utils.win_reg
winreg.cast_vdata(vdata='This is the string', vtype='REG_SZ')
'''
# Check data type and cast to expected type
# int will automatically become long on 64bit numbers
# https://www.python.org/dev/peps/pep-0237/
registry = Registry()
vtype_value = registry.vtype[vtype]
# String Types to Unicode
if vtype_value in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]:
return _to_unicode(vdata)
# Don't touch binary... if it's binary
elif vtype_value == win32con.REG_BINARY:
if isinstance(vdata, six.text_type):
# Unicode data must be encoded
return vdata.encode('utf-8')
return vdata
# Make sure REG_MULTI_SZ is a list of strings
elif vtype_value == win32con.REG_MULTI_SZ:
return [_to_unicode(i) for i in vdata]
# Make sure REG_QWORD is a 64 bit integer
elif vtype_value == win32con.REG_QWORD:
return vdata if six.PY3 else long(vdata) # pylint: disable=W1699
# Everything else is int
else:
return int(vdata)
def delete_key_recursive(hive, key, use_32bit_registry=False):
'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
Usage:
The following example will remove ``salt`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: python
import salt.utils.win_reg
winreg.delete_key_recursive(hive='HKLM', key='SOFTWARE\\DeleteMe')
'''
local_hive = _to_unicode(hive)
local_key = _to_unicode(key)
# Instantiate the registry object
registry = Registry()
try:
hkey = registry.hkeys[local_hive]
except KeyError:
raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive))
key_path = local_key
access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS
if not key_exists(local_hive, local_key, use_32bit_registry):
return False
if (len(key) > 1) and (key.count('\\', 1) < registry.subkey_slash_check[hkey]):
log.error(
'Hive:%s Key:%s; key is too close to root, not safe to remove',
hive, key
)
return False
# Functions for traversing the registry tree
def _subkeys(_key):
'''
Enumerate keys
'''
i = 0
while True:
try:
subkey = win32api.RegEnumKey(_key, i)
yield _to_mbcs(subkey)
i += 1
except Exception: # pylint: disable=E0602
break
def _traverse_registry_tree(_hkey, _keypath, _ret, _access_mask):
'''
Traverse the registry tree i.e. dive into the tree
'''
_key = win32api.RegOpenKeyEx(_hkey, _keypath, 0, _access_mask)
for subkeyname in _subkeys(_key):
subkeypath = '{0}\\{1}'.format(_keypath, subkeyname)
_ret = _traverse_registry_tree(_hkey, subkeypath, _ret, access_mask)
_ret.append(subkeypath)
return _ret
# Get a reverse list of registry keys to be deleted
key_list = []
key_list = _traverse_registry_tree(hkey, key_path, key_list, access_mask)
# Add the top level key last, all subkeys must be deleted first
key_list.append(key_path)
ret = {'Deleted': [],
'Failed': []}
# Delete all sub_keys
for sub_key_path in key_list:
try:
key_handle = win32api.RegOpenKeyEx(hkey, sub_key_path, 0, access_mask)
win32api.RegDeleteKey(key_handle, '')
ret['Deleted'].append(r'{0}\{1}'.format(hive, sub_key_path))
except WindowsError as exc: # pylint: disable=E0602
log.error(exc, exc_info=True)
ret['Failed'].append(r'{0}\{1} {2}'.format(hive, sub_key_path, exc))
broadcast_change()
return ret
def delete_value(hive, key, vname=None, use_32bit_registry=False):
'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Return:
bool: True if successful, otherwise False
Usage:
.. code-block:: python
import salt.utils.win_reg
winreg.delete_value(hive='HKLM', key='SOFTWARE\\SaltTest', vname='version')
'''
local_hive = _to_unicode(hive)
local_key = _to_unicode(key)
local_vname = _to_unicode(vname)
registry = Registry()
try:
hkey = registry.hkeys[local_hive]
except KeyError:
raise CommandExecutionError('Invalid Hive: {0}'.format(local_hive))
access_mask = registry.registry_32[use_32bit_registry] | win32con.KEY_ALL_ACCESS
handle = None
try:
handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
win32api.RegDeleteValue(handle, local_vname)
broadcast_change()
return True
except Exception as exc: # pylint: disable=E0602
if exc.winerror == 2:
return None
else:
log.error(exc, exc_info=True)
log.error('Hive: %s', local_hive)
log.error('Key: %s', local_key)
log.error('ValueName: %s', local_vname)
log.error('32bit Reg: %s', use_32bit_registry)
return False
finally:
if handle:
win32api.RegCloseKey(handle)