Giter VIP home page Giter VIP logo

windows_tools's Introduction

windows_tools

Collection of useful python functions around Microsoft Windows

License Percentage of issues still open Maintainability codecov windows-tests GitHub Release

windows_tools is a set of various recurrent functions amongst

  • antivirus: antivirus state and list of installed AV engines
  • bitlocker: drive encryption status and protector key retrieval
  • bitness: simple bitness identification
  • file_utils: file ownership handling, NTFS & ReFS ACL handling, file listing with permission fixes
  • impersonate: python Runas implementation
  • installed_software: list of installed software from registry, 32 and 64 bits
  • logical_disk: logical disk listing
  • misc: basic time related functions to convert windows ticks into epoch / date strings
  • office: microsoft Office version identification, works for click & run, O365 and legacy
  • powershell: powershell wrapper to identify interpreter and run scripts or commands
  • product_key: windows product key retrieval
  • registry: registry 32 and 64 bit API
  • securityprivilege: enable / disable various security privileges for user
  • server: windows server identification
  • signtool: Easily sign executables with Authenticode
  • updates: get all installed windows updates based on COM, WMI and registry retrieval methods
  • users: user lookup for SID/PySID/username
  • virtualization: virtualization platform identification for guest
  • windows_firewall: windows firewall state retrieval
  • wmi_queries: windows WMI query wrapper, wmi timezone converters

It is compatible with Python 3.5+ and is tested on Windows only (obviously).

Setup

You may install the whole windows_tools package or any subpackage using the following commands

pip install windows_tools
pip install windows_tools.<subpackage>

Usage

antivirus

The antivirus package tries to list installed Antivirus products via the SecurityCenter API (using WMI calls). Since SecurityCenter API does not exist on Windows Servers, we also need to check for installed antivirus software using the uninstall registry keys. These checks are more fuzzy, but allow to detect the following products:

  • avast
  • avira
  • avg technologies
  • bitdefender
  • dr web
  • eset
  • f-secure
  • g data software
  • kaspersky
  • mcafee
  • panda security
  • sophos
  • trend micro
  • malwarebytes
  • vipre
  • sentinel one
  • cybereason
  • cylance

On top of that list, it will detect any installed software containing "antivirus/antiviral/antimalware" in the name.

Please report back if your antivirus is not detected, so we can improve the fuzzy detection here.

Usage

import windows_tools.antivirus

result = windows_tools.antivirus.get_installed_antivirus_software()

result will contain a list of dict like

[{
        'name': 'Windows Defender',
        'version': None,
        'publisher': None,
        'enabled': False,
        'is_up_to_date': True,
        'type': 'Windows Defender / Security Essentials'
    }, {
        'name': 'Malwarebytes version 4.4.6.132',
        'version': '4.4.6.132',
        'publisher': 'Malwarebytes',
        'enabled': None,
        'is_up_to_date': None,
        'type': None
    }
]

Warning Keys enabled, is_up_to_date and type are only filled via securityCenter API*. Keys version and publisher are only filled via installed software list. The only guaranteed filled key will always be name

bitlocker

Bitlocker can only work on NTFS or ReFS formatted disks. Bitlocker keys can only be retrieved on local disks.

Usage

import windows_tools.bitlocker

result = windows_tools.bitlocker.get_bitlocker_full_status()

result will contain a dict as follows containing raw strings from manage-bde windows tool:

{
	'C:': {
		'status': 'Chiffrement de lecteur BitLocker\xa0: outil de configuration version 10.0.19041\nCopyright (C) 2013 Microsoft Corporation. Tous droits réservés.\n\nVolume C: [Windows ]\n[Volume du système d?exploitation]\n\n    Taille :                     855,14 Go\n    Version de BitLocker :       Aucun\n    État de la conversion :      Intégralement déchiffré\n    Pourcentage chiffré :        0,0%\n    Méthode de chiffrement :     Aucun\n    État de la protection\xa0:      Protection désactivée\n    État du verrouillage :       Déverrouillé\n    Champ d?identification :     Aucun\n    Protecteurs de clés :        Aucun trouvé\n\n', 
		'protectors': None
	},
	'D:': {
		'status': 'Chiffrement de lecteur BitLocker\xa0: outil de configuration version 10.0.19041\nCopyright (C) 2013 Microsoft Corporation. Tous droits réservés.\n\nVolume D: [Étiquette inconnue]\n[Volume de données]\n\n    Taille :                     Inconnu Go\n    Version de BitLocker :       2.0\n    État de la conversion :      Inconnu\n    Pourcentage chiffré :        Inconnu%\n    Méthode de chiffrement :     XTS-AES 128\n    État de la protection\xa0:      Inconnu\n    État du verrouillage :       Verrouillé\n    Champ d?identification :     Inconnu\n    Déverrouillage automatique : Désactivé\n    Protecteurs de clés\xa0:\n        Password\n        Mot de passe numérique\n\n',
		'protectors': 'Chiffrement de lecteur BitLocker\xa0: outil de configuration version 10.0.19041\nCopyright (C) 2013 Microsoft Corporation. Tous droits réservés.\n\nVolume D: [Étiquette inconnue]\nTous les protecteurs de clés\n\n    Password :\n      ID : {SOMEPASS-WORD-ICAN-NNOT-REMEMBERWELL}\n\n    Mot de passe numérique :\n      ID : {SOMEPASS-GUID-ICAN-NNOT-REMEMBERWELL}\n\n'
	}
}

You may parse those or simply pretty print since print will not interpret special characters from a dict or multiple variables at once:

result = windows_tools.bitlocker.get_bitlocker_full_status()


result = get_bitlocker_full_status()
for drive in result:
    for designation, content in result[drive].items():
        print(designation, content)

Warning bitlocker needs to be run as admin. Running as non administrator will produce the following logs

Don't have permission to get bitlocker drive status for C:.
Don't have permission to get bitlocker drive protectors for C:.
Don't have permission to get bitlocker drive status for D:.
Don't have permission to get bitlocker drive protectors for D:.

Output shall be

{
    'C:': {
        'status': None,
        'protectors': None
    },
    'D:': {
        'status': None,
        'protectors': None
    }
}

You can check that you have administrator rights with windows_utils.users module

bitness

file_utils

impersonate

installed_software

logical_disk

misc

office

powershell

product_key

registry

securityprivilege

server

signtool

signtool is designed to make the windows executable signature as simple as possible.
Once the Windows SDK is installed on your machine, you can sign any executable with the following commands:

from windows_tools.signtool import SignTool
signer = SignTool()
signer.sign(r"c:\path\to\executable", bitness=64)

Note that current versions of signtool.exe that come with Windows 10 SDK automagically detect hardware EV certificate tokens like Safenet.

When using former certificate files in order to sign an executable, one should use the following syntax:

from windows_tools.signtool import SignTool
signer = SignTool(certificate=r"c:\path\to\cert.pfx", pkcs12_password="the_certificate_file_password")
signer.sign(r"c:\path\to\executable", bitness=64)

If the wrong certificate is used to sign, please open certmgr.msc, go to Private > Certificates and remove the certificate you don't want.

updates

Windows updates can be retrieved via a COM object that talks to Windows Update service, via WMI requests or via registry entries. All methods can return different results, so they are combined into one function.

Usage

import windows_tools.updates

result = windows_tools.updates.get_windows_updates(filter_duplicates=True, include_all_states=False)

result will contain a list of dict like

[{
        'kb': 'KB123456',
        'date': '2021-01-01 00:01:02',
        'title': 'Some update title',
        'description': 'Some update description',
        'supporturl': 'https://support.microsoft.com/someID',
        'operation': 'Installation'
        'result': 'Installed'
    }, {
        'kb': None,
        'date': '2021-01-01 00:01:02',
        'title': 'Windows 10 20H1 update',
        'description': 'Pretty big system update',
        'supporturl': 'https://support.microsoft.com/someID',
        'operation': 'Installation'
        'result': 'Installed'
    }
]

Using filter_duplicates will avoid returning multiple times the same KB from different sources. This setting is enabled by default.

The parameter include_all_states set to True will include all updates, even those who failed to install or are superseeded.

users

virtualization

windows_firewall

wmi_queries

windows_tools's People

Contributors

amirrossert avatar deajan avatar diogomcasado avatar sajjadhossanshimanto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

windows_tools's Issues

Installation Failed -Access Denied - Pipenv - Python 3.10

Installing windows_tools...
                            Error:                                     windows_tools!
Error text: Collecting windows_tools
  Using cached windows_tools-2.3.0-py3-none-any.whl (46 kB)
Collecting pywin32>=210
  Using cached pywin32-304-cp310-cp310-win_amd64.whl (12.1 MB)
Collecting psutil>=5.6.0
  Using cached psutil-5.9.3-cp310-cp310-win_amd64.whl (247 kB)
Collecting command-runner>=1.2.1
  Using cached command_runner-1.4.0-py3-none-any.whl (22 kB)
Collecting python-dateutil>=2.8.1
  Using cached python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
Collecting typing>=3.5.0
  Using cached typing-3.7.4.3-py3-none-any.whl
Collecting ofunctions.file-utils>=1.0.2
  Using cached ofunctions.file_utils-1.2.2-py3-none-any.whl (13 kB)
Collecting wmi>=1.4.9
  Using cached WMI-1.5.1-py2.py3-none-any.whl (28 kB)
Collecting ofunctions.random>=0.1.1
  Using cached ofunctions.random-0.2.0-py3-none-any.whl (6.9 kB)
Collecting six>=1.5
  Using cached six-1.16.0-py2.py3-none-any.whl (11 kB)
Installing collected packages: pywin32, wmi, typing, six, psutil, ofunctions.random, python-dateutil, command-runner, ofunctions.file-utils, windows_tools

ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\\Users\\.virtualenvs\\VaMkNO3m\\Lib\\site-packages\\pywin32_system32\\pythoncom310.dll'
Check the permissions.


Installation Failed

No Antivirus Detected

Hello, is your program working correctly? i just ran it and it returned this:

Example code for tests.windows_tools.antivirus, 2021020901
Antivirus software:

[]

Why is there no windows defender?

Product key

i wanted to use your imports but how do i grab the windows product key? You left no docs for it

windows_tools.updates.get_windows_updates not working

With the current project state and the setup described in #10:

using
python.exe -m pip install .\dist\windows_tools.updates-2.0.5-py3-none-any.whl
and the code snippet from the readme.md:

>>> import windows_tools.updates
>>> result = windows_tools.updates.get_windows_updates(filter_duplicates=True, include_all_states=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\windows_tools\updates\__init__.py", line 221, in get_windows_updates
    reg_update_list = get_windows_updates_reg(
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\windows_tools\updates\__init__.py", line 184, in get_windows_updates_reg
    "date": key["InstallLocation"]["last_modified"],
KeyError: 'last_modified'

To check if that isn't caused because the system never had updates installed, I installed and rebooted:
"2023-04 Update for Windows 11 Version 22H2 for x64-based Systems (KB4023057)".
Expected behavior would be that it shows this update in the output.

(Also the case in release v2.3.0, I believe to remember)

Exception when installing the registry package

This is what I got in pycharm:

Collecting windows-tools.registry==1.1.0
  Using cached windows_tools.registry-1.1.0-py3-none-any.whl.metadata (11 kB)
Collecting typing>=3.5.0 (from windows-tools.registry==1.1.0)
  Using cached typing-3.7.4.3.tar.gz (78 kB)
  Preparing metadata (setup.py): started
  Preparing metadata (setup.py): finished with status 'error'

  error: subprocess-exited-with-error
  
  python setup.py egg_info did not run successfully.
  exit code: 1
  
  [11 lines of output]
  Traceback (most recent call last):
    File "<string>", line 2, in <module>
    File "<pip-setuptools-caller>", line 14, in <module>
    File "C:\Users\ink\PycharmProjects\dummy\.venv\Lib\site-packages\setuptools\__init__.py", line 16, in <module>
      import setuptools.version
    File "C:\Users\ink\PycharmProjects\dummy\.venv\Lib\site-packages\setuptools\version.py", line 1, in <module>
      import pkg_resources
    File "C:\Users\ink\PycharmProjects\dummy\.venv\Lib\site-packages\pkg_resources\__init__.py", line 2191, in <module>
      register_finder(pkgutil.ImpImporter, find_on_path)
                      ^^^^^^^^^^^^^^^^^^^
  AttributeError: module 'pkgutil' has no attribute 'ImpImporter'. Did you mean: 'zipimporter'?
  [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

Encountered error while generating package metadata.

See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.


Cannot install the current project state from source

Installing the lastest release (v2.3.0) via pip worked flawlessly :)
But it being from Oct 11, 2021, it doesn't include a lot of the improvements.
So I tried (with user and admin rights respectively) to install the current project state using pip and setup.py.

system/software info

OS

OS Name: Microsoft Windows 11 Enterprise Evaluation
Version: 10.0.22621 Build 22621
using the VirtualBox dev vm version one can freely download from Microsoft:
https://developer.microsoft.com/en-us/windows/downloads/virtual-machines/

python

Python 3.10.10 (tags/v3.10.10:aad5f6a, Feb 7 2023, 17:20:36) [MSC v.1929 64 bit (AMD64)] on win32
pip 23.1.2 from C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\pip (python 3.10)

via pip in 3 different ways

download the currect master branch state and call on .zip file

pip install .\wintools.zip

inside the extracted zip

pip install .

download directly from github

python -m pip install git+https://github.com/netinvent/windows_tools.git@master

same result for all 3 ways:

File "C:\Users\User\AppData\Local\Temp\pip-build-env-8drvjp5x\overlay\Lib\site-packages\setuptools\build_meta.py", line 364, in _find_info_directory
          assert len(candidates) == 1, f"Multiple {suffix} directories found"
"AssertionError: Multiple .egg-info directories found"

(these directories are located in the root dir of the project)

research

regarding this problem, I found this:
pypa/pip#8201
TL;DR, seems like the blame is put on the setup.py file, creating more than on project

via .\setup.py

  1. python.exe .\setup.py clean

  2. python.exe .\setup.py build

  3. python.exe .\setup.py install

  4. and 2. run without error

  5. quits with
    "creating build\bdist.win-amd64\egg
    error: could not create 'build\bdist.win-amd64\egg': The system cannot find the path specified"

(creating the dir manually still results in the error/doesn't make the program continue after this step as well)

What I tried to research:

Reading pypa/pip#8201, I looked at the diff between the setup.py from the lastest release and the one from the current state, but couldn't determine a cause of the problem, I lack the knowledge/background.

If further information is needed, I'm more than welcome to help. :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.