forked from tranquilit/WAPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetuphelpers.py
2294 lines (1978 loc) · 86.6 KB
/
setuphelpers.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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------
# This file is part of WAPT
# Copyright (C) 2013 Tranquil IT Systems http://www.tranquil.it
# WAPT aims to help Windows systems administrators to deploy
# setup and update applications on users PC.
#
# WAPT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WAPT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WAPT. If not, see <http://www.gnu.org/licenses/>.
#
# -----------------------------------------------------------------------
__version__ = "0.9.8"
import os
import sys
import logging
import tempfile
import shutil
import shlex
import _subprocess
import subprocess
from subprocess import Popen, PIPE
import psutil
import win32api
import win32net
import win32netcon
import win32security
import ntsecuritycon
import win32con
import win32pdhutil
import msilib
import win32service
import win32serviceutil
import glob
import ctypes
import requests
import time
import datetime
import socket
import _winreg
import platform
import winshell
import pythoncom
from win32com.shell import shell, shellcon
from win32com.taskscheduler import taskscheduler
import locale
import types
import re
import threading
from types import ModuleType
import codecs
from waptpackage import PackageEntry
from iniparse import RawConfigParser
import keyfinder
logger = logging.getLogger()
# common windows diectories
desktop = winshell.desktop
application_data = winshell.application_data
bookmarks = winshell.bookmarks
start_menu = winshell.start_menu
programs = winshell.programs
startup = winshell.startup
my_documents= winshell.my_documents
recent = winshell.recent
sendto = winshell.sendto
def ensure_dir(f):
"""Be sure the directory of f exists on disk. Make it if not"""
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
# from opsi
def ensure_unicode(data):
ur"""Return a unicode string from data object
>>> ensure_unicode(str('éé'))
u'\xe9\xe9'
>>> ensure_unicode(u'éé')
u'\xe9\xe9'
>>> ensure_unicode(Exception("test"))
u'Exception: test'
>>> ensure_unicode(Exception())
u'Exception: '
"""
try:
if type(data) is types.UnicodeType:
return data
if type(data) is types.StringType:
return unicode(data, 'utf8', 'replace')
if isinstance(data,WindowsError):
return u"%s : %s" % (data.args[0], data.args[1].decode(sys.getfilesystemencoding()))
if isinstance(data,(UnicodeDecodeError,UnicodeEncodeError)):
return u"%s : faulty string is '%s'" % (data,repr(data.args[1]))
if isinstance(data,Exception):
try:
return u"%s: %s" % (data.__class__.__name__,("%s"%data).decode(sys.getfilesystemencoding()))
except:
try:
return u"%s: %s" % (data.__class__.__name__,("%s"%data).decode('utf8'))
except:
try:
return u"%s: %s" % (data.__class__.__name__,u"%s"%data)
except:
return u"%s" % (data.__class__.__name__,)
if hasattr(data, '__unicode__'):
try:
return data.__unicode__()
except:
pass
return unicode(data)
except:
if logger.level != logging.DEBUG:
return("Error in ensure_unicode / %s"%(repr(data)))
else:
raise
def create_shortcut(path, target='', arguments='', wDir='', icon=''):
"""Create a windows shortcut
path - As what file should the shortcut be created?
target - What command should the desktop use?
arguments - What arguments should be supplied to the command?
wdir - What folder should the command start in?
icon - (filename, index) What icon should be used for the shortcut?
>>> create_shortcut(r'c:\\tmp\\test.lnk',target='c:\\wapt\\wapt-get.exe')
"""
ext = path[-3:]
if ext == 'url':
shortcut = file(path, 'w')
shortcut.write('[InternetShortcut]\n')
shortcut.write('URL=%s\n' % target)
shortcut.write('IconFile="%s"\n' % icon)
shortcut.write('IconIndex=0\n')
shortcut.close()
else:
winshell.CreateShortcut(path,target,arguments,wDir,(icon,0),'')
def create_desktop_shortcut(label, target='', arguments ='', wDir='', icon=''):
"""Create a desktop shortcut link for all users
label : Name of the shorcut (.lnk extension is appended if not provided)
target : path to application
arguments : argument to pass to application
wDir : working directory
icon : path to ico file
>>> create_desktop_shortcut(r'WAPT Console Management',target='c:\\wapt\\waptconsole.exe')
>>> create_desktop_shortcut(r'WAPT local status',target='http://localhost:8088/')
"""
if not (label.endswith('.lnk') or label.endswith('.url')):
if target.startswith('http://') or target.startswith('https://'):
label += '.url'
else:
label += '.lnk'
sc_path = os.path.join(desktop(1),label)
if os.path.isfile(sc_path):
os.remove(sc_path)
create_shortcut(sc_path,target,arguments, wDir,icon)
return sc_path
def create_user_desktop_shortcut(label, target='',arguments='', wDir='', icon=''):
"""Create a desktop shortcut link for current user
label : Name of the shorcut (.lnk extension is appended if not provided)
target : path to application
arguments : argument to pass to application
wDir : working directory
icon : path to ico file
"""
if not (label.endswith('.lnk') or label.endswith('.url')):
if target.startswith('http://') or target.startswith('https://'):
label += '.url'
else:
label += '.lnk'
sc_path = os.path.join(desktop(0),label)
if os.path.isfile(sc_path):
os.remove(sc_path)
create_shortcut(sc_path,target,arguments,wDir,icon)
return sc_path
def create_programs_menu_shortcut(label, target='', arguments='', wDir='', icon=''):
"""Create a program menu shortcut link for all users
label : Name of the shorcut (.lnk extension is appended if not provided)
target : path to application
arguments : argument to pass to application
wDir : working directory
icon : path to ico file
"""
if not (label.endswith('.lnk') or label.endswith('.url')):
label += '.lnk'
sc = os.path.join(start_menu(1),label)
if os.path.isfile(sc):
os.remove(sc)
create_shortcut(sc,target,arguments,wDir,icon)
return sc
def create_user_programs_menu_shortcut(label, target='', arguments='', wDir='', icon=''):
if not (label.endswith('.lnk') or label.endswith('.url')):
label += '.lnk'
sc = os.path.join(start_menu(0),label)
if os.path.isfile(sc):
os.remove(sc)
create_shortcut(sc,target,arguments,wDir,icon)
return sc
def wgets(url,proxies=None):
"""Return the content of a remote resource as a String
>>> data = wgets('http://wapt:8080/info')
>>> "client_version" in data and "server_version" in data
True
"""
r = requests.get(url,proxies=proxies,verify=False)
if r.ok:
return r.text
else:
r.raise_for_status()
def wget(url,target,printhook=None,proxies=None,connect_timeout=10,download_timeout=None):
r"""Copy the contents of a file from a given URL
to a local file.
>>> respath = wget('http://wapt.tranquil.it/wapt/tis-firefox_28.0.0-1_all.wapt','c:\\tmp\\test.wapt',proxies={'http':'http://proxy:3128'})
???
>>> os.stat(respath).st_size>10000
True
>>> respath = wget('http://localhost:8088/runstatus','c:\\tmp\\test.json')
???
"""
start_time = time.time()
last_time_display = 0.0
last_downloaded = 0
def reporthook(received,total):
total = float(total)
if total>1 and received>1:
# print only every second or at end
if (time.time()-start_time>1) and ((time.time()-last_time_display>=1) or (received>=total)):
speed = received /(1024.0 * (time.time()-start_time))
if printhook:
printhook(received,total,speed,url)
else:
try:
if received == 0:
print u"Downloading %s (%.1f Mb)" % (url,int(total)/1024/1024)
elif received>=total:
print u" -> download finished (%.0f Kb/s)" % (total /(1024.0*(time.time()+.001-start_time)))
else:
print u'%i / %i (%.0f%%) (%.0f KB/s)\r' % (received,total,100.0*received/total,speed ),
except:
return False
return True
else:
return False
if os.path.isdir(target):
target = os.path.join(target,'')
(dir,filename) = os.path.split(target)
if not filename:
filename = url.split('/')[-1]
if not dir:
dir = os.getcwd()
if not os.path.isdir(dir):
os.makedirs(dir)
httpreq = requests.get(url,stream=True, proxies=proxies, timeout=connect_timeout,verify=False)
total_bytes = int(httpreq.headers['content-length'])
# 1Mb max, 1kb min
chunk_size = min([1024*1024,max([total_bytes/100,2048])])
cnt = 0
reporthook(last_downloaded,total_bytes)
with open(os.path.join(dir,filename),'wb') as output_file:
last_time_display = time.time()
last_downloaded = 0
if httpreq.ok:
for chunk in httpreq.iter_content(chunk_size=chunk_size):
output_file.write(chunk)
if download_timeout is not None and (time.time()-start_time>download_timeout):
raise requests.Timeout(r'Download of %s takes more than the requested %ss'%(url,download_timeout))
if reporthook(cnt*len(chunk),total_bytes):
last_time_display = time.time()
last_downloaded += len(chunk)
cnt +=1
if reporthook(last_downloaded,total_bytes):
last_time_display = time.time()
else:
httpreq.raise_for_status()
return os.path.join(dir,filename)
def filecopyto(filename,target):
"""Copy file from package temporary directory to target directory
target is either a full filename or a directory name
if filename is .exe or .dll, logger prints version numbers
>>> if not os.path.isfile('c:/tmp/fc.test'):
... with open('c:/tmp/fc.test','wb') as f:
... f.write('test')
>>> if not os.path.isdir('c:/tmp/target'):
... os.mkdir('c:/tmp/target')
>>> if os.path.isfile('c:/tmp/target/fc.test'):
... os.unlink('c:/tmp/target/fc.test')
>>> filecopyto('c:/tmp/fc.test','c:/tmp/target')
>>> os.path.isfile('c:/tmp/target/fc.test')
True
"""
(dir,fn) = os.path.split(filename)
if not dir:
dir = os.getcwd()
if os.path.isdir(target):
target = os.path.join(target,os.path.basename(filename))
if os.path.isfile(target):
if os.path.splitext(target)[1] in ('.exe','.dll'):
ov = get_file_properties(target)['FileVersion']
nv = get_file_properties(filename)['FileVersion']
logger.info(u'Replacing %s (%s) -> %s' % (ensure_unicode(target),ov,nv))
else:
logger.info(u'Replacing %s' % target)
else:
if os.path.splitext(target)[1] in ('.exe','.dll'):
nv = get_file_properties(filename)['FileVersion']
logger.info(u'Copying %s (%s)' % (ensure_unicode(target),nv))
else:
logger.info(u'Copying %s' % (ensure_unicode(target)))
shutil.copy(filename,target)
# Copy of an entire tree from install temp directory to target
def default_oncopy(msg,src,dst):
logger.debug(u'%s : "%s" to "%s"' % (ensure_unicode(msg),ensure_unicode(src),ensure_unicode(dst)))
return True
def default_skip(src,dst):
return False
def default_overwrite(src,dst):
return True
def default_overwrite_older(src,dst):
if os.stat(src).st_mtime <= os.stat(dst).st_mtime:
logger.debug(u'Skipping, file on target is newer than source: "%s"' % (dst,))
return False
else:
logger.debug(u'Overwriting file on target is older than source: "%s"' % (dst,))
return True
def register_ext(appname,fileext,shellopen,icon=None,otherverbs=[]):
"""Associates a file extension with an application, and command to open it
>>> register_ext(
... appname='WAPT.Package',
... fileext='.wapt',
... icon=r'c:\wapt\wapt.ico',
... shellopen=r'"7zfm.exe" "%1"',otherverbs=[
... ('install',r'"c:\wapt\wapt-get.exe" install "%1"'),
... ('edit',r'"c:\wapt\wapt-get.exe" edit "%1"'),
... ])
>>>
"""
def setvalue(key,path,value):
rootpath = os.path.dirname(path)
name = os.path.basename(path)
k = reg_openkey_noredir(key,path,sam=KEY_READ | KEY_WRITE,create_if_missing=True)
if value != None:
reg_setvalue(k,'',value)
filetype = appname+fileext
setvalue(HKEY_CLASSES_ROOT,fileext,filetype)
setvalue(HKEY_CLASSES_ROOT,filetype,appname+ " file")
if icon:
setvalue(HKEY_CLASSES_ROOT,makepath(filetype,"DefaultIcon"),icon)
setvalue(HKEY_CLASSES_ROOT,makepath(filetype,"shell"),'')
setvalue(HKEY_CLASSES_ROOT,makepath(filetype,"shell","open"),'')
setvalue(HKEY_CLASSES_ROOT,makepath(filetype,"shell","open","command"),shellopen)
if otherverbs:
for (verb,cmd) in otherverbs:
setvalue(HKEY_CLASSES_ROOT,makepath(filetype,"shell",verb),'')
setvalue(HKEY_CLASSES_ROOT,makepath(filetype,"shell",verb,"command"),cmd)
def copytree2(src, dst, ignore=None,onreplace=default_skip,oncopy=default_oncopy,enable_replace_at_reboot=True):
"""Copy src directory to dst directory. dst is created if it doesn't exists
src can be relative to installation temporary dir
oncopy is called for each file copy. if False is returned, copy is skipped
onreplace is called when a file will be overwritten.
"""
logger.debug('Copy tree from "%s" to "%s"' % (ensure_unicode(src),ensure_unicode(dst)))
# path relative to temp directory...
tempdir = os.getcwd()
if not os.path.isdir(src) and os.path.isdir(os.path.join(tempdir,src)):
src = os.path.join(tempdir,src)
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
if not os.path.isdir(dst):
if oncopy('create directory',src,dst):
os.makedirs(dst)
errors = []
skipped = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if os.path.isdir(srcname):
if oncopy('directory',srcname,dstname):
copytree2(srcname, dstname, ignore = ignore,onreplace=onreplace,oncopy=oncopy)
else:
try:
if os.path.isfile(dstname):
if onreplace(srcname,dstname) and oncopy('overwrites',srcname,dstname):
os.unlink(dstname)
shutil.copy2(srcname, dstname)
else:
if oncopy('copy',srcname,dstname):
shutil.copy2(srcname, dstname)
except (IOError, os.error) as e:
# file is locked...
if enable_replace_at_reboot and e.errno in (5,13):
filecopyto(srcname,dstname+'.pending')
replace_at_next_reboot(tmp_filename=dstname+'.pending',target_filename=dstname)
else:
raise
except (IOError, os.error), why:
logger.critical(u'Error copying from "%s" to "%s" : %s' % (ensure_unicode(src),ensure_unicode(dst),ensure_unicode(why)))
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except shutil.Error, err:
#errors.extend(err.args[0])
errors.append(err)
try:
shutil.copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
except OSError, why:
errors.extend((src, dst, str(why)))
if errors:
raise shutil.Error(errors)
class RunReader(threading.Thread):
# helper thread to read output of run command
def __init__(self, callable, *args, **kwargs):
super(RunReader, self).__init__()
self.callable = callable
self.args = args
self.kwargs = kwargs
self.setDaemon(True)
def run(self):
try:
self.callable(*self.args, **self.kwargs)
except Exception, e:
print e
class TimeoutExpired(Exception):
"""This exception is raised when the timeout expires while waiting for a
child process.
"""
def __init__(self, cmd, output=None, timeout=None):
self.cmd = cmd
self.output = output
self.timeout = timeout
def __str__(self):
return ("Command '%s' timed out after %s seconds with output '%s'" %
(self.cmd, self.timeout, self.output))
def run(*cmd,**args):
"""Run the command cmd and return the output and error text
shell=True is assumed
timeout=600 (seconds) after that time, a TimeoutExpired is raised
if return code of cmd is non zero, a CalledProcessError is raised
on_write : called when a new line is printed on stdout or stderr by the subprocess
accept_returncodes=[0,1601]
pidlist : list wher to append
"""
logger.info(u'Run "%s"' % (ensure_unicode(cmd),))
output = []
def worker(pipe,on_write=None):
while True:
line = pipe.readline()
if line == '':
break
else:
if on_write:
on_write(line)
output.append(line)
if 'timeout' in args:
timeout = args['timeout']
del args['timeout']
else:
timeout = 10*60.0
if not "shell" in args:
args['shell']=True
if not 'accept_returncodes' in args:
# 1603 : souvent renvoyé quand déjà installé.
# 3010 : reboot required.
valid_returncodes = [0,1603,3010]
else:
valid_returncodes = args['accept_returncodes']
del args['accept_returncodes']
if 'pidlist' in args and isinstance(args['pidlist'],list):
pidlist = args['pidlist']
args.pop('pidlist')
else:
pidlist = []
proc = psutil.Popen(*cmd, bufsize=1, stdout=PIPE, stderr=PIPE,**args)
# keep track of launched pid if required by providing a pidlist argument to run
if not proc.pid in pidlist:
pidlist.append(proc.pid)
stdout_worker = RunReader(worker, proc.stdout,args.get('on_write',None))
stderr_worker = RunReader(worker, proc.stderr,args.get('on_write',None))
stdout_worker.start()
stderr_worker.start()
stdout_worker.join(timeout)
if stdout_worker.is_alive():
# kill the task and all subtasks
if proc.pid in pidlist:
pidlist.remove(proc.pid)
killtree(proc.pid)
raise TimeoutExpired(cmd,timeout,''.join(output))
stderr_worker.join(timeout)
if stderr_worker.is_alive():
if proc.pid in pidlist:
pidlist.remove(proc.pid)
killtree(proc.pid)
raise TimeoutExpired(cmd,timeout,''.join(output))
proc.returncode = _subprocess.GetExitCodeProcess(proc._handle)
if proc.pid in pidlist:
pidlist.remove(proc.pid)
killtree(proc.pid)
if not proc.returncode in valid_returncodes:
raise subprocess.CalledProcessError(proc.returncode,cmd,''.join(output))
else:
if proc.returncode == 0:
logger.info(u'%s command returns code %s' % (ensure_unicode(cmd),proc.returncode))
else:
logger.warning(u'%s command returns code %s' % (ensure_unicode(cmd),proc.returncode))
return ensure_unicode(''.join(output))
def run_notfatal(*cmd,**args):
"""Runs the command and wait for it termination
returns output, don't raise exception if exitcode is not null but return '' """
try:
return run(*cmd,**args)
except Exception,e:
print u'Warning : %s' % ensure_unicode(e)
return ''
def shell_launch(cmd):
"""Launch a command (without arguments) but doesn't wait for its termination
.>>> open('c:/tmp/test.txt','w').write('Test line')
.>>> shell_launch('c:/tmp/test.txt')
"""
os.startfile(cmd)
def isrunning(processname):
"""Check if a process is running, example isrunning('explorer')"""
processname = processname.lower()
for p in psutil.process_iter():
try:
if p.name().lower() == processname or p.name().lower() == processname+'.exe':
return True
except (psutil.AccessDenied,psutil.NoSuchProcess):
pass
return False
def killalltasks(exenames,include_children=True):
"""Kill the task by their exename : example killalltasks('explorer.exe') """
logger.debug('Kill tasks %s' % (exenames,))
if not isinstance(exenames,list):
exenames = [exenames]
exenames = [exe.lower() for exe in exenames]+[exe.lower()+'.exe' for exe in exenames]
for p in psutil.process_iter():
try:
if p.name().lower() in exenames:
logger.debug('Kill process %i' % (p.pid,))
if include_children:
killtree(p.pid)
else:
p.kill()
except (psutil.AccessDenied,psutil.NoSuchProcess):
pass
"""
for c in exenames:
run(u'taskkill /t /im "%s" /f' % c)
"""
def killtree(pid, including_parent=True):
try:
parent = psutil.Process(pid)
if parent:
for child in parent.get_children(recursive=True):
child.kill()
if including_parent:
parent.kill()
except psutil.NoSuchProcess as e:
pass
def processnames_list():
"""return all process name of running processes in lower case"""
return list(set([p.name().lower() for p in psutil.get_process_list()]))
def find_processes(process_name):
"""Return list of Process having process_name"""
process_name = process_name.lower()
result = []
for p in psutil.process_iter():
try:
if p.name().lower() in [process_name,process_name+'.exe']:
result.append(p)
except (psutil.AccessDenied,psutil.NoSuchProcess):
pass
return result
def messagebox(title,msg):
win32api.MessageBox(0, msg, title, win32con.MB_ICONINFORMATION)
def showmessage(msg):
win32api.MessageBox(0, msg, 'Information', win32con.MB_ICONINFORMATION)
def programfiles64():
"""Return 64 bits program folder"""
if 'PROGRAMW6432' in os.environ :
return os.environ['PROGRAMW6432']
else:
return os.environ['PROGRAMFILES']
def programfiles():
"""Return native program directory, ie C:\Program Files for both 64 and 32 bits"""
#return get_path(shellcon.CSIDL_PROGRAM_FILES)
if 'PROGRAMW6432' in os.environ:
return os.environ['PROGRAMW6432']
else:
return os.environ['PROGRAMFILES']
def programfiles32():
"""Return 32bits applications folder."""
if 'PROGRAMW6432' in os.environ and 'PROGRAMFILES(X86)' in os.environ:
return os.environ['PROGRAMFILES(X86)']
else:
return os.environ['PROGRAMFILES']
def iswin64():
# could be
# return platform.machine()=='AMD64'
return 'PROGRAMW6432' in os.environ
def get_computername():
"""Return host name (without domain part)"""
return socket.gethostname()
def get_hostname():
"""Return host fully qualified domain name in lower case"""
return socket.getfqdn().lower()
def get_domain_fromregistry():
"""Return main DNS domain of the computer"""
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters")
try:
(domain,atype) = _winreg.QueryValueEx(key,'Domain')
if domain=='':
(domain,atype) = _winreg.QueryValueEx(key,'DhcpDomain')
except:
try:
(domain,atype) = _winreg.QueryValueEx(key,'DhcpDomain')
except:
domain = None
return domain
def get_loggedinusers():
result = []
try:
import win32ts
for session in win32ts.WTSEnumerateSessions():
if session['State']==win32ts.WTSActive:
result.append(win32ts.WTSQuerySessionInformation(win32ts.WTS_CURRENT_SERVER_HANDLE,session['SessionId'],win32ts.WTSUserName))
return result
except:
return [get_current_user()]
def registered_organization():
return registry_readstring(HKEY_LOCAL_MACHINE,r'SOFTWARE\Microsoft\Windows NT\CurrentVersion','RegisteredOrganization')
def _environ_params(dict_or_module={}):
"""set some environment params in the supplied module or dict"""
if type(dict_or_module) is dict:
params_dict = dict_or_module
else:
params_dict = {}
params_dict['programfiles32'] = programfiles32()
params_dict['programfiles64'] = programfiles64()
params_dict['programfiles'] = programfiles()
params_dict['domainname'] = get_domain_fromregistry()
params_dict['computername'] = os.environ['COMPUTERNAME']
if type(dict_or_module) is ModuleType:
for k,v in params_dict.items():
setattr(dict_or_module,k,v)
return params_dict
###########
HKEY_CLASSES_ROOT = _winreg.HKEY_CLASSES_ROOT
HKEY_CURRENT_USER = _winreg.HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
HKEY_USERS = _winreg.HKEY_USERS
HKEY_CURRENT_CONFIG = _winreg.HKEY_CURRENT_CONFIG
KEY_WRITE = _winreg.KEY_WRITE
KEY_READ = _winreg.KEY_READ
KEY_ALL_ACCESS = _winreg.KEY_ALL_ACCESS
REG_SZ = _winreg.REG_SZ
REG_MULTI_SZ = _winreg.REG_MULTI_SZ
REG_DWORD = _winreg.REG_DWORD
REG_EXPAND_SZ = _winreg.REG_EXPAND_SZ
def reg_closekey(hkey):
"""Close a registry key opened with reg_openkey_noredir"""
_winreg.CloseKey(hkey)
def reg_openkey_noredir(key, sub_key, sam=_winreg.KEY_READ,create_if_missing=False):
"""Open the registry key\subkey with access rights sam
Returns a key handle for reg_getvalue and reg_set_value
key : HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
sub_key : string like "software\\microsoft\\windows\\currentversion"
sam : a boolean comination of KEY_READ | KEY_WRITE
create_if_missing : True to create the sub_key if not exists, access rights will include KEY_WRITE
"""
try:
if platform.machine() == 'AMD64':
result = _winreg.OpenKey(key,sub_key,0, sam | _winreg.KEY_WOW64_64KEY)
else:
result = _winreg.OpenKey(key,sub_key,0,sam)
return result
except WindowsError,e:
if e.errno == 2:
if create_if_missing:
if platform.machine() == 'AMD64':
return _winreg.CreateKeyEx(key,sub_key,0, sam | _winreg.KEY_READ| _winreg.KEY_WOW64_64KEY | _winreg.KEY_WRITE )
else:
return _winreg.CreateKeyEx(key,sub_key,0,sam | _winreg.KEY_READ | _winreg.KEY_WRITE )
else:
raise WindowsError(e.errno,'The key %s can not be opened' % sub_key)
def reg_getvalue(key,name,default=None):
"""Return the value of specified name inside 'key' folder
key : handle of registry key as returned by reg_openkey_noredir()
name : value name or None for key default value
default : value returned if specified name doesn't exist
"""
try:
value = _winreg.QueryValueEx(key,name)[0]
if type(value) is types.StringTypes:
return ensure_unicode(value)
else:
return value
except WindowsError,e:
if e.errno in(259,2):
# WindowsError: [Errno 259] No more data is available
# WindowsError: [Error 2] Le fichier spécifié est introuvable
return default
else:
raise
def reg_setvalue(key,name,value,type=_winreg.REG_SZ ):
"""Set the value of specified name inside 'key' folder
key : handle of registry key as returned by reg_openkey_noredir()
name : value name
type : type of value (REG_SZ,REG_MULTI_SZ,REG_DWORD,REG_EXPAND_SZ)
"""
return _winreg.SetValueEx(key,name,0,type,value)
def reg_delvalue(key,name):
"""Remove the value of specified name inside 'key' folder
key : handle of registry key as returned by reg_openkey_noredir()
name : value name
"""
try:
_winreg.DeleteValue(key,name)
return True
except WindowsError,e:
# WindowsError: [Errno 2] : file does not exist
if e.winerror == 2:
return False
else:
raise
def registry_setstring(root,path,keyname,value,type=_winreg.REG_SZ):
"""Set the value of a string key in registry
root : HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
path : string like "software\\microsoft\\windows\\currentversion"
or "software\\wow6432node\\microsoft\\windows\\currentversion"
keyname : None for value of key or str for a specific value like 'CommonFilesDir'
value : string to put in keyname
the path can be either with backslash or slash"""
path = path.replace(u'/',u'\\')
key = reg_openkey_noredir(root,path,sam=KEY_WRITE,create_if_missing=True)
result = reg_setvalue(key,keyname,value,type=type)
return result
def registry_readstring(root,path,keyname,default=''):
"""Return a string from registry
root : HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
path : string like "software\\microsoft\\windows\\currentversion"
or "software\\wow6432node\\microsoft\\windows\\currentversion"
keyname : None for value of key or str for a specific value like 'CommonFilesDir'
the path can be either with backslash or slash
>>> registry_readstring(HKEY_LOCAL_MACHINE,r'SYSTEM/CurrentControlSet/services/Tcpip/Parameters','Hostname')
u'HTLAPTOP'
"""
path = path.replace(u'/',u'\\')
try:
key = reg_openkey_noredir(root,path)
result = reg_getvalue(key,keyname,default)
return result
except:
return default
def registry_set(root,path,keyname,value,type=None):
"""Set the value of a key in registry, tajing in account calue type
root : HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
path : string like "software\\microsoft\\windows\\currentversion"
or "software\\wow6432node\\microsoft\\windows\\currentversion"
keyname : None for value of key or str for a specific value like 'CommonFilesDir'
value : value (integer or string type) to put in keyname
the path can be either with backslash or slash"""
path = path.replace(u'/',u'\\')
key = reg_openkey_noredir(root,path,sam=KEY_WRITE,create_if_missing=True)
if not type:
if isinstance(value,list):
type = REG_MULTI_SZ
elif isinstance(value,int):
type = REG_DWORD
else:
type = REG_SZ
result = reg_setvalue(key,keyname,value,type=type)
return result
def registry_delete(root,path,valuename):
"""Delete the valuename inside specified registry path
root : HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
path : string like "software\\microsoft\\windows\\currentversion"
or "software\\wow6432node\\microsoft\\windows\\currentversion"
valuename : None for value of key or str for a specific value like 'CommonFilesDir'
the path can be either with backslash or slash
"""
result = False
path = path.replace(u'/',u'\\')
try:
key = reg_openkey_noredir(root,path,sam=KEY_WRITE)
result = _winreg.DeleteValue(key,valuename)
except WindowsError as e:
logger.warning('registry_delete:%s'%ensure_unicode(e))
return result
def inifile_hasoption(inifilename,section,key):
"""Read a string parameter from inifile"""
inifile = RawConfigParser()
inifile.read(inifilename)
return inifile.has_section(section) and inifile.has_option(section,key)
def inifile_readstring(inifilename,section,key,default=None):
"""Read a string parameter from inifile"""
inifile = RawConfigParser()
inifile.read(inifilename)
if inifile.has_section(section) and inifile.has_option(section,key):
return inifile.get(section,key)
else:
return default
def inifile_writestring(inifilename,section,key,value):
"""Write a string parameter to inifile"""
inifile = RawConfigParser()
inifile.read(inifilename)
if not inifile.has_section(section):
inifile.add_section(section)
inifile.set(section,key,value)
inifile.write(open(inifilename,'w'))
class disable_file_system_redirection:
"""disable wow3264 redirection
.>>> with disable_file_system_redirection():
....
"""
if iswin64():
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
else:
_disable = None
_revert = None
def __enter__(self):
if self._disable:
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self._revert and self.success:
self._revert(self.old_value)
def system32():
return win32api.GetSystemDirectory()
def set_file_visible(path):
"""unset the hidden attribute of path"""
FILE_ATTRIBUTE_HIDDEN = 0x02
old_att = ctypes.windll.kernel32.GetFileAttributesW(unicode(path))
ret = ctypes.windll.kernel32.SetFileAttributesW(unicode(path),old_att & ~FILE_ATTRIBUTE_HIDDEN)
if not ret:
raise ctypes.WinError()
def set_file_hidden(path):
"""set the hidden attribute of path"""
FILE_ATTRIBUTE_HIDDEN = 0x02
old_att = ctypes.windll.kernel32.GetFileAttributesW(unicode(path))
ret = ctypes.windll.kernel32.SetFileAttributesW(unicode(path),old_att | FILE_ATTRIBUTE_HIDDEN)
if not ret:
raise ctypes.WinError()
def replace_at_next_reboot(tmp_filename,target_filename):
"""Create a key in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager
with content :