WAPT Setuphelpers Usage

class setuphelpers.EnsureWUAUServRunning[source]

Bases: object

Contextual object to ensure that wauserv service is running (in manual mode) Restores previous state at context exit.

class setuphelpers.InstallerTypes[source]

Bases: object

APPX = 'WExtract'
ExeWinUpdates = 'ExeWindowsUpdate'
GenericInstaller = 'GenericInstaller'
InnoSetup = 'InnoSetup'
InstallShield = 'InstallShield'
MSI = 'MSI'
MSU = 'MSU'
MozillaInstaller = 'MozillaInstaller'
NSIS = 'NSIS'
SFXCab = 'SFXCab'
SevenZIPSFX = 'SevenZIPSFX'
UnknownExeInstaller = 'UnknownExeInstaller'
UnknownInstaller = 'UnknownInstaller'
WExtract = 'WExtract'
class setuphelpers.RunOutput(value)[source]

Bases: str

Subclass of str (bytes) to return returncode from runned command in addition to output

>>> run(r'cmd /C dir c:     oto ',accept_returncodes=[0,1])
No handlers could be found for logger "root"
<RunOuput returncode :[0, 1]>
 Le volume dans le lecteur C n'a pas de nom.
 Le numéro de série du volume est 74EF-5918
Fichier introuvable

Répertoire de c:

Changed in version 1.4.0: subclass str(bytes string) and not unicode

class setuphelpers.RunReader(callable, *args, **kwargs)[source]

Bases: Thread

run()[source]
exception setuphelpers.TimeoutExpired(cmd, output=None, timeout=None)[source]

Bases: Exception

This exception is raised when the timeout expires while waiting for a child process.

>>> try:
...     run('ping -t 10.10.1.67',timeout=5)
... except TimeoutExpired as e:
...     print e.output
...     raise
...
class setuphelpers.WindowsVersions[source]

Bases: object

Helper class to get numbered windows version from windows name version

Sources: https://msdn.microsoft.com/en-us/library/windows/desktop/dn481241(v=vs.85).aspx https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions

… versionadded:: 1.3.5

Changed in version 1.9: Adding Windows 10.0 and newer versions

Changed in version 2.0: Adding Windows 10 version 20H1 and newer versions

Changed in version 2.2: Adding Windows 11/2022 versions

Windows10 = Version('10.0')
Windows10v1507 = Version('10.0.10240')
Windows10v1511 = Version('10.0.10586')
Windows10v1607 = Version('10.0.14393')
Windows10v1703 = Version('10.0.15063')
Windows10v1709 = Version('10.0.16299')
Windows10v1803 = Version('10.0.17134')
Windows10v1809 = Version('10.0.17763')
Windows10v1903 = Version('10.0.18362')
Windows10v1909 = Version('10.0.18363')
Windows10v2004 = Version('10.0.19041')
Windows10v2009 = Version('10.0.19042')
Windows10v20H1 = Version('10.0.19041')
Windows10v20H2 = Version('10.0.19042')
Windows10v21H1 = Version('10.0.19043')
Windows10v21H2 = Version('10.0.19044')
Windows11 = Version('10.0.22000')
Windows2000 = Version('5.0')
Windows7 = Version('6.1')
Windows8 = Version('6.2')
Windows81 = Version('6.3')
WindowsServer2003 = Version('5.2')
WindowsServer2003R2 = Version('5.2')
WindowsServer2008 = Version('6.0')
WindowsServer2008R2 = Version('6.1')
WindowsServer2012 = Version('6.2')
WindowsServer2012R2 = Version('6.3')
WindowsServer2016 = Version('10.0.14393')
WindowsServer2019 = Version('10.0.17763')
WindowsServer2022 = Version('10.0.20348')
WindowsVista = Version('6.0')
WindowsXP = Version('5.1')
WindowsXP64 = Version('5.2')
setuphelpers.add_double_quotes_around(string)[source]

Return the string with double quotes around

Args:

string (str): a string

setuphelpers.add_shutdown_script(cmd, parameters)[source]

Adds a local shutdown script as a local GPO

Args:

cmd (str): absolute path to exe or bat file (without parameters) parameters (str): parameters to append to command

Returns:

int: index of command into the list of shutdown scripts

>>> 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.add_user_to_group(user, group)[source]

Add membership to a local group for a user

setuphelpers.adjust_current_privileges(priv, enable=1)[source]
setuphelpers.all_files(rootdir, pattern=None)[source]

Recursively return all files from rootdir and sub directories matching the (dos style) pattern (example: *.exe)

setuphelpers.application_data(common=0)[source]

What folder holds application configuration files?

setuphelpers.battery_lifetime()[source]

Return battery life in seconds

New in version 1.4.2.

setuphelpers.battery_percent()[source]

Return battery level in percent

New in version 1.4.2.

setuphelpers.bookmarks(common=0)

What folder holds the Explorer favourites shortcuts?

setuphelpers.bs_find(url, element, attribute=None, value=None, user_agent=None, proxies=None, features='html.parser', **kwargs)[source]

Parse html web page with BeautifulSoup and get the first result

Args:

url (str): url of the web page to parse element (str): searched element attribute (str): selected attribute of the element value (str): value of the selected attribute user_agent (str): specify a user-agent if needed proxies (dict): specify your proxy if needed **kwargs (str): joker for requests parameters features (str): bs feature to use

>>> bs_find('https://www.w3.org/', 'a', 'title', 'Open Web Platform testing')['href']
'https://web-platform-tests.org/'
>>> bs_find('https://www.w3.org/', 'span', 'class', 'alt-logo').string
'W3C'

New in version 2.0.

setuphelpers.bs_find_all(url, element, attribute=None, value=None, user_agent=None, proxies=None, features='html.parser', **kwargs)[source]

Parse html web page with BeautifulSoup and get a list of the result

Args:

url (str): url of the web page to parse element (str): searched element attribute (str): selected attribute of the element value (str): value of the selected attribute user_agent (str): specify a user-agent if needed proxies (dict): specify your proxy if needed **kwargs (str): joker for requests parameters features (str): bs feature to use

>>> bs_find_all('https://www.w3.org/', 'a', 'title', 'Open Web Platform testing')[0]['href']
'https://web-platform-tests.org/'
>>> bs_find_all('https://www.w3.org/', 'span', 'class', 'alt-logo')[0].string
'W3C'

New in version 2.0.

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>, oncopy=<function default_oncopy>, 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.

Args:

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 exists. can be default_overwrite or default_overwrite_older or custom function.

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:

Raises:

>>> 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.

Args:

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:

PyITask: scheduled task

setuphelpers.create_desktop_shortcut(label, target='', arguments='', wDir='', icon='')[source]

Create a desktop shortcut link for all users

Args:

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:

str: Path to the shortcut

>>> 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_group(group)[source]

Creates a local group

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.

setuphelpers.create_programs_menu_shortcut(label, target='', arguments='', wDir='', icon='', folder=None)[source]

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.

Args:

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 folder (str) : folder of Programs Menu where to put the shortcut.

Returns:

str: Path to the shortcut

>>> create_programs_menu_shortcut('Dev-TranquilIT', target='http://dev.tranquil.it')
u'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Dev-TranquilIT.url'
>>> create_programs_menu_shortcut('Console WAPT', target=makepath('c:/wapt','waptconsole.exe'))
u'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Console WAPT.lnk'
setuphelpers.create_shortcut(path, target='', arguments='', wDir='', icon='')[source]

Create a windows shortcut

Args:

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

Args:

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:

str: Path to the shortcut

>>> 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'
setuphelpers.create_user_programs_menu_shortcut(label, target='', arguments='', wDir='', icon='', folder=None)[source]

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.

Args:

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 folder (str) : folder of User’s Programs Menu where to put the shortcut.

Returns:

str: Path to the shortcut

>>> create_user_programs_menu_shortcut('Doc-TranquilIT', target='https://doc.wapt.fr')
u'C:\\Users\\htouvet\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Doc-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\\Programs\\Console WAPT.lnk'
setuphelpers.critical_system_pending_updates(severities=['Critical'])[source]

Return list of not installed critical updates

Returns:

list: list of title of WSUS crititcal updates not applied

setuphelpers.currentdate()[source]

date as string YYYYMMDD

>>> currentdate()
'20161102'
setuphelpers.currentdatetime()[source]

date/time as YYYYMMDD-hhmmss

>>> currentdatetime()
'20161102-193600'
setuphelpers.dateof(adatetime)[source]
setuphelpers.datetime2isodate(adatetime=None)[source]
setuphelpers.default_gateway()[source]

Returns default ipv4 current gateway

setuphelpers.default_oncopy(msg, src, dst)[source]
setuphelpers.default_overwrite(src, dst)[source]
setuphelpers.default_overwrite_older(src, dst)[source]
setuphelpers.default_skip(src, dst)[source]
setuphelpers.default_user_appdata()[source]

Return the roaming appdata profile of default user

Returns:

str: path like u’C:\Users\Default\AppData\Roaming’

setuphelpers.default_user_local_appdata()[source]

Return the local appdata profile of current user

Returns:

str: path like u’C:\Users\Default\AppData\Local’

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]

Args:

target_filename (str): File to delete

setuphelpers.delete_group(group)[source]

Delete a local user group

setuphelpers.delete_task(name)[source]

Removes a Windows scheduled task

Args:

name (str) : name of the tasks as created in create_daily_task

setuphelpers.delete_user(user)[source]

Delete a local user

setuphelpers.desktop(common=0)[source]

What folder is equivalent to the current desktop?

setuphelpers.dir_is_empty(path)[source]

Check if a directory is empty

class setuphelpers.disable_file_system_redirection[source]

Bases: object

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.disable_task(name)[source]

Disable a Windows scheduled task

setuphelpers.dmi_info()[source]

Hardware System information from BIOS estracted with dmidecode Convert dmidecode -q output to python dict

Returns:

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

Args:

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.

Args:

filename (str): path to a future file for which to create directory.

Returns:

None

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

Args:

csv_or_list (list or str): ignore_empty_args (bool): if True, empty string found in csv are not appended to the list. allow_none (bool): if True, if csv_or_list is None, return None, else return empty list/

Returns:

list

setuphelpers.ensure_unicode(data)[source]

Return a unicode string from data object It is sometimes difficult 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.

Args:

data: either str or unicode or object having a __str__ or WindowsError or Exception

Returns:

unicode: unicode string representing the data

>>> ensure_unicode(str('éé'))
u'éé'
>>> ensure_unicode(u'éé')
u'éé'
>>> ensure_unicode(Exception("test"))
u'Exception: test'
>>> ensure_unicode(Exception())
u'Exception: '
setuphelpers.error(reason)[source]

Raise a WAPT fatal error

setuphelpers.file_is_locked(path, timeout=5)[source]

Check if a file is locked. waits timout seconds for the release

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.

Args:
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.

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
setuphelpers.fileisodate(filename)[source]

Returns last update date time from filename in local time

setuphelpers.find_all_files(rootdir, include_patterns=None, exclude_patterns=None, include_dirs=None, exclude_dirs=None, excludes_full=None)[source]

Generator which recursively find all files from rootdir and sub directories matching the (dos style) patterns (example: *.exe)

Args;

rootdir (str): root dir where to start looking for files include_patterns (str or list) : list of glob pattern of files to return exclude_patterns (str or list) : list of glob pattern of files to exclude

(if a file is both in include and exclude, it is excluded)

include_dirs (str or list) : list of glob directory patterns to return exclude_dirs (str or list) : list of glob directory patterns to exclude

(if a dir is both in include and exclude, it is excluded)

excludes_full (list) : list of exact (relative to package root) filepathes to exclude from manifest.

>>> for fn in find_all_files('c:\tmp','*.txt'):
        print(fn)
>>>
setuphelpers.find_processes(process_name)[source]

Return list of Process names process_name

Args:

process_name (str): process name to lookup

Returns:

list: list of processes (Process) named process_name or process_name.exe

>>> [p.pid for p in find_processes('explorer')]
[2756, 4024]
setuphelpers.fix_wmi()[source]

reregister all the WMI related DLLs in the wbem folder

setuphelpers.get_all_scheduled_tasks(enable_only=False)[source]
setuphelpers.get_antivirus_info()[source]
setuphelpers.get_app_install_location(uninstallkey)[source]

Get the registered application install location from registry given its uninstallkey

>>> get_app_install_location('wapt_is1')
u'C:\\wapt\\'
setuphelpers.get_app_path(exename)[source]

Get the registered application location from registry given its executable name

>>> get_app_path('firefox.exe')
u'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe'
>>> get_app_path('wapt-get.exe')
u'C:\\wapt\\wapt-get.exe'
setuphelpers.get_appath(exename)

Get the registered application location from registry given its executable name

>>> get_app_path('firefox.exe')
u'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe'
>>> get_app_path('wapt-get.exe')
u'C:\\wapt\\wapt-get.exe'
setuphelpers.get_computer_description()[source]

Get the computer descrption

setuphelpers.get_computer_domain()[source]

Get computer AD domain

setuphelpers.get_computer_groups()[source]

Try to finc the computer in the Active Directory and return the list of groups

setuphelpers.get_computername()[source]

Return host name (without domain part)

setuphelpers.get_current_user()[source]

Get the login name for the current user.

>>> get_current_user()
u'htouvet'
setuphelpers.get_default_app(suffix)[source]

Return application path associated to a file extension (example: .pptx)

>>> get_default_app('.pptx')
'C:\\Program Files\\LibreOffice\\program\\simpress.exe'
setuphelpers.get_default_gateways()[source]
setuphelpers.get_disk_free_space(filepath)[source]

Returns the number of free bytes on the drive that filepath is on

setuphelpers.get_dns_servers()[source]
setuphelpers.get_domain_fromregistry()[source]

Return main DNS domain of the computer

Returns:

str: domain name

>>> get_domain_fromregistry()
u'tranquilit.local'
setuphelpers.get_file_assocation(ext)[source]

Return the associated application for a file extension (example : ‘.doc’)

>>> get_file_assocation('.pptx')
'LibreOffice.Pptx'
setuphelpers.get_file_properties(fname, ignore_warning=True)[source]

Read all properties of the given file return them as a dictionary.

Source: http://stackoverflow.com/questions/580924/python-windows-file-version-attribute

Args:

fname : path to Windows executable or DLL

Returns:

dict: properties of executable

>>> xp = get_file_properties(r'c:\windows\explorer.exe')
>>> 'FileVersion' in xp and 'FileDescription' in xp
True
setuphelpers.get_fqdn()[source]
setuphelpers.get_hostname()[source]

Return host fully qualified domain name in lower case

If a main domain is set in registry, use this domain (faster) If not, use value returned from main connection (ie DHCP)

Result is cached because Windows 10 is sometimes slow to return when there are multiple network interfaces.

setuphelpers.get_installer_defaults_win(installer_path)[source]

Returns guessed default values for package templates based on installer binary

Args:

installer_path (str): filepath to installer

Returns:

dict:

>>> get_installer_defaults(r'c:     ranquilit\wapt  ests\SumatraPDF-3.1.1-install.exe')
{'description': u'SumatraPDF Installer (Krzysztof Kowalczyk)',
 'filename': 'SumatraPDF-3.1.1-install.exe',
 'silentflags': '/VERYSILENT',
 'simplename': u'sumatrapdf-installer',
 'type': 'UnknownExeInstaller',
 'version': u'3.1.1'}
>>> get_installer_defaults(r'c:     ranquilit\wapt  estsz920.msi')
{'description': u'7-Zip 9.20 (Igor Pavlov)',
 'filename': '7z920.msi',
 'silentflags': '/q /norestart',
 'simplename': u'7-zip-9.20',
 'type': 'MSI',
 'version': u'9.20.00.0'}
setuphelpers.get_language(full_locale=False, separator='_')[source]

Get the os default locale (example: fr, en, pl, etc.)

>>> get_language()
'fr'
>>> get_language(full_locale=True)
'fr_FR'
>>> get_language(full_locale=True, separator='-').lower()
'fr-fr'
setuphelpers.get_language_code()[source]

Return the current Windows language code

Returns:

integer

>>> get_language_code()
1036
setuphelpers.get_last_logged_on_user()[source]
setuphelpers.get_local_IPs()[source]
setuphelpers.get_local_profiles(domain_sid=None)[source]

Return list of locally created profiles usernames

setuphelpers.get_loggedinusers()[source]

Return the list of logged in users on this host

Returns:

list: list of users logins

>>> get_loggedinusers()
[u'htouvet']
setuphelpers.get_main_ip(host=None, hostv6=None)[source]
setuphelpers.get_msi_properties(msi_filename, list_properties=['FileDescription', 'ProductCode', 'version', 'product', 'publisher', 'description', 'ProductVersion', 'UpgradeCode', 'Manufacturer', 'CompanyName', 'FileVersion', 'product', 'ProductName'])[source]

Return a dict of msi installer properties

Source: http://stackoverflow.com/questions/3157955/get-msi-product-name-version-from-command-line

Args:

msi_filename (str): path to msi file

Returns:
dict: properties of msi. at least there seems to be keys like

‘Manufacturer’,’ProductCode’,’ProductName’,’ProductVersion’

>>> zprop = get_msi_properties(r'C:\tranquilit\wapt\tests\7z920.msi')
>>> 'ProductVersion' in zprop and 'ProductCode' in zprop and 'ProductName' in zprop
True
setuphelpers.get_os_name()[source]

Get the name of the current running operating system

Returns:

str: Windows, Linux, Darwin

>>> get_os_name()
'Windows'
setuphelpers.get_os_version()[source]
setuphelpers.get_powershell_str(powershell_cmd, value=None)[source]

Get a value as string from the output of a powershell command WARNING: Adding -AllUsers parameter may be necessary to make sure WAPT is enable to get the request value

Args:

powershell_cmd (str): Powershell command value (str) : Value to get as string

New in version 2.2.

setuphelpers.get_product_props(installer_path)[source]

get the properties (product, version, description…) of an exe file or a msi file

Args:

installer_path (str): filepath to exe or msi file

Returns:

dict: {‘product’,’description’,’version’,’publisher’}

setuphelpers.get_profile_path(sid)[source]

Return the filesystem path to profile of user with SID sid

setuphelpers.get_profiles_users(domain_sid=None)[source]

Return list of locally created profiles usernames

setuphelpers.get_proxies()[source]

Return system proxy with the urllib python library

>>> get_proxies()
{'http': 'http://srvproxy.ad.domain.lan:8080',
'https': 'http://srvproxy.ad.domain.lan:8080'}
setuphelpers.get_proxies_from_wapt_console()[source]

Return proxy information from the current user WAPT console

>>> get_proxies_from_wapt_console()
{'http': 'http://srvproxy.ad.domain.lan:8080',
'https': 'http://srvproxy.ad.domain.lan:8080'}
setuphelpers.get_service_start_mode(service_name)[source]

Getting actual start mode of a service Returned values: ‘Auto’, ‘Manual’, ‘Disabled’

setuphelpers.get_sha256(afile='', BLOCK_SIZE=1048576)[source]
setuphelpers.get_shortcut_properties(shortcut_filename)[source]

Return a dict of shortcut properties

Args:

shortcut_filename (str): path to shortcut

Returns:
dict: properties of shortcut

‘description’,’hotkey’,’icon_location’,’lnk_filepath’,’show_cmd’,’show_cmd’,’show_states’,’working_directory’

>>> lnk = get_shortcut_properties(shortcut_filename)
>>> 'path' in lnk and 'description' in lnk
True
setuphelpers.get_task(name)[source]

Return an instance of PyITask given its name (without .job)

setuphelpers.get_user_from_sid(sid, controller=None)[source]

Returns domainuser for the given sid sid is either a string or a PySID

setuphelpers.get_version_from_binary(filename, property_name='ProductVersion')[source]

Get installer version from file informations, for now, only exe and msi files are compatibles

Args:

filename (str): path to the file property_name (str): selected property

Returns:

str: version number

setuphelpers.getscreens()[source]
setuphelpers.getsilentflags(installer_path)[source]

Detect the type of installer and returns silent silent install flags

Args:

installer_path (str): filepath to installer

Returns:

str: detected command line flags to append to installer

>>> getsilentflags(r'C:     ranquilit\wapt  estsz920.msi')
'/q /norestart'
setuphelpers.host_info()[source]

Read main workstation informations, returned as a dict

Returns:

dict: main properties of host, networking and windows system

Changed in version 1.4.1: returned keys changed : dns_domain -> dnsdomain

>>> hi = host_info()
>>> 'computer_fqdn' in hi and 'connected_ips' in hi and 'computer_name' in hi and 'mac' in hi
True
setuphelpers.host_metrics()[source]

Frequently updated host data

setuphelpers.hours_minutes(hours)[source]
setuphelpers.httpdatetime2isodate(httpdate)[source]

Convert a date string as returned in http headers or mail headers to isodate (UTC)

>>> 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.inifile_deleteoption(inifilename, section, key)[source]

Remove a key within the section of the inifile

Args:

inifilename (str): Path to the ini file section (str): section key (str): value key of option to remove

Returns:

boolean : True if the key/option has been removed

>>> 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_deleteoption('c:/tranquilit/wapt/tests/test.ini','global','version')
False
setuphelpers.inifile_deletesection(inifilename, section)[source]

Remove a section within the inifile

Args:

inifilename (str): Path to the ini file section (str): section to remove

Returns:

boolean : True if the section has been removed

setuphelpers.inifile_hasoption(inifilename, section, key)[source]

Check if an option is present in section of the inifile

Args:

inifilename (str): Path to the ini file section (str): section key (str): value key to check

Returns:

boolean : True if the key exists

>>> 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_hassection(inifilename, section)[source]

Check if an option is present in section of the inifile

Args:

inifilename (str): Path to the ini file section (str): section

Returns:

boolean : True if the key exists

>>> inifile_writestring('c:/tranquilit/wapt/tests/test.ini','global','version','1.1.2')
>>> print inifile_hassection('c:/tranquilit/wapt/tests/test.ini','global')
True
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.install_exe_if_needed(exe, silentflags=None, key=None, min_version=None, killbefore=[], accept_returncodes=[0, 3010], timeout=300, get_version=None, remove_old_version=False, force=False, uninstallkeylist=None, pidlist=None, keywords=None, name=None, time_wait_uninstallkey_present=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.

Args:

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 (None), guess it from exe setup file properties. if == ‘’: ignore version check.

kill_before (list of str)processes to kill before setup, to avoid file locks

issues.

get_version (callable)optional func to get installed software version from one entry retunred by installed_softwares

if not provided, version is taken from ‘version’ attribute in uninstall registry

remove_old_version (bool) : If True, uninstall the old version matching the provided key explicitely before installing the new one.

Returns:

None

New in version 1.3.2.

Changed in version 1.3.10: added get_version callback for non conventional setup.exe

Changed in version 1.4.1: error code 1603 is no longer accepted by default.

Changed in version 1.5: added remove_old_version to explicitly remove old version

setuphelpers.install_location(uninstallkey)[source]

Return the install location of the software given its uninstall key or None if not found

>>> install_location('winscp3_is1')
u'C:\Program Files\WinSCP\'
setuphelpers.install_msi_if_needed(msi, min_version=None, killbefore=None, accept_returncodes=[0, 3010], timeout=300, properties=None, get_version=None, remove_old_version=False, force=False, uninstallkeylist=None, pidlist=None, key=None, keywords=None, name=None, time_wait_uninstallkey_present=300)[source]

Install silently the supplied msi file, and add the uninstall key to uninstallkeylist 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

Args:

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 (None), guess it from exe setup file properties. if == ‘’: ignore version check.

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 timeout int) : 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. remove_old_version (bool) : If True, uninstall the old version explicitely before installing the new one.

These 3 args are set automatically when run from install() :

force (bool) : Value is set automatically when run from install(). install even if already at the right version uninstallkeylist (list) : if the installation is run, add the msi unsinstall key to this list pidlist (list) : if a process is created, add the pid to this list. (useful for external watchdogs in case of abort)

Returns:

None

New in version 1.3.2.

Changed in version 1.3.10: added get_version callback for non conventional setup.exe

Changed in version 1.4.1: error code 1603 is no longer accepted by default.

Changed in version 1.5: added remove_old_version to explicitly remove old version

setuphelpers.installed_softwares(keywords=None, uninstallkey=None, name=None, ignore_empty_names=True)[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

Changed in version 1.3.11: name (str regexp) : filter on a regular expression on software name

Returns:
list of dicts: [{‘key’, ‘name’, ‘version’, ‘install_date’, ‘install_location’

‘uninstall_string’, ‘publisher’,’system_component’}]

>>> softs = installed_softwares('libre office')
>>> if softs:
...     for soft in softs:
...         print uninstall_cmd(soft['key'])
???
setuphelpers.installed_windows_updates(**queryfilter)[source]
Return list of installed updates, indepently from WUA agent
Example :

[… {u’CSName’: u’WSDCARDON’,

u’Caption’: u’http://support.microsoft.com/?kbid=3207752’, u’Description’: u’Security Update’, u’FixComments’: u’’, u’HotFixID’: u’KB3207752’, u’InstallDate’: None, u’InstalledBy’: u’TRANQUILITdcardon-adm’, u’InstalledOn’: u’12/28/2016’, u’Name’: None, u’ServicePackInEffect’: u’’, u’Status’: None}

…]

Args:

queryfilter (dict)

Returns:

list

New in version 1.3.3.

setuphelpers.is32()[source]
setuphelpers.is64()[source]
setuphelpers.isARM()[source]
setuphelpers.isARM64()[source]
setuphelpers.is_kb_installed(hotfixid)[source]

Check whether the Windows KB is installed

Returns:

boolean

>>> is_kb_installed('3216755')
True
>>> is_kb_installed('KB3216755')
True
setuphelpers.is_pending_reboot()[source]

Check whether operating system is on pending reboot

Returns:

boolean

>>> is_pending_reboot()
True
setuphelpers.isdir(s)
setuphelpers.isfile(path)
setuphelpers.isodate2datetime(isodatestr)[source]
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.json_load_file(json_file)[source]

Get content of a json file

Args:

path (str): path to the file

Returns:

dictionary (dict)

setuphelpers.json_write_file(json_file, data, indent=4, sort_keys=False, encoding='utf-8')[source]

Write dictionary to a json file

Args:

json_file (str): path to json file data (dict): dictionary content indent (str or list of str): tabulation size ; default: 4 spaces sort_keys (bool): alphabetical order or not encoding (bool): file encoding

setuphelpers.killalltasks(exenames, include_children=True)[source]

Kill the task by their exename

>>> killalltasks('firefox.exe')
setuphelpers.killtree(pid, including_parent=True)[source]
setuphelpers.list_local_printers()[source]

Return a list of local printers .. versionadded:: 1.7.1

setuphelpers.listening_sockets(low_ports=False, include_loc=True, kind='all')[source]
setuphelpers.local_admins()[source]

List local users who are local administrators

>>> local_admins()
[u'Administrateur', u'cyg_user', u'install', u'toto']    
setuphelpers.local_desktops()[source]

Return a list of all local user’s desktops paths

Args:

None

Returns:

list : list of desktop path

>>> 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']

New in version 1.2.3.

setuphelpers.local_drives()[source]
setuphelpers.local_group_members(groupname)[source]
setuphelpers.local_group_memberships(username)[source]

List the local groups a user is member Of

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_users_profiles()[source]

Return a list of all local user’s profile paths

Returns:

list : list of desktop path

>>> local_desktops()
[u'C:\Windows\ServiceProfiles\LocalService',
 u'C:\Windows\ServiceProfiles\NetworkService',
 u'C:\Users\install',
 u'C:\Users\UpdatusUser',
 u'C:\Users\administrateur',
 u'C:\Users\htouvet-adm']

New in version 1.3.9.

setuphelpers.makepath(*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. Path functions will be called automatically

>>> makepath("c:", "Windows", "system32")
'c:\\Windows\\system32'
>>> makepath(system32())
'C:\\WINDOWS\\system32'
>>> system32()
'C:\\WINDOWS\\system32'
>>> system32
<function system32 at 0x063EBE79>
>>> makepath(system32)
'C:\\WINDOWS\\system32'
setuphelpers.memory_status()[source]

Return system memory statistics

setuphelpers.messagebox(title, msg, style=64)[source]

Open a message box to interact with the end user

Args:

title (str): Title of the message box msg (str): Text contained in the message box style (win32con): Format of the message box, usable values:

MB_OK MB_OKCANCEL MB_ABORTRETRYIGNORE MB_YESNOCANCEL MB_YESNO MB_RETRYCANCEL

MB_ICONHAND MB_ICONQUESTION MB_ICONEXCLAMATION MB_ICONASTERISK MB_ICONWARNING = MB_ICONEXCLAMATION MB_ICONERROR = MB_ICONHAND MB_ICONSTOP = MB_ICONHAND MB_ICONINFORMATION = MB_ICONASTERISK

MB_DEFBUTTON1 MB_DEFBUTTON2 MB_DEFBUTTON3 MB_DEFBUTTON4

Returns:

ID_OK = 0 ID_CANCEL = 2 ID_ABORT = 3 ID_YES = 6 ID_NO = 7

setuphelpers.mkdirs(path)[source]

Create directory path if it doesn’t exists yet Creates intermediate directories too.

>>> mkdirs("C:\Program Files (x86)\wapt")
u'C:\Program Files (x86)\wapt'
setuphelpers.my_documents()

What folder holds the My Documents files?

setuphelpers.need_install(key=None, min_version=None, force=False, get_version=None, keywords=None, name=None, higher_version_warning=True)[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

Args:

key (str): uninstall key min_version (str): minimum version or None if don’t check version (like when key is specific for each soft version) get_version (callable): optional func to get installed software version from one installed_softwares item

if not provided, version is taken from ‘version’ attribute in uninstall registry

keywords (str or list): string to lookup in key, display_name or publisher fields name (str regexp) : filter on a regular expression on software name

Returns:

boolean

Changed in version 2.1: added keywords and name

setuphelpers.networking()[source]

return a list of (iface,mac,{addr,broadcast,netmask})

setuphelpers.pending_reboot_reasons()[source]

Return the list of reasons requiring a pending reboot the computer If list is empty, no reboot is needed.

Returns:

list : list of Windows Update, CBS Updates or File Renames

setuphelpers.processes_for_file(filepath, open_files=True, dll=True)[source]

Generator returning processes currently having a open file descriptor for filepath

If not running as System account, can not access system processes.

Args:

filepath (str): file path or pattern (glob *)

Returns:

iterator psutil.Process

setuphelpers.programs(common=0)[source]

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.

Args:

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()[source]

What folder holds the Documents shortcuts (from the Start Menu)?

setuphelpers.reg_closekey(hkey)[source]

Close a registry key opened with reg_openkey_noredir

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_enum_subkeys(rootkey)[source]
setuphelpers.reg_enum_values(rootkey)[source]
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\
Args:

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:

int or str or list: depends on type of value named name.

setuphelpers.reg_key_exists(rootkey, subkeypath)[source]

Check if a key exists in registry

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.

Args:

rootkey : HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER … subkeypath : string like “softwaremicrosoftwindowscurrentversion”

Returns:

boolean

>>> if reg_key_exists(HKEY_LOCAL_MACHINE,makepath('SOFTWARE','VideoLAN','VLC')):
...     print('VLC key exists')
???
setuphelpers.reg_openkey_noredir(rootkey, subkeypath, sam=131097, create_if_missing=False, noredir=True)[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.

Args:

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 noredir (boolean): True by default. disable the redirection to the 32 bits view of registry.

Returns:

keyhandle : a key handle for reg_getvalue and reg_set_value

>>>
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.reg_value_exists(rootkey, subkeypath, value_name)[source]

Check if there is value named value_name in the subkeypath registry key of rootkey

Args:

rootkey (int): branch of registry HKEY_LOCAL_MACHINE,HKEY_USERS,HKEY_CURRENT_USER,HKEY_CURRENT_CONFIG subkeypath (str): path with back slashes like ‘SOFTWAREVideoLANVLC’ value_name (str) : value key like “Version”

Returns:

boolean: True if there is a value called value_name in the subkeypath of rootkey

>>> if reg_value_exists(HKEY_LOCAL_MACHINE,makepath('SOFTWARE','VideoLAN','VLC'),'Version'):
...     print('VLC seems to be installed')
???
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

Args:

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=None, win64app=None, quiet_uninstall_string=None, install_location=None, display_name=None, display_version=None, publisher=None, icon=None, installed_size=None)[source]

Register or update the uninstall entry in Windows registry, so that the application is displayed in Control Panel / Programs and features with correct informations

Args:

installed_size (int): in MB (default: converting bytes from control file to megabytes)

Changed in version 2.3: now detect automatically if the app is win64

setuphelpers.register_windows_uninstall(package_entry, win64app=None)[source]

Add a uninstall entry in Windows registry for custom installer (for example: portable installation)

setuphelpers.registered_organization()[source]
setuphelpers.registry_delete(root, path, valuename)[source]

Delete the valuename inside specified registry path

The path can be either with backslash or slash

Args:

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, force=False)[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.

Args:

root : HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER … path : string like “software\microsoft\windows\currentversion”

or “software\wow6432node\microsoft\windows\currentversion”

keyname : Name of key

>>> from winsys import registry
>>> py27 = registry.Registry(r'HKEY_LOCAL_MACHINE\Software\Python\PythonCore\2.7')
>>> py27.copy(r'HKEY_LOCAL_MACHINE\Software\Python\PythonCore\test')
>>> registry_deletekey(HKEY_LOCAL_MACHINE,'Software\\Python\\PythonCore','test')
True
setuphelpers.registry_readstring(root, path, keyname, default='')[source]

Return a string from registry

Args:

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’ the path can be either with backslash or slash

>>> 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

Args:

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

Args:

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_appx(package, default_user=True)[source]

Remove Windows AppX package from computer environment

Args:

package (str): AppX Package name. Asterisk character (*) can be used as wildcard default_user (bool): Remove AppX Package from image. It prevent installation for new users

New in version 2.2.

setuphelpers.remove_desktop_shortcut(label)[source]

Remove a shortcut from the desktop of all users

Args:

label (str): label of shortcut without extension

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

Args:

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

setuphelpers.remove_metroapp(package)[source]

Uninstall and remove a metro package from the computer

New in version 1.3.9.

setuphelpers.remove_outdated_binaries(version, list_extensions=['exe', 'msi', 'deb', 'rpm', 'dmg', 'pkg'], filename_contains=None)[source]

Remove files based on the version contained in his filename, failing over on file version on compatible OSes

Args:

version (str): version number of keeped files list_extensions (str or list of str): file extensions of compared files filename_contains (str or list of str): Part of the filename that must be contained (useful for distinguishing architecture and os)

Returns:

list: list of deleted files

New in version 2.0.

Changed in version 2.2: Now returns removed files, now checking .exe and .msi file versions

setuphelpers.remove_printer(name)[source]

Remove a printer by its name

Args:

name (str) : name of local printer to be deleted

New in version 1.7.1.

>>> remove_printer('Brother QL-1060')
setuphelpers.remove_programs_menu_folder(folder)[source]

Remove a folder from the start menu of all users

Args:

folder(str): folder to remove

setuphelpers.remove_programs_menu_shortcut(label, folder=None)[source]

Remove a shortcut from the start menu of all users

Args:

label (str): label of shortcut without extension folder (str): subfolder of Programs menu where the shortcut resides.

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 not ignored by default. Pass ignore_errors=False to access possible errors.

Args:

path (str): path to directory to remove ignore_errors (boolean) : default to False. Set it to True to ignore exceptions on children deletion onerror (func) : hook called with (func, path, exc)

on each delete exception. Should raise if stop is required.

>>> def print_error(func, path, error):
>>>     print(u'Error when "%s" for "%s": "%s"' % (func.__name__, path, repr(error[1])))
>>>
>>> remove_tree(r'c:\tmp\target', onerror=print_error)

Changed in version 1.5.1.17: ignore_errors default to False

setuphelpers.remove_user_desktop_shortcut(label)[source]

Remove a shortcut from the desktop of current user

Args:

label (str): label of shortcut without extension

setuphelpers.remove_user_from_group(user, group)[source]

Remove membership from a local group for a user

setuphelpers.remove_user_programs_menu_folder(folder)[source]

Remove a folder from the start menu of current user

Args:

folder(str): folder to remove

setuphelpers.remove_user_programs_menu_shortcut(label, folder=None)[source]

Remove a shortcut from the start menu of current user

Args:

label (str): label of shortcut without extension

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

Args:

tmp_filename (str): Temporary path to file to rename (defaults to <target_filename>.pending) target_filename (str): Final target filename

setuphelpers.run(cmd, shell=True, timeout=600, accept_returncodes=[0, 3010], on_write=None, pidlist=None, return_stderr=True, **kwargs)[source]

Run the command cmd in a shell and return the output and error text as string

Args:

cmd : command and arguments, either as a string or as a list of arguments 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_writecallback when a new line is printed on stdout or stderr by the subprocess

func(unicode_line). arg is enforced to unicode

accept_returncodes (list) : list of return code which are considered OK default = (0, 3010) pidlist (list): external list where to append the pid of the launched process. return_stderr (bool or list) : if True, the error lines are returned to caller in result.

if a list is provided, the error lines are appended to this list

all other parameters from the psutil.Popen constructor are accepted

Returns:
RunOutputbytes like output of stdout and optionnaly stderr streams.

returncode attribute

Raises:

CalledProcessError: if return code of cmd is not in accept_returncodes list TimeoutExpired: if process is running for more than timeout time.

Changed in version 1.3.9: return_stderr parameters to disable stderr or get it in a separate list return value has a returncode attribute to

Changed in version 1.4.0: output is not forced to unicode

Changed in version 1.4.1: error code 1603 is no longer accepted by default.

Changed in version 1.5.1: If cmd is unicode, encode it to default filesystem encoding before running it.

>>> run(r'dir /B c:\windows\explorer.exe')
'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_as_administrator(afile, params=None)[source]

Launch with a runas verb to trigger a privileges elevation.

setuphelpers.run_notfatal(*cmd, **args)[source]

Runs the command and wait for it termination, returns output Ignore exit status code of command, return ‘’ instead

Changed in version 1.4.0: output is now enforced to unicode

setuphelpers.run_powershell(cmd, output_format='json', **kwargs)[source]

Run a command/script (possibly multiline) using powershell, return output in text format If format is ‘json’, the result is piped to ConvertTo-Json and converted back to a python dict for convenient use

WARNING: This works only with powershell >= 3

Args:

output_format (str): set output format as json (default) or xml (ElementTree object) or text

Returns:

str or dict or list

New in version 1.3.9.

setuphelpers.run_powershell_from_file(file, output_format='json', **kwargs)[source]

Run a command/script from file using powershell, return output in text format If format is ‘json’, the result is piped to ConvertTo-Json and converted back to a python dict for convenient use

New in version 1.3.9.

setuphelpers.run_task(name)[source]

Launch immediately the Windows Scheduled task

setuphelpers.running_as_admin()[source]
setuphelpers.running_as_system()[source]

Dirty way to check if current process is running as system user

setuphelpers.running_on_ac()[source]

Return True if computer is connected to AC power supply

New in version 1.3.9.

setuphelpers.sendto()[source]

What folder holds the SendTo shortcuts (from the Context Menu)?

setuphelpers.service_delete(service_name)[source]
setuphelpers.service_installed(service_name)[source]

Return True if the service is installed

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.service_restart(service_name, timeout=15)[source]

Restart a service by its service name

setuphelpers.service_start(service_name, timeout=15)[source]

Start a service by its service name

setuphelpers.service_stop(service_name, timeout=15)[source]

Stop a service by its service name

setuphelpers.set_computer_description(description)[source]

Change the computer descrption

setuphelpers.set_environ_variable(name, value, type=2, user=False)[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’

setuphelpers.set_file_hidden(path)[source]

Set the hidden attribute of file located at path Utility function for shutdown gpo script

Args:

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

Args:

path (str): path to the file

setuphelpers.set_service_start_mode(service_name, start_mode, change_state=True)[source]

Changing start mode of a service and changing his running status accordingly Usable values: ‘Auto’, ‘Manual’, ‘Disabled’ Informations: https://msdn.microsoft.com/en-us/library/aa384896(v=vs.85).aspx

Changed in version 2.2: Now interact on the running state

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.showmessage(msg)[source]
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)
setuphelpers.start_menu(common=0)[source]

What folder holds the Start Menu shortcuts?

setuphelpers.startup(common=0)[source]

What folder holds the Startup shortcuts (from the Start Menu)?

setuphelpers.system32()[source]

returns the path of system32directory

Returns:

str: path to system32 directory

>>> print(system32())
C:\WINDOWS\system32
setuphelpers.task_exists(name)[source]

Return true if a sheduled task names ‘name.job’ is defined

setuphelpers.time2display(adatetime)[source]
setuphelpers.uac_enabled()[source]

Return True if UAC is enabled

New in version 1.3.9.

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.uninstall_key_exists(uninstallkey, keywords=None, name=None)[source]

Check if the uninstalley is present in win32 / win54 registry

setuphelpers.unregister_dll(dllpath)[source]

Unregister a COM/OLE server DLL from registry

setuphelpers.unregister_uninstall(uninstallkey, win64app=None)[source]

Remove uninstall method from registry

Changed in version 2.3: now detect automatically if the app is win64

setuphelpers.unset_environ_variable(name, user=True)[source]

Remove a system wide persistent environment variable if it exist. Fails silently if it doesn’t exist

setuphelpers.unzip(zipfn, target=None, filenames=None, extract_with_full_paths=True)[source]

Unzip the files from zipfile with patterns in filenames to target directory

Args:

zipfn (str) : path to zipfile. (can be relative to temporary unzip location of package) target (str) : target location. Defaults to dirname(zipfile) + basename(zipfile) filenames (str or list of str): list of filenames / glob patterns (path sep is normally a slash) extract_with_full_paths (bool): keeping or not the subfolders of the archive as is

Returns:

list : list of extracted files

>>> unzip(r'C:\example\tis-7zip_9.2.0-15_all.wapt')
['C:\\example\\tis-7zip_9.2.0-15_all\\7z920-x64.msi',
 'C:\\example\\tis-7zip_9.2.0-15_all\\7z920.msi',
 'C:\\example\\tis-7zip_9.2.0-15_all\\setup.py',
 'C:\\example\\tis-7zip_9.2.0-15_all\\WAPT/control',
 'C:\\example\\tis-7zip_9.2.0-15_all\\WAPT/wapt.psproj',
 'C:\\example\\tis-7zip_9.2.0-15_all\\WAPT/manifest.sha256',
 'C:\\example\\tis-7zip_9.2.0-15_all\\WAPT/signature']
>>> unzip(r'C:\example\tis-7zip_9.2.0-15_all.wapt', filenames=['*.msi','*.py'])
['C:\\example\\tis-7zip_9.2.0-15_all\\7z920-x64.msi',
 'C:\\example\\tis-7zip_9.2.0-15_all\\7z920.msi',
 'C:\\example\\tis-7zip_9.2.0-15_all\\setup.py']
>>> unzip(r'C:\example\tis-7zip_9.2.0-15_all.wapt', target='test', filenames=['*.msi','*.py'])
['C:\\example\\test\\7z920-x64.msi',
 'C:\\example\\test\\7z920.msi',
 'C:\\example\\test\\setup.py']
>>> unzip(r'C:\example\tis-7zip_9.2.0-15_all.wapt', filenames='WAPT/*')
['C:\\example\\tis-7zip_9.2.0-15_all\\WAPT/control',
 'C:\\example\\tis-7zip_9.2.0-15_all\\WAPT/wapt.psproj',
 'C:\\example\\tis-7zip_9.2.0-15_all\\WAPT/manifest.sha256',
 'C:\\example\\tis-7zip_9.2.0-15_all\\WAPT/signature']
>>> unzip(r'C:\example\tis-7zip_9.2.0-15_all.wapt', filenames='WAPT/control')
['C:\\example\\tis-7zip_9.2.0-15_all\\WAPT\\control']
>>> unzip('tis-7zip_9.2.0-15_all.wapt', target='.', filenames='WAPT/control')
['.\\WAPT\\control']
>>> unzip(r'C:\example\tis-7zip_9.2.0-15_all.wapt', target=r'C:\example\', filenames='WAPT/control')
['C:\\example\\WAPT\\control']
>>> unzip('tis-7zip_9.2.0-15_all.wapt', target=basedir, filenames='WAPT/control')
['C:\\example\\WAPT\\control']
>>> unzip(r'C:\example\tis-7zip_9.2.0-15_all.wapt', filenames='WAPT/control', extract_with_full_paths=False)
['C:\\example\\control']

New in version 1.3.11.

Changed in version 2.2: added extract_with_full_paths parameter

setuphelpers.unzip_with_7zip(filename, target=None, filenames=[], recursive=True, extract_with_full_paths=True)[source]

Extract the files from an archive file with 7zip with patterns in filenames to target directory

Args:

filename (str): path to archive file. (can be relative to temporary unzip location of package) target (str): archive content to target dir location (dir will be created if needed). Default: dirname(archive file) + basename(archive file) filenames (str or list of str): list of filenames / glob patterns (path sep is normally a slash) recursive (bool): looking or not for filenames recursively extract_with_full_paths (bool): keeping or not the subfolders of the archive as is

Returns:

None

New in version 2.0.

Changed in version 2.2: changed default target location to make it correspond with unzip()

setuphelpers.user_appdata()[source]

Return the roaming appdata profile of current user

Returns:

str: path like u’C:\Users\username\AppData\Roaming’

setuphelpers.user_desktop()[source]

Return path to current logged in user desktop

>>> user_desktop()
u'C:\\Users\\htouvet\\Desktop'
setuphelpers.user_home_directory()[source]
setuphelpers.user_local_appdata()[source]

Return the local appdata profile of current user

Returns:

str: path like u’C:\Users\user\AppData\Local’

setuphelpers.wait_uninstallkey_absent(key=None, max_loop=120, keywords=None, name=None, raise_on_timeout=False)[source]
setuphelpers.wait_uninstallkey_present(key=None, max_loop=120, keywords=None, name=None, raise_on_timeout=False)[source]
setuphelpers.wget(url, target: Optional[str] = None, printhook: Optional[Callable] = None, proxies: Optional[dict] = None, connect_timeout=10, download_timeout=None, verify_cert=None, referer=None, user_agent=None, cert=None, resume=False, md5=None, sha1=None, sha256=None, cache_dir=None, requests_session=None, limit_bandwidth=None) str[source]

Copy the contents of a file from a given URL to a local file.

Args:

url (str): URL to document target (str) : full file path of downloaded file. If None, put in a temporary dir with supplied url filename (final part of url) proxies (dict) : proxies to use. eg {‘http’:’http://wpad:3128’,’https’:’http://wpad:3128’} timeout (int) : seconds to wait for answer before giving up auth (list) : (user,password) to authenticate with basic auth verify_cert (bool or str) : either False, True (verify with embedded CA list), or path to a directory or PEM encoded CA bundle file

to check https certificate signature against.

cert (list) : tuple/list of (x509certfilename,pemkeyfilename,key password) for authenticating the client. If key is not encrypted, password must be None referer (str): user_agent: resume (bool): md5 (str) : sha1 (str) : sha256 (str) : cache_dir (str) : if file exists here, and md5 matches, copy from here instead of downloading. If not, put a copy of the file here after downloading.

requests_session (request.Session) : predefined request session to use instead of building one from scratch from proxies, cert, verfify_cert

Returns:

str : path to downloaded 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: Optional[dict] = None, verify_cert=None, referer=None, user_agent=None, timeout=None, cert=None, requests_session=None, as_json=False) str[source]

Return the content of a remote resource as a string / bytes or dict with a http get request.

Raise an exception if remote data can’t be retrieved.

Args:

url (str): http(s) url proxies (dict): proxy configuration as requests requires it {‘http’: url, ‘https’:url} verify_cert (bool or str) : verfiy server certificate, path to trusted CA bundle cert (tuple of 3 str) : (cert_path, key_path, key password) client side authentication.

requests_session (request.Session) : predefined request session to use instead of building one from scratch

Returns:

str or bytes or dict : content of remote resource. str or bytes or json depending of the encoding and the Content-Type.

>>> data = wgets('https://wapt/ping')
>>> "msg" in data
True
setuphelpers.win32com_ensure_dispatch_patch(prog_id)[source]
setuphelpers.win_startup_info()[source]

Return the applications started at boot or login

Returns:
dict{‘common_startup’: [{‘command’: ‘’,

‘name’: ‘’},]

‘run’: [{‘command’: ‘’,

‘name’: ‘’},]

setuphelpers.wincomputername()
setuphelpers.windomainname()
setuphelpers.windows_version(members_count=3)[source]

Same than windows_version_from_WMI() but get information for windows 10 in registry (it’s faster)

New in version 1.3.5.

Changed in version 1.6.2.5: members_count (int) : default to 3.

setuphelpers.wmi_as_struct(wmi_object, exclude_subkeys=['OEMLogoBitmap'])[source]

Convert a wmi object to a simple python list/dict structure

setuphelpers.wmi_info(keys=['Win32_ComputerSystem', 'Win32_ComputerSystemProduct', 'Win32_BIOS', 'Win32_NetworkAdapter', 'Win32_Printer', 'Win32_VideoController', 'Win32_LogicalDisk', 'Win32_OperatingSystem', 'Win32_DesktopMonitor', 'Win32_USBController', 'Win32_DiskDrive', 'Win32_Volume'], exclude_subkeys=['OEMLogoBitmap'], **where)[source]

Get WMI machine informations as dictionaries

setuphelpers.wmi_info_basic()[source]

Return uuid, serial, model, vendor from WMI

Returns:

dict: minimal informations for wapt registration

>>> r = wmi_info_basic()
>>> 'System_Information' in r
True
setuphelpers.wua_agent_version()[source]

PackageEntry Class

class setuphelpers.PackageEntry(package='', version='0', repo='', waptfile=None, section='base', _default_md='sha256', **kwargs)[source]

Manage package attributes coming from either control files in WAPT package, local DB, or developement dir.

Methods to build, unzip, sign or check a package. Methods to sign the control attributes and check them.

>>> pe = PackageEntry('testgroup','0')
>>> pe.depends = 'tis-7zip'
>>> pe.section = 'group'
>>> pe.description = 'A test package'
>>> print(pe.ascontrol())
package           : testgroup
version           : 0
architecture      : all
section           : group
priority          : optional
maintainer        :
description       : A test package
depends           : tis-7zip
conflicts         :
maturity          :
locale            :
min_wapt_version  :
sources           :
installed_size    :
signer            :
signer_fingerprint:
signature_date    :
signed_attributes :
>>>
as_control_bytes()[source]

Return this package entry metadata as bytes as saved in package control file

Return:

bytes: lines with key: value

as_zipfile(mode='r')[source]

Return a CustomZipFile for this package for read only operations

ascontrol(with_repo_attributes=False, with_empty_attributes=False)[source]

Return control attributes and values as stored in control packages file

Each attribute on a line with key : value If value is multiline, new line begin with a space.

Args:

with_repo_attributes (bool) : if True, include md5sum and filename (for Packages index only) with_empty_attributes (bool) : weither to include attribute with empty value too or only

non empty and/or signed attributes

Returns:

str: lines of attr: value

asrequirement()[source]

Return package and version for designing this package in depends or install actions

Returns:

str: “packagename (=version)”

build_management_package(target_directory=None)[source]

Build the WAPT package from attributes only, without setup.py stores the result in target_directory.

self.sourcespath must be None. Package will contain only a control file.

Args:
target_directory (str): where to create Zip wapt file.

if None, temp dir will be used.

Returns:

str: path to zipped Wapt file. It is unsigned.

>>> pe = PackageEntry('testgroup','0',description='Test package',maintainer='Hubert',sources='https://dev/svn/testgroup',architecture='x86')
>>> waptfn = pe.build_management_package()
>>> key = SSLPrivateKey('c:/private/htouvet.pem',password='monmotdepasse')
>>> crt = SSLCertificate('c:/private/htouvet.crt')
>>> pe.sign_package(crt,key)
>>> pe.unzip_package()
'c:\users\htouvet\appdata\local\temp\waptob4gcd'
>>> ca = SSLCABundle('c:/wapt/ssl')
>>> pe.check_control_signature(ca)
<SSLCertificate cn=u'htouvet' issuer=u'tranquilit-ca-test' validity=2017-06-28 - 2027-06-26 Code-Signing=True CA=True>
build_manifest(exclude_filenames=None, block_size=1048576, forbidden_files=[], md='sha256', waptzip=None, excludes=[])[source]

Calc the manifest of a wapt package

Args:
forbidden_files (list): list of relative files which must not be present for the manifest to be built

(if one is found, build fails)

exclude_filenames (list) : list of exact (relative to package root with forward slashes) filepathes to exclude from manifest. excludes (list) : list of file / dir patterns to exclude, whatever level they are in the file hierarchy

Returns:

dict: {filepath:shasum,}

build_package(excludes=[], target_directory=None, excludes_full=['.svn', '.git', '.gitignore', 'setup.pyc', '__pycache__'])[source]

Build the WAPT package, stores the result in target_directory Zip the content of self.sourcespath directory into a zipfile named with default package filename based on control attributes.

Update filename attribute. Update localpath attribute with result filepath.

Args:

excludes (list) : list of patterns for source files to exclude from built package. target_directory (str): target directory where to store built package.

If None, use parent directory of package sources dircetory.

excludes_full (list) : list of exact (relative to package root) filepathes to exclude from Zip.

Returns:

str: full filepath to built wapt package

call_setup_hook(hook_name='session_setup', wapt_context=None, params=None, force=None, user=None)[source]

Calls a hook in setuppy given a wapt_context

Set basedir, control, and run context within the function context.

Args:

hook_name (str): name of function to call in setuppy wapt_context (Wapt) : run context

Returns:

output of hook.

Changes:

1.6.2.1: the called hook is run with Disabled win6432 FileSystem redirection

change_depends_conflicts_prefix(new_prefix)[source]

Change prefix of package name to new_prefix in depends and conflicts csv lists and return True if it was really changed.

Args:

new_prefix (str): new prefix to put in package names

Returns:

bool

change_prefix(new_prefix)[source]

Change prefix of package name to new_prefix and return True if it was really changed.

check_control_signature(trusted_bundle, signers_bundle=None)[source]

Check in memory control signature against a list of public certificates

Args:

trusted_bundle (SSLCABundle): Trusted certificates. : packages certificates must be signed by one of this bundle. signers_bundle : Optional. List of potential packages signers certificates chains.

When checking Packages index, actual packages are not available, only certificates embedded in Packages index. Package signature are checked against these certificates looking here for potential intermediate CA too. and matching certificate is checked against trusted_bundle.

Returns:

SSLCertificate : matching trusted package’s signers SSLCertificate

>>> from waptpackage import *
>>> from common import SSLPrivateKey,SSLCertificate
>>> k = SSLPrivateKey('c:/private/test.pem')
>>> c = SSLCertificate('c:/private/test.crt')
>>> p = PackageEntry('test',version='1.0-0')
>>> p.depends = 'test'
>>> p._sign_control(k,c)
>>> p.check_control_signature(c)
>>> p.check_control_signature(SSLCABundle('c:/wapt/ssl'))
check_package_signature(trusted_bundle, ignore_missing_files=False)[source]

Check - hash of files in unzipped package_dir with list in package’s manifest file - try to decrypt manifest signature with package’s certificate - check that the package certificate is issued by a know CA or the same as one the authorized certitificates.

Args:

trusted_bundle (SSLCABundle) : Local certificates store. Certificates in trusted_bundle.trusted_certificates are trusted. ignore_missing_files (bool): whether to raise exception for missing files. Useful to check stripped down packages when remote resigning

Returns:

SSLCertificate : matching certificate

Raises:

Exception if no certificate match is found.

delete_localsources()[source]

Remove the unzipped local directory

get(name, default=None)[source]

Get PackageEntry property.

Args:

name (str): property to get. name is forced to lowercase. default (any) : value to return in case the property doesn’t not exist.

Returns:

any : property value

get_impacted_process_list()[source]

Return a list containing the impacted process

Returns:

List[str] impacted process list

get_localized_description(locale_code=None)[source]

locale_code is a 2 chars code like fr or en or de

get_software_version()[source]

Return the software version only (without the build number of the package)

Returns:

str: “software_version”

get_stripped_package()[source]

Build a package keeping only Wapt stuff… Keeps only WAPT directory and setup.py

Returns:

bytes: zipped data

has_file(fname)[source]

Return None if fname is not in package, else return file datetime

Args:

fname (unicode): file path like WAPT/signature

Returns:

datetime : last modification datetime of file in Wapt archive if zipped or local sources if unzipped

inc_build()[source]

Increment last number part of version in memory

invalidate_signature()[source]

Remove all signature informations from control and unzipped package directory Package must be in unzipped state.

list_corrupted_files(ignore_missing_files=False, remove_extra_files=False)[source]

Check hexdigest sha for the files in manifest. Package must be already unzipped.

Returns:

list: non matching files (corrupted files)

load_control_from_dict(adict)[source]

Fill in members of entry with keys from supplied dict

adict members which are not a registered control attribute are set too and attribute name is put in list of “calculated” attributes.

Args:

adict (dict): key,value to put in this entry

Returns:

PackageEntry: self

load_control_from_wapt(fname=None, calc_md5=True, keep_control_lines=False)[source]

Load package attributes from the control file (utf8 encoded) included in WAPT zipfile fname

Args:
fname (str or unicode): Package file/directory path

If None, try to load entry attributes from self.sourcespath or self.localpath If fname is a file path, it must be Wapt zipped file, and try to load control data from it If fname is a directory path, it must be root dir of unzipped package file and load control from <fname>/WAPT/control

calc_md5 (boolean): if True and fname is a zipped file, initialize md5sum attribute with md5 part of filename or calc from Zipped file

Returns:

PackageEntry: self

make_package_edit_directory()[source]

Return the standard package directory to edit the package based on current attributes

Returns:
str: standard package filename
  • {package}_{version}_{architecture}_{OS}_{Min-OS-Version}_{Max-OS-Version}_{maturity}_{locale}-wapt

make_package_filename(with_md5sum=False)[source]

Return the standard package filename based on current attributes parts of control which are either ‘all’ or empty are not included in filename

Returns:
str: standard package filename
  • packagename.wapt for host

  • packagename_arch_maturity_locale.wapt for group

  • packagename_version_arch_maturity_locale.wapt for others

match(match_expr)[source]

Return True if package entry match a package string like ‘tis-package (>=1.0.1-00)

Check if entry match search words

Args:

search (str): words to search for separated by spaces

Returns:

boolean: True if entry contains the words in search in correct order and at word boundaries

match_version(version_expr)[source]

Return True if package entry match a version string condition like ‘>=1.0.1-00’

merge_stripped_package(stripped_package_zip_data=None, stripped_package_filename=None)[source]

Use the files from stripped_package_zip_data and include it in current unzipped package, remove files not in manifest, and recheck file hashes.

package_certificates()[source]

Return certificates from package. If package is built, take it from Zip else take the certificates from unzipped directory

Returns:
list: list of embedded certificates when package was signed or None if not provided or signed.

First one of the list is the signer, the others are optional intermediate CA

package_ident()[source]

Version independent package key

Returns:

tuple

parse_version()[source]

Parse version to major, minor, patch, pre-release, build parts.

save_control_to_wapt(fname=None, force=True)[source]

Save package attributes to the control file (utf8 encoded)

Update self.locapath or self.sourcespath if not already set.

Args:
fname (str)base directoy of waptpackage or filepath of Zipped Packges.

If None, use self.sourcespath if exists, or self.localpath if exists

force (bool) : write control in wapt zip file even if it already exist

Returns:

PackageEntry : None if nothing written, or previous PackageEntry if new data written

Raises:

Exception: if fname is None and no sourcespath and no localpath Exception: if control exists and force is False

set_software_version(version, inc_build=False)[source]

Set the software version only inc_build will increment the buildnumber

sign_package(certificate, private_key, mds=['sha256'], keep_signature_date=False, excludes_full=['.svn', '.git', '.gitignore', 'setup.pyc', '__pycache__'], excludes=[])[source]

Sign a package source directory or an already built (zipped) package. Should follow immediately the build_package step.

Append signed control, manifest.sha256 and signature to zip wapt package If these files are already in the package, they are first removed.

Use the self.localpath attribute to get location of waptfile build file.

Args:

certificate (SSLCertificate or list): signer certificate chain private_key (SSLPrivateKey): signer private key keep_signature_date (bool): If true, previous date fo signature is kept (useful when resigning is needed, but no meaningful change has been done) mds (list): list of message digest manifest and signature methods to include. For backward compatibility. excludes_full (list) : list of exact (relative to package root) filepathes to exclude from manifest. excludes (list) : list of file / dir patterns to exclude, whatever level they are in the file hierarchy

Returns:

str: signature

sign_stripped_package(certificate, private_key, excludes_full=['.svn', '.git', '.gitignore', 'setup.pyc', '__pycache__'], excludes=[], sign_setuppy=False)[source]

Sign an unzipped source package assuming digests in manifest file are OK except for control and certificate.crt * remove signature files -> WAPT/certificate.crt, WAPT/signature.sha256, * resign WAPT/control * update control hash in WAPT/manifest.sha256 * resign WAPT/manifest.sha256 and put in WAPT/signature.sha256

Args:

certificate (list of SSLCertificate) : certificates chain of the signer. First certificate is the signer’s one. other are intermediate CA private_key (SSLPrivateKey) : key to sign the control and manifest files. excludes_full excludes

Returns:

str: signature of manifest.sha256

unzip_package(target_dir=None, cabundle=None, ignore_missing_files=False)[source]

Unzip package and optionnally check content

Args:

target_dir (str): where to unzip package content. If None, a temp dir is created cabundle (list) : list of Certificates to check content. If None, no check is done

Returns:

str : path to unzipped packages files

Raises:

EWaptNotAPackage, EWaptBadSignature,EWaptCorruptedFiles if check is not successful, unzipped files are deleted.

Version Class

class setuphelpers.Version(version, members_count=None)[source]

Version object of form 0.0.0 can compare with respect to natural numbering and not alphabetical

Args:

version (str) : version string member_count (int) : number of version memebers to take in account.

If actual members in version is less, add missing memeber with 0 value If actual members count is higher, removes last ones.

>>> 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
>>> Version('7') < Version('7.1')
True

Changed in version 1.6.2.5: truncate version members list to members_count if provided.

sortable_str()[source]

Output a str suitable for direct ordering members are converted to a chars hex padded with zero on the left. If member is not a digit, it is padded to a 8 chars string padded with spaces on the right.