setuphelpers module¶
- class setuphelpers.PackageEntry(package='', version='0', repo='')¶
Bases: object
Package attributes coming from either control files in WAPT package or local DB
- all_attributes¶
- as_dict()¶
- ascontrol(with_non_control_attributes=False)¶
- asrequirement()¶
resturn package and version for designing this package in depends or install actions
Returns: “packagename (=version)” Return type: str
- download_url()¶
- get(name, default=None)¶
Get PackageEntry property like a dict
>>> r = WaptLocalRepo('C:\wapt\waptserver\repository\wapt-host') >>> print(dict(r['htlaptop.tranquilit.local']))
- inc_build()¶
Increment last number part of version
- load_control_from_dict(adict)¶
- load_control_from_wapt(fname, calc_md5=True)¶
Load package attributes from the control file (utf8 encoded) included in WAPT zipfile fname
- fname can be
- the path to WAPT file itelsef (zip file)
- a list with the lines from control file
- a path to the directory of wapt file unzipped content (debugging)
- make_package_filename()¶
Return the standard package filename based on current attributes
Returns: standard package filename - packagename_version_arch.wapt for softwares - packagename.wapt for group and host. Return type: str
- match(match_expr)¶
Return True if package entry match a package string like ‘tis-package (>=1.0.1-00)
- match_search(search)¶
Return True if entry contains the words in search in correct order and at word boundaries
- match_version(match_expr)¶
Return True if package entry match a version string condition like ‘>=1.0.1-00’
- non_control_attributes = ['localpath', 'filename', 'size', 'repo_url', 'md5sum', 'repo']¶
- optional_attributes = ['section', 'priority', 'maintainer', 'description', 'depends', 'conflicts', 'sources', 'installed_size']¶
- parse_version()¶
Parse version to major, minor, patch, pre-release, build parts.
- required_attributes = ['package', 'version', 'architecture']¶
- save_control_to_wapt(fname)¶
Save package attributes to the control file (utf8 encoded)
- fname can be
- the path to WAPT file itelsef (zip file)
- a path to the directory of wapt file unzipped content (debugging)
- wapt_fullpath()¶
return full local path of wapt package if built
- exception setuphelpers.TimeoutExpired(cmd, output=None, timeout=None)[source]¶
Bases: exceptions.Exception
This exception is raised when the timeout expires while waiting for a child process.
- class setuphelpers.Version(version, members_count=None)¶
Bases: object
- Version object of form 0.0.0
- can compare with respect to natural numbering and not alphabetical
>>> Version('0.10.2') > Version('0.2.5') True >>> Version('0.1.2') < Version('0.2.5') True >>> Version('0.1.2') == Version('0.1.2') True
- setuphelpers.add_shutdown_script(cmd, parameters)[source]¶
Adds a local shutdown script as a local GPO
Parameters: - cmd (str) – absolute path to exe or bat file (without parameters)
- parameters (str) – parameters to append to command
Returns: index of command into the list of shutdown scripts
Return type: int
>>> index = add_shutdown_script(r'c:\wapt\wapt-get.exe','update')
- setuphelpers.add_to_system_path(path)[source]¶
Add path to the global search PATH environment variable if it is not yet
- setuphelpers.application_data(common=0)¶
What folder holds application configuration files?
- setuphelpers.bookmarks(common=0)¶
What folder holds the Explorer favourites shortcuts?
- setuphelpers.common_desktop()[source]¶
return path to public desktop (visible by all users)
>>> common_desktop() u'C:\\Users\\Public\\Desktop'
- setuphelpers.copytree2(src, dst, ignore=None, onreplace=<function default_skip at 0x026385F0>, oncopy=<function default_oncopy at 0x026385B0>, enable_replace_at_reboot=True)[source]¶
- 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.
Parameters: - src (str) – path to source directory (absolute path or relative to package extraction tempdir)
- dst (str) – path to target directory (created if not present)
- ignore (func) – callback func(root_dir,filenames) which returns names to ignore
- onreplace (func) – callback func(src,dst):boolean called when a file will be replaced to decide what to do. default is to not replace if target exist. can be default_override or default_override_older.
- oncopy (func) – callback func(msg,src,dst) called when a file is copied. default is to log in debug level the operation
- enable_replace_at_reboot (boolean) – if True, files which are locked will be scheduled for replace at next reboot
Returns:
Exceptions:
>>> copytree2(r'c:\tranquilit\wapt\tests',r'c:\tranquilit\wapt\tests2') >>> isdir(r'c:\tranquilit\wapt\tests2') True >>> remove_tree(r'c:\tranquilit\wapt\tests2') >>> isdir(r'c:\tranquilit\wapt\tests2') False
- setuphelpers.create_daily_task(name, cmd, parameters, max_runtime=10, repeat_minutes=None, start_hour=None, start_minute=None)[source]¶
creates a Windows scheduled daily task and activate it.
Parameters: - name (str) – name of task for reference
- cmd (str) – command line
- parameters (str) – arguments to append to cmd
- max_runtime (int) – maximum running time in minutes
- repeat_minutes (int) – interval in minutes between run
- start_hour (int) – hour time of start
- start_minute (int) – minute time of start
Returns: scheduled task
Return type: PyITask
- setuphelpers.create_desktop_shortcut(label, target='', arguments='', wDir='', icon='')[source]¶
Create a desktop shortcut link for all users
Parameters: - label (str) – Name of the shorcut (.lnk extension is appended if not provided)
- target (str) – path to application
- arguments (str) – argument to pass to application
- wDir (str) – working directory
- icon (str) – path to ico file
Returns: Path to the shortcut
Return type: str
>>> create_desktop_shortcut(r'WAPT Console Management',target=r'c:\wapt\waptconsole.exe') u'C:\\Users\\Public\\Desktop\\WAPT Console Management.lnk' >>> create_desktop_shortcut(r'WAPT local status',target='http://localhost:8088/') u'C:\\Users\\Public\\Desktop\\WAPT local status.url'
- setuphelpers.create_onetime_task(name, cmd, parameters=None, delay_minutes=2, max_runtime=10, retry_count=3, retry_delay_minutes=1)[source]¶
creates a one time Windows scheduled task and activate it.
Create a program menu shortcut link for all users
if label’s extension is url, a http shortcut is created, else creates a file system shortcut.
Parameters: - 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
Returns: Path to the shortcut
Return type: str
>>> create_programs_menu_shortcut('Dev-TranquilIT', target='http://dev.tranquil.it') u'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Dev-TranquilIT.url' >>> create_programs_menu_shortcut('Console WAPT', target=makepath('c:/wapt','waptconsole.exe')) u'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Console WAPT.lnk'
- setuphelpers.create_shortcut(path, target='', arguments='', wDir='', icon='')[source]¶
Create a windows shortcut
Parameters: - path (str) – As what file should the shortcut be created?
- target (str) – What command should the desktop use?
- arguments (str) – What arguments should be supplied to the command?
- wdir (str) – working directory. What folder should the command start in?
- icon (str or list) – filename or (filename, index) (only for file sc) What icon should be used for the shortcut
Returns: None
>>> create_shortcut(r'c:\\tmp\\test.lnk',target='c:\\wapt\\waptconsole.exe')
- setuphelpers.create_user(user, password, full_name=None, comment=None)[source]¶
Creates a local user
- setuphelpers.create_user_desktop_shortcut(label, target='', arguments='', wDir='', icon='')[source]¶
Create a desktop shortcut link for current user
Parameters: - label (str) – Name of the shorcut (.lnk extension is appended if not provided)
- target (str) – path to application
- arguments (str) – argument to pass to application
- wDir (str) – working directory
- icon (str) – path to ico file
Returns: Path to the shortcut
Return type: str
>>> create_user_desktop_shortcut(r'WAPT Console Management',target='c:\\wapt\\waptconsole.exe') u'C:\\Users\\htouvet\\Desktop\\WAPT Console Management.lnk' >>> create_user_desktop_shortcut(r'WAPT local status',target='http://localhost:8088/') u'C:\\Users\\htouvet\\Desktop\\WAPT local status.url'
Create a shortcut in the start menu of the current user
If label extension is url, create a Http shortcut, else a file system shortcut.Parameters: - label – Name of the shorcut (.lnk or .url extension is appended if not provided.)
- target – path to application
- arguments – argument to pass to application
- wDir – working directory
- icon – path to ico file
Returns: Path to the shortcut
Return type: str
>>> create_user_programs_menu_shortcut('Dev-TranquilIT', target='http://dev.tranquil.it') u'C:\\Users\\htouvet\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Dev-TranquilIT.url' >>> create_user_programs_menu_shortcut('Console WAPT', target=makepath('c:/wapt','waptconsole.exe')) u'C:\\Users\\htouvet\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Console WAPT.lnk'
- setuphelpers.critical_system_pending_updates()[source]¶
Return list of not installed critical updates
Returns: list of title of WSUS crititcal updates not applied Return type: list
- setuphelpers.delete_at_next_reboot(target_filename)[source]¶
delete at next reboot using standard Windows PendingFileRenameOperations
- Creates a key in HKEY_LOCAL_MACHINESystemCurrentControlSetControlSession Manager with content :
- PendingFileRenameOperations
- Data type : REG_MULTI_SZ Value data: [??path,0]
Parameters: target_filename (str) – File to delete
- setuphelpers.delete_task(name)[source]¶
Removes a Windows scheduled task
Parameters: name (str) – name of the tasks as created in create_daily_task
- setuphelpers.desktop(common=0)¶
What folder is equivalent to the current desktop?
- class setuphelpers.disable_file_system_redirection[source]¶
Context manager to disable temporarily the wow3264 file redirector
>>> with disable_file_system_redirection(): ... winshell.get_path(shellcon.CSIDL_PROGRAM_FILES) u'C:\\Program Files (x86)'
- setuphelpers.dmi_info()[source]¶
Hardware System information from BIOS estracted with dmidecode
Convert dmidecode -q output to python dictReturns: dict >>> dmi = dmi_info() >>> 'UUID' in dmi['System_Information'] True >>> 'Product_Name' in dmi['System_Information'] True
- setuphelpers.enable_task(name)[source]¶
Enable (start of) a Windows scheduled task
Parameters: name (str) – name of the tasks as created in create_daily_task
- setuphelpers.ensure_dir(filename)[source]¶
Be sure the directory of filename exists on disk. Create it if not
The intermediate directories are created either.
Parameters: filename (str) – path to a future file for which to create directory. Returns: None
- setuphelpers.ensure_unicode(data)[source]¶
Return a unicode string from data object
- It is sometimes diffcult to know in advance what we will get from command line
- application output.
- This is to ensure we get a (not always accurate) representation of the data
- mainly for logging purpose.
Parameters: data – either str or unicode or object having a __unicode__ or WindowsError or Exception Returns: unicode string representing the data Return type: unicode >>> ensure_unicode(str('éé')) u'\xe9\xe9' >>> ensure_unicode(u'éé') u'\xe9\xe9' >>> ensure_unicode(Exception("test")) u'Exception: test' >>> ensure_unicode(Exception()) u'Exception: '
- setuphelpers.filecopyto(filename, target)[source]¶
Copy file from absolute or package temporary directory to target directory
If file is dll or exe, logs the original and new version.
Parameters: - filename (str) – absolute path to file to copy, or relative path to temporary package install content directory.
- target (str) – absolute path to target directory where to copy file.
- is either a full filename or a directory name (target) –
- filename is .exe or .dll, logger prints version numbers (if) –
>>> 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
- setuphelpers.find_processes(process_name)[source]¶
Return list of Process names process_name
- Args;
- process_name (str): process name to lookup
Returns: list of processes (Process) named process_name or process_name.exe Return type: list >>> [p.pid for p in find_processes('explorer')] [2756, 4024]
- setuphelpers.file_is_locked(path, timeout=5)[source]¶
Chack if a file is locked. waits timout seconds for the release
- setuphelpers.get_appath(exename)[source]¶
Get the registered application location from registry given its executable name
>>> get_appath('firefox.exe') u'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe' >>> get_appath('wapt-get.exe') u'C:\\wapt\\wapt-get.exe'
- setuphelpers.get_current_user()[source]¶
Get the login name for the current user.
>>> get_current_user() u'htouvet'
- setuphelpers.get_domain_fromregistry()[source]¶
Return main DNS domain of the computer
Returns: domain name Return type: str >>> get_domain_fromregistry() u'tranquilit.local'
- setuphelpers.get_file_properties(fname)[source]¶
Read all properties of the given file return them as a dictionary.
Parameters: fname – path to Windows executable or DLL Returns: properties of executable Return type: dict >>> xp = get_file_properties(r'c:\windows\explorer.exe') >>> 'FileVersion' in xp and 'FileDescription' in xp True
- setuphelpers.get_language()[source]¶
Get the default locale like fr, en, pl etc.. etc
>>> get_language() 'fr'
- setuphelpers.get_loggedinusers()[source]¶
Return the list of logged in users on this host
Returns: list of users logins Return type: list >>> get_loggedinusers() [u'htouvet']
- setuphelpers.get_msi_properties(msi_filename)[source]¶
Return a dict of msi installer properties
Parameters: msi_filename (str) – path to msi file Returns: properties of msi. at least there seems to be keys like ‘Manufacturer’,’ProductCode’,’ProductName’,’ProductVersion’ Return type: dict >>> zprop = get_msi_properties(r'C:\tranquilit\wapt\tests\7z920.msi') >>> 'ProductVersion' in zprop and 'ProductCode' in zprop and 'ProductName' in zprop True
- setuphelpers.getproductprops(installer_path)[source]¶
get the properties (product, version, description...) of an exe file or a msi file
Parameters: installer_path (str) – filepath to exe or msi file Returns: {‘product’,’description’,’version’,’publisher’} Return type: dict
- setuphelpers.getsilentflags(installer_path)[source]¶
Detect the type of installer and returns silent silent install flags
Parameters: installer_path (str) – filepath to installer Returns: detected command line flags to append to installer Return type: str >>> getsilentflags(r'C: ranquilit\wapt estsz920.msi') '/q /norestart'
- setuphelpers.host_info()[source]¶
Read main workstation informations, returned as a dict
Returns: main properties of host, networking and windows system Return type: dict >>> hi = host_info() >>> 'computer_fqdn' in hi and 'connected_ips' in hi and 'computer_name' in hi and 'mac' in hi True
- setuphelpers.inifile_hasoption(inifilename, section, key)[source]¶
Check if an option is present in section of the inifile
Parameters: - inifilename (str) – Path to the ini file
- section (str) – section
- key (str) – value key to check
Returns: True if the key exists
Return type: boolean
>>> inifile_writestring('c:/tranquilit/wapt/tests/test.ini','global','version','1.1.2') >>> print inifile_hasoption('c:/tranquilit/wapt/tests/test.ini','global','version') True >>> print inifile_hasoption('c:/tranquilit/wapt/tests/test.ini','global','dontexist') False
- setuphelpers.inifile_readstring(inifilename, section, key, default=None)[source]¶
Read a string parameter from inifile
>>> inifile_writestring('c:/tranquilit/wapt/tests/test.ini','global','version','1.1.2') >>> print inifile_readstring('c:/tranquilit/wapt/tests/test.ini','global','version') 1.1.2 >>> print inifile_readstring('c:/tranquilit/wapt/tests/test.ini','global','undefaut','defvalue') defvalue
- setuphelpers.inifile_writestring(inifilename, section, key, value)[source]¶
Write a string parameter to inifile
>>> inifile_writestring('c:/tranquilit/wapt/tests/test.ini','global','version','1.1.1') >>> print inifile_readstring('c:/tranquilit/wapt/tests/test.ini','global','version') 1.1.1
- setuphelpers.installed_softwares(keywords='', uninstallkey=None)[source]¶
return list of installed software from registry (both 32bit and 64bit
- Args;
- keywords (str or list): string to lookup in key, display_name or publisher fields uninstallkey : filter on a specific uninstall key instead of fuzzy search
Returns: {‘key’, ‘name’, ‘version’, ‘install_date’, ‘install_location’ ‘uninstall_string’, ‘publisher’,’system_component’} Return type: dict >>> softs = installed_softwares('libre office') >>> if softs: ... for soft in softs: ... print uninstall_cmd(soft['key']) ???
- setuphelpers.installed_windows_updates()[source]¶
return list of installed updates, indepently from WUA agent
- setuphelpers.install_exe_if_needed(exe, silentflags='', key=None, min_version=None, killbefore=[], accept_returncodes=[0, 1603, 3010], timeout=300)[source]¶
Install silently the supplied setup executable file, and add the uninstall key to global uninstallkey list if it is defined.
Check if already installed at the supllied min_version.
Kill the processes in killbefore list before launching the setup.
Raises an error if, after the setup install, the uninstall key is not found in registry.
Parameters: - exe (str) – path to the setup exe file
- silentflags (str) – flags to append to the exe command line for silent install if not provided, tries to guess them.
- key (str) – uninstall key to check in registry and to add to uninstallkey global list
- min_version (str) – if installed version is equal or gretaer than this, don’t install if not provided, guess it from exe setup file properties.
- kill_before (list of str) – processes to kill before setup, to avoid file locks issues.
Returns: None
- setuphelpers.install_msi_if_needed(msi, min_version=None, killbefore=[], accept_returncodes=[0, 1603, 3010], timeout=300, properties={})[source]¶
Install silently the supplied msi file, and add the uninstall key to global uninstall key list
uninstall key, min_version and silent flags are guessed from msi file.
Raises an error if, after the msi install, the uninstall key is not found in registry.
The matching is done on key
Parameters: - msi (str) – path to the MSI file
- min_version (str) – if installed version is equal or gretaer than this, don’t install if not provided, guess it from exe setup file properties.
- kill_before (list of str) – processes to kill before setup, to avoid file locks issues.
- accept_returncodes (list of int) – return codes which are acceptable and don’t raise exception
- int) (timeout) – maximum run time of command in seconds bfore the child is killed and error is raised.
- properties (dict) – map (key=value) of properties for specific msi installation.
Returns: None
- setuphelpers.isdir()¶
Return true if the pathname refers to an existing directory.
- setuphelpers.isfile(path)¶
Test whether a path is a regular file
- setuphelpers.isrunning(processname)[source]¶
Check if a process is running,
>>> isrunning('explorer') True
- setuphelpers.iswin64()[source]¶
Check whether operating system is 64bits
Returns: boolean >>> iswin64() True
- setuphelpers.killalltasks(exenames, include_children=True)[source]¶
Kill the task by their exename
>>> killalltasks('firefox.exe')
- setuphelpers.local_admins()[source]¶
List local users who are local administrators
>>> local_admins() [u'Administrateur', u'cyg_user', u'install', u'toto']
- setuphelpers.local_groups()[source]¶
Returns local groups
>>> local_groups() [u'Administrateurs', u'Duplicateurs', u'IIS_IUSRS', u'Invités', u'Lecteurs des journaux d\u2019événements', u'Opérateurs de chiffrement', u'Opérateurs de configuration réseau', u'Opérateurs de sauvegarde', u'Utilisateurs', u'Utilisateurs avec pouvoir', u'Utilisateurs de l\u2019Analyseur de performances', u'Utilisateurs du Bureau à distance', u'Utilisateurs du journal de performances', u'Utilisateurs du modèle COM distribué', u'IIS_WPG', u'test']
- setuphelpers.local_users()[source]¶
Returns local users
>>> local_users() [u'Administrateur', u'ASPNET', u'cyg_user', u'install', u'Invité', u'newadmin', u'sshd', u'toto', u'UpdatusUser'] >>>
- setuphelpers.local_desktops()[source]¶
Return a list of all local user’s desktops paths
Parameters: None – Returns: list of desktop path Return type: list >>> local_desktops() [u'C:\Windows\ServiceProfiles\LocalService\Desktop', u'C:\Windows\ServiceProfiles\NetworkService\Desktop', u'C:\Users\install\Desktop', u'C:\Users\UpdatusUser\Desktop', u'C:\Users\administrateur\Desktop', u'C:\Users\htouvet-adm\Desktop']
- setuphelpers.makepath(a, *p)[source]¶
Create a path given the components passed, but with saner defaults than os.path.join.
In particular, removes ending path separators (backslashes) from components
>>> makepath('c:',programfiles) 'C:\\Program Files'
- setuphelpers.mkdirs(path)[source]¶
Create directory path if it doesn’t exists yet Creates intermediate directories too.
- setuphelpers.my_documents()¶
What folder holds the My Documents files?
- setuphelpers.need_install(key, min_version=None, force=False)[source]¶
- Return True if the software with key can be found in uninstall registry
- and the registred version is equal or greater than min_version
Parameters: - key (str) – uninstall key
- min_version (str) – minimum version or None if don’t check verion
Returns: boolean
- setuphelpers.programs(common=0)¶
What folder holds the Programs shortcuts (from the Start Menu)?
- setuphelpers.reboot_machine(message='Machine Rebooting', timeout=30, force=0, reboot=1)[source]¶
Reboot the current host within specified timeout, display a message to the user
This can not be cancelled bu the user.
Parameters: - message (str) – displayed to user to warn him
- timeout (int) – timeout in seconds before proceeding
- force (int) –
- If this parameter is 1, applications with unsaved changes
- are to be forcibly closed.
- If this parameter is 0, the system displays a dialog box instructing
- the user to close the applications.
- reboot (int) – 1 to reboot after shutdown; If 0, the system halt.
- setuphelpers.recent()¶
What folder holds the Documents shortcuts (from the Start Menu)?
- setuphelpers.reg_delvalue(key, name)[source]¶
Remove the value of specified name inside ‘key’ folder key : handle of registry key as returned by reg_openkey_noredir() name : value name
- setuphelpers.reg_getvalue(key, name, default=None)[source]¶
Return the value of specified name inside ‘key’ folder
>>> with reg_openkey_noredir(HKEY_LOCAL_MACHINE,'SOFTWARE\\7-Zip') as zkey: ... path = reg_getvalue(zkey,'Path') >>> print path c:\Program Files\7-Zip\
Parameters: - 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
Returns: depends on type of value named name.
Return type: int or str or list
- setuphelpers.reg_openkey_noredir(rootkey, subkeypath, sam=131097, create_if_missing=False)[source]¶
Open the registry keysubkey with access rights sam
- The Wow6432Node redirector is disabled. So one can access 32 and 64 part or the registry
- even if python is running in 32 bits mode.
Parameters: - rootkey – HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
- subkeypath – string like “softwaremicrosoftwindowscurrentversion”
- sam – a boolean combination of KEY_READ | KEY_WRITE
- create_if_missing – True to create the subkeypath if not exists, access rights will include KEY_WRITE
Returns: a key handle for reg_getvalue and reg_set_value
Return type: keyhandle
>>>
- setuphelpers.reg_setvalue(key, name, value, type=1)[source]¶
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)
- setuphelpers.register_dll(dllpath)[source]¶
Register a COM/OLE server DLL in registry (similar to regsvr32)
- setuphelpers.register_ext(appname, fileext, shellopen, icon=None, otherverbs=[])[source]¶
Associates a file extension with an application, and command to open it
Parameters: - appname (str) – descriptive name of the type of file / appication
- fileext (str) – extension with dot prefix of
>>> 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"'), ... ]) >>>
- setuphelpers.register_uninstall(uninstallkey, uninstallstring, win64app=False, quiet_uninstall_string='', install_location=None, display_name=None, display_version=None, publisher='')[source]¶
Register the uninstall method in Windows registry, so that the application is displayed in Control Panel / Programs and features
- setuphelpers.register_windows_uninstall(package_entry)[source]¶
Add a windows registry key for custom installer
- setuphelpers.registry_delete(root, path, valuename)[source]¶
Delete the valuename inside specified registry path
the path can be either with backslash or slash
Parameters: - root – HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
- path – string like “softwaremicrosoftwindowscurrentversion” or “softwarewow6432nodemicrosoftwindowscurrentversion”
- valuename – None for value of key or str for a specific value like ‘CommonFilesDir’
- setuphelpers.registry_deletekey(root, path, keyname)[source]¶
Delete the key under specified registry path and all its values.
the path can be either with backslash or slash if the key has sub keys, the function fails.
Parameters: - root – HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
- path – string like “softwaremicrosoftwindowscurrentversion” or “softwarewow6432nodemicrosoftwindowscurrentversion”
- keyname – Name of key
- setuphelpers.registry_readstring(root, path, keyname, default='')[source]¶
Return a string from registry
Parameters: - root – HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
- path – string like “softwaremicrosoftwindowscurrentversion” or “softwarewow6432nodemicrosoftwindowscurrentversion”
- keyname – None for value of key or str for a specific value like ‘CommonFilesDir’
- path can be either with backslash or slash (the) –
>>> registry_readstring(HKEY_LOCAL_MACHINE,r'SYSTEM/CurrentControlSet/services/Tcpip/Parameters','Hostname').upper() u'HTLAPTOP'
- setuphelpers.registry_set(root, path, keyname, value, type=None)[source]¶
Set the value of a key in registry, taking in account value type The path can be either with backslash or slash
Parameters: - root – HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
- path – string like “softwaremicrosoftwindowscurrentversion” or “softwarewow6432nodemicrosoftwindowscurrentversion”
- keyname – None for value of key or str for a specific value like ‘CommonFilesDir’
- value – value (integer or string type) to put in keyname
Returns:
- setuphelpers.registry_setstring(root, path, keyname, value, type=1)[source]¶
Set the value of a string key in registry the path can be either with backslash or slash
Parameters: - root – HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER ...
- path – string like “softwaremicrosoftwindowscurrentversion” or “softwarewow6432nodemicrosoftwindowscurrentversion”
- keyname – None for value of key or str for a specific value like ‘CommonFilesDir’
- value – string to put in keyname
- setuphelpers.remove_desktop_shortcut(label)[source]¶
Remove a shortcut from the desktop of all users
Parameters: label (str) – label of shortcut with extension lnk or url
- setuphelpers.remove_file(path)[source]¶
- Try to remove a single file
- log a warning msg if file doesn’t exist log a critical msg if file can’t be removed
Parameters: path (str) – path to file >>> remove_file(r'c:\tmp\fc.txt')
- setuphelpers.remove_from_system_path(path)[source]¶
Remove a path from the global search PATH environment variable if it is set
Remove a shortcut from the start menu of all users
Parameters: label (str) – label of shortcut with extension lnk or url
- setuphelpers.remove_shutdown_script(cmd, parameters)[source]¶
Removes a local shutdown GPO script
>>> index = remove_shutdown_script(r'c:\wapt\wapt-get.exe','update')
- setuphelpers.remove_tree(*args, **kwargs)[source]¶
Convenience function to delete a directory tree, with any error ignored by default. Pass ignore_errors=False to access possible errors.
Parameters: - path (str) – path to directory to remove
- ignore_errors (boolean) – default to True to ignore exceptions on children deletion
- onerror (func) – hook called with (os.path.islink, path, sys.exc_info()) on each delete exception. Should raise if stop is required.
>>> remove_tree(r'c:\tmp\target')
- setuphelpers.remove_user_desktop_shortcut(label)[source]¶
Remove a shortcut from the desktop of current user
Parameters: label (str) – label of shortcut with extension lnk or url
- setuphelpers.remove_user_from_group(user, group)[source]¶
Remove membership from a local group for a user
Remove a shortcut from the start menu of current user
Parameters: label (str) – label of shortcut with extension lnk or url
- setuphelpers.replace_at_next_reboot(tmp_filename, target_filename)[source]¶
Schedule a file rename at next reboot using standard Windows PendingFileRenameOperations
- Creates a key in HKEY_LOCAL_MACHINESystemCurrentControlSetControlSession Manager with content :
- PendingFileRenameOperations
- Data type : REG_MULTI_SZ Value data: ??c:tempwin32k.sys !??c:winntsystem32win32k.s
Parameters: - tmp_filename (str) – Temporary path to file to rename (defaults to <target_filename>.pending)
- target_filename (str) – Final target filename
- setuphelpers.run(*cmd, **kwargs)[source]¶
Run the command cmd in a shell and return the output and error text as string
Parameters: *cmd – command and arguments, either as a string or as a list of arguments - Kwargs:
shell (boolean) : True is assumed timeout (int) : maximum time to wait for cmd completion is second (default = 600)
a TimeoutExpired exception is raised if tiemout is reached.- on_write : callback when a new line is printed on stdout or stderr by the subprocess
- func(linestr)
accept_returncodes (list) : list of return code which are considered OK default = (0,1601) pidlist (list): external list where to append the pid of the launched process.
all other parameters from the psutil.Popen constructor are accepted
Returns: merged output of stdout and stderr streams Return type: unicode - Exceptions:
- CalledProcessError: if return code of cmd is not in accept_returncodes list TimeoutExpired: if process is running for more than timeout time.
>>> run(r'dir /B c:\windows\explorer.exe') u'explorer.exe\r\n'
>>> out = [] >>> pids = [] >>> def getlines(line): ... out.append(line) >>> run(r'dir /B c:\windows\explorer.exe',pidlist=pids,on_write=getlines) u'explorer.exe\r\n'
>>> print out ['explorer.exe\r\n'] >>> try: ... run(r'ping /t 127.0.0.1',timeout=3) ... except TimeoutExpired: ... print('timeout') timeout
- setuphelpers.run_notfatal(*cmd, **args)[source]¶
Runs the command and wait for it termination, returns output Ignore exit status code of command, return ‘’ instead
- setuphelpers.sendto()¶
What folder holds the SendTo shortcuts (from the Context Menu)?
- setuphelpers.service_is_running(service_name)[source]¶
Return True if the service is running
>>> state = service_is_running('waptservice')
- setuphelpers.service_is_stopped(service_name)[source]¶
Return True if the service is running
>>> state = service_is_running('waptservice')
- setuphelpers.set_environ_variable(name, value, type=2)[source]¶
Add or update a system wide persistent environment variable
.>>> set_environ_variable(‘WAPT_HOME’,’c:\wapt’) .>>> import os .>>> os.environ[‘WAPT_HOME’] ‘c:\wapt’
Set the hidden attribute of file located at path
Utility function for shutdown gpo script
Parameters: path (str) – path to the file
- setuphelpers.set_file_visible(path)[source]¶
Unset the hidden attribute of file located at path
Utility function for shutdown gpo script
Parameters: path (str) – path to the file
- setuphelpers.shell_launch(cmd)[source]¶
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’)
- setuphelpers.shutdown_scripts_ui_visible(state=True)[source]¶
Enable or disable the GUI for windows shutdown scripts
>>> shutdown_scripts_ui_visible(None) >>> shutdown_scripts_ui_visible(False) >>> shutdown_scripts_ui_visible(True)
What folder holds the Start Menu shortcuts?
- setuphelpers.startup(common=0)¶
What folder holds the Startup shortcuts (from the Start Menu)?
- setuphelpers.system32()[source]¶
returns the path of system32directory
Returns: path to system32 directory Return type: str >>> print system32() C:\Windows\system32
- setuphelpers.uninstall_cmd(guid)[source]¶
return the (quiet) command stored in registry to uninstall a software given its registry key
>>> old_softs = installed_softwares('notepad++') >>> for soft in old_softs: ... print uninstall_cmd(soft['key']) [u'C:\\Program Files (x86)\\Notepad++\\uninstall.exe', '/S']
- setuphelpers.unregister_uninstall(uninstallkey, win64app=False)[source]¶
Remove uninstall method from registry
- setuphelpers.uninstall_key_exists(uninstallkey)[source]¶
Check if the uninstalley is present in win32 / win54 registry
- setuphelpers.unset_environ_variable(name)[source]¶
Remove a system wide persistent environment variable if it exist. Fails silently if it doesn’t exist
- setuphelpers.user_appdata()[source]¶
Return the roaming appdata profile of current user
Returns: path like u’C:\Users\username\AppData\Roaming’ Return type: str
- setuphelpers.user_desktop()[source]¶
return path to current logged in user desktop
>>> user_desktop() u'C:\\Users\\htouvet\\Desktop'
- setuphelpers.wget(url, target, printhook=None, proxies=None, connect_timeout=10, download_timeout=None, verify_cert=False, referer=None, user_agent=None)[source]¶
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’) ???
- setuphelpers.wgets(url, proxies=None, verify_cert=False, referer=None, user_agent=None)[source]¶
Return the content of a remote resource as a String with a http get request.
Raise an exception if remote data can’t be retrieved.
Parameters: - url (str) – http(s) url
- proxies (dict) – proxy configuration as requests requires it {‘http’: url, ‘https’:url}
Returns: content of remote resource
Return type: str
>>> data = wgets('https://wapt/ping') >>> "msg" in data True
- setuphelpers.wincomputername()¶
- setuphelpers.windomainname()¶
- setuphelpers.wmi_info(keys=['Win32_ComputerSystem', 'Win32_ComputerSystemProduct', 'Win32_BIOS', 'Win32_NetworkAdapter', 'Win32_Printer', 'Win32_VideoController', 'Win32_LogicalDisk'], exclude_subkeys=['OEMLogoBitmap'])[source]¶
Get WMI machine informations as dictionaries
- setuphelpers.wmi_info_basic()[source]¶
Return uuid, serial, model, vendor from WMI
Returns: minimal informations for wapt registration Return type: dict >>> r = wmi_info_basic() >>> 'System_Information' in r True
- setuphelpers.windows_version()[source]¶
see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx
- setuphelpers.httpdatetime2isodate(httpdate)[source]¶
convert a date string as returned in http headers or mail headers to isodate >>> import requests >>> last_modified = requests.head(‘http://wapt/wapt/Packages‘,headers={‘cache-control’:’no-cache’,’pragma’:’no-cache’}).headers[‘last-modified’] >>> len(httpdatetime2isodate(last_modified)) == 19 True
- setuphelpers.ensure_list(csv_or_list, ignore_empty_args=True, allow_none=False)[source]¶
if argument is not a list, return a list from a csv string
- class setuphelpers.WindowsVersions[source]¶
- Windows10 = Version('10.0')¶
- Windows2000 = Version('5.0')¶
- Windows7 = Version('6.1')¶
- Windows8 = Version('6.2')¶
- Windows81 = Version('6.3')¶
- WindowsEmbeddedStandard2009 = Version('5.1')¶
- WindowsServer2003 = Version('5.2')¶
- WindowsServer2003R2 = Version('5.2')¶
- WindowsServer2008 = Version('6.0')¶
- WindowsServer2008R2 = Version('6.1')¶
- WindowsServer2012 = Version('6.2')¶
- WindowsServer2012R2 = Version('6.3')¶
- WindowsServer2016TechnicalPreview = Version('10.0')¶
- WindowsVista = Version('6.0')¶
- WindowsXP = Version('5.1')¶
- WindowsXP64 = Version('5.2')¶