setuphelpers module

exception setuphelpers.CalledProcessError(returncode, cmd, output=None)[source]

This exception is raised when a process run by check_call() or check_output() returns a non-zero exit status.

cmd, returncode, output
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_os_version    :
max_os_version    :
min_wapt_version  :
sources           :
installed_size    :
signer            :
signer_fingerprint:
signature_date    :
signed_attributes :
>>>
as_zipfile(mode='r')[source]

Return a Zipfile for this package for read only operations

ascontrol(with_non_control_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.

Parameters:
  • with_non_control_attributes (bool) – weither to include all attributes or only those relevant for final package content.
  • with_empty_attributes (bool) – weither to include attribute with empty value too or only non empty and/or signed attributes
Returns:

lines of attr: value

Return type:

str

asrequirement()[source]

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

Returns:“packagename (=version)”
Return type:str
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)
'qrUUQeNJ3RSSeXQERrP9vD7H/Hfvw8kmBXZvczq0b2PVRKPdjMCElYKzryAbQ+2nYVDWAGSGrXxs

y2WzhOhrdMfGfcy6YLaY5muApoArBn3CjKP5G6HypOGD5agznLEKkcUg5/Y3aIR8bL55Ylmp3RaS WKnezUcuA2yuNuKwHsXr9CdihK5pRyYrm5KhCNy8S7+kAJvayrUj5q8ur6z0nNMQCHEnWGN+V3MI 84PymR1eXsuauKeYNqIESWCyyD/lFZv0JEYfrfml8rirC6yd6iTJW0OqH7gKwCEl03JpRaF91vWB OXN65S1j2oV8Jgjq43oa7lyywKC01a/ehQF5Jw== ‘

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

Calc the manifest of an already built (zipped) wapt package

Returns:{filepath:shasum,}
Return type:dict
build_package(excludes=['.svn', '.git', '.gitignore', 'setup.pyc'], target_directory=None)[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.

Parameters:
  • 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.
Returns:

full filepath to built wapt package

Return type:

str

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

Parameters:
  • trusted_bundle (SSLCABundle) – Trusted certificates. : packages certificates must be signed by a 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 againt these certificates looking here for potential intermediate CA too. and matching certificate is checked against trusted_bundle.
Returns:

matching trusted package’s signers SSLCertificate

Return type:

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

Parameters:trusted_bundle (SSLCABundle) – list of authorized certificates / ca filepaths
Returns:matching certificate
Return type:SSLCertificate
Raises:Exception if no certificate match is found.
delete_localsources()[source]

Remove the unzipped local directory

download_url

Calculate the download URL for this entry

get(name, default=None)[source]

Get PackageEntry property.

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

property value

Return type:

any

has_file(fname)[source]

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

Parameters:fname (unicode) – file path like WAPT/signature
Returns:last modification datetime of file in Wapt archive if zipped or local sources if unzipped
Return type:datetime
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()[source]

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

Returns:non matching files (corrupted files)
Return type:list
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.

Parameters:adict (dict) – key,value to put in this entry
Returns:self
Return type:PackageEntry
load_control_from_wapt(fname=None, calc_md5=True)[source]

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

Parameters:
  • fname (str or list) – If None, try to load entry attributes from self.sourcespath or self.localpath If fname is a list, consider fname is the lines of control file If fname is file, it must be Wapt zipped file, and try to load control data from it If fname is a directory, 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 sum of Zipped file/
Returns:

self

Return type:

PackageEntry

make_package_edit_directory()[source]

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

Returns:
standard package filename
  • packagename_arch_maturity_locale-wapt for softwares and groups
  • packagename-wapt for host.
Return type:str
make_package_filename()[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:
standard package filename
  • packagename.wapt for host
  • packagename_arch_maturity_locale.wapt for group
  • packagename_version_arch_maturity_locale.wapt for others
Return type:str
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

Parameters:search (str) – words to search for separated by spaces
Returns:True if entry contains the words in search in correct order and at word boundaries
Return type:boolean
match_version(match_expr)[source]

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

package_certificate()[source]

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

Returns:
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
Return type:list
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.

Parameters:
  • 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:

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

Return type:

PackageEntry

Raises:
  • Exception – if fname is None and no sourcespath and no localpath
  • Exception – if control exists and force is False
sign_package(certificate, private_key=None, password_callback=None, private_key_password=None, mds=['sha256'])[source]

Sign an already built 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.

Parameters:
  • certificate (SSLCertificate or list) – signer certificate chain
  • private_key (SSLPrivateKey) – signer private key
  • password_callback (func) – function to call to get key password if encrypted.
  • private_key_password (str) – password to use if key is encrypted. Use eithe this or password_callback
  • mds (list) – list of message digest manifest and signature methods to include. For backward compatibility.
Returns:

signature

Return type:

str

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

Unzip package and optionnally check content

Parameters:
  • 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:

path to unzipped packages files

Return type:

str

Raises:
  • EWaptNotAPackage, EWaptBadSignature,EWaptCorruptedFiles
  • if check is not successful, unzipped files are deleted.
exception setuphelpers.TimeoutExpired(cmd, output=None, timeout=None)[source]

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.Version(version, members_count=None)[source]

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

Add membership to a local group for a user

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

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

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_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='')[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.

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'
setuphelpers.create_user_programs_menu_shortcut(label, target='', arguments='', wDir='', icon='')[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.
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('Doc-TranquilIT', target='https://doc.wapt.fr')
u'C:\\Users\\htouvet\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\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\\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.currentdate()[source]

date as string YYYYMMDD

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

date/time as YYYYMMDD-hhmmss

>>> currentdatetime()
'20161102-193600'
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_group(group)[source]

Delete a local user group

setuphelpers.delete_task(name)[source]

Removes a Windows scheduled task

Parameters: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]

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

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

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

Parameters: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_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_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_hostname()[source]

Return host fully qualified domain name in lower case

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

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

setuphelpers.get_task(name)[source]

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

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

Returns guessed default values for package templates based on installer binary

Parameters:installer_path (str) – filepath to installer
Returns:
Return type: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.host_info()[source]

Read main workstation informations, returned as a dict

Returns:main properties of host, networking and windows system
Return type:dict

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

Check if an option is present in section of the inifile

Parameters:
  • inifilename (str) – Path to the ini file
  • section (str) – section
Returns:

True if the key exists

Return type:

boolean

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

Remove a key within the section of the inifile

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

True if the key/option has been removed

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

Remove a section within the inifile

Parameters:
  • inifilename (str) – Path to the ini file
  • section (str) – section to remove
Returns:

True if the section has been removed

Return type:

boolean

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, name=None)[source]

Return list of installed software from registry (both 32bit and 64bit

Parameters:
  • 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:
{‘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.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.installed_windows_updates(**queryfilter)[source]

Return list of installed updates, indepently from WUA agent

Parameters:queryfilter (dict) –
Returns:list

New in version 1.3.3.

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)[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 (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 (booleen) – Defined if uninstalling the old version of the uninstallkey should be started.
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 for remove old version uninstallkey

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)[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 (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
  • 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.
  • remove_old_version (booleen) – Defined if uninstalling the old version of the uninstallkey should be started.
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 for remove old version uninstallkey

setuphelpers.isdir()

Return true if the pathname refers to an existing directory.

setuphelpers.isfile(path)[source]

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

New in version 1.2.3.

setuphelpers.local_users_profiles()[source]

Return a list of all local user’s profile paths

Returns:list of desktop path
Return type:list
>>> 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

>>> makepath('c:',programfiles)
'C:\\Program Files'
setuphelpers.memory_status()[source]

Return system memory statistics

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

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

setuphelpers.need_install(key, min_version=None, force=False, get_version=None)[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 (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
Returns:

boolean

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 of Windows Update, CBS Updates or File Renames
Return type:list
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.

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()[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_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.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.

Parameters:
  • 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_value_exists(rootkey, subkeypath, value_name)[source]

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

Parameters:
  • 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:

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

Return type:

boolean

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

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

Parameters:
  • 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

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

setuphelpers.remove_programs_menu_shortcut(label)[source]

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

setuphelpers.remove_user_programs_menu_shortcut(label)[source]

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

Parameters:
  • 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_write – callback 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,1601)
  • 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
  • other parameters from the psutil.Popen constructor are accepted (all) –
Returns:

bytes like output of stdout and optionnaly stderr streams.

returncode attribute

Return type:

RunOutput

Raises:

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_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 not enforced to unicode

setuphelpers.run_task(name)[source]

Launch immediately the Windows Scheduled task

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

New in version 1.3.9.

setuphelpers.running_on_ac()[source]

Return True if computer is connected to AC power supply

New in version 1.3.9.

setuphelpers.running_as_system()[source]

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

setuphelpers.remove_metroapp(package)[source]

Uninstall and remove a metro package from the computer

New in version 1.3.9.

setuphelpers.sendto()[source]

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

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

Restart a service by its service name

setuphelpers.service_start(service_name)[source]

Start a service by its service name

setuphelpers.service_stop(service_name)[source]

Stop a service by its service name

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’

setuphelpers.set_file_hidden(path)[source]

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)
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:path to system32 directory
Return type:str
>>> print system32()
C:\Windows\system32
setuphelpers.task_exists(name)[source]

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

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

Unregister a COM/OLE server DLL from registry

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

Return the local appdata profile of current user

Returns:path like u’C:\Users\user\AppData\Local’
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=None, printhook=None, proxies=None, connect_timeout=10, download_timeout=None, verify_cert=False, referer=None, user_agent=None, cert=None, resume=False, md5=None, cache_dir=None)[source]

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

Parameters:
  • 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 wirh 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) – pair of (x509certfilename,pemkeyfilename) for authenticating the client
  • referer (str) –
  • user_agent
  • resume (bool) –
  • md5 (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.
Returns:

path to downloaded file

Return type:

str

>>> 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, timeout=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.wmi_info(keys=['Win32_ComputerSystem', 'Win32_ComputerSystemProduct', 'Win32_BIOS', 'Win32_NetworkAdapter', 'Win32_Printer', 'Win32_VideoController', 'Win32_LogicalDisk', 'Win32_OperatingSystem'], exclude_subkeys=['OEMLogoBitmap'], **where)[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.wmi_as_struct(wmi_object, exclude_subkeys=['OEMLogoBitmap'])[source]

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

setuphelpers.windows_version()[source]

see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx

New in version 1.3.5.

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

setuphelpers.win_startup_info()[source]

Return the applications started at boot or login

Returns:
{‘common_startup’: [{‘command’: ‘’,
’name’: ‘’},]
’run’: [{‘command’: ‘’,
’name’: ‘’},]
Return type:dict
class setuphelpers.WindowsVersions[source]

Helper class to get numbered windows version from windows name version

… versionadded:: 1.3.5

setuphelpers.get_profiles_users(domain_sid=None)[source]

Return list of locally created profiles usernames

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

Return the filesystem path to profile of user with SID sid

setuphelpers.local_admins()[source]

List local users who are local administrators

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

List the local groups a user is member Of

setuphelpers.set_computer_description(description)[source]

Change the computer descrption

setuphelpers.get_computer_description()[source]

Get the computer descrption

setuphelpers.uac_enabled()[source]

Return True if UAC is enabled

New in version 1.3.9.

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

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

Parameters:
  • 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)
Returns:

list of extracted files

Return type:

list

>>> unzip(r'C:      ranquilit\wapt  ests\packages   is-7zip_9.2.0-15_all.wapt')
[u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\7z920-x64.msi',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\7z920.msi',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\setup.py',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\WAPT/control',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\WAPT/wapt.psproj',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\WAPT/manifest.sha256',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\WAPT/signature']
>>> unzip(r'C:      ranquilit\wapt  ests\packages   is-7zip_9.2.0-15_all.wapt',filenames=['*.msi','*.py'])
[u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\7z920-x64.msi',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\7z920.msi',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\setup.py']
>>> unzip(r'C:      ranquilit\wapt  ests\packages   is-7zip_9.2.0-15_all.wapt',filenames='WAPT/*')
[u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\WAPT/control',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\WAPT/wapt.psproj',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\WAPT/manifest.sha256',
 u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\WAPT/signature']
>>> unzip(r'C:      ranquilit\wapt  ests\packages   is-7zip_9.2.0-15_all.wapt',filenames='WAPT/control')
[u'C:\tranquilit\wapt\tests\packages\tis-7zip_9.2.0-15_all\WAPT\control']

New in version 1.3.11.