Codebase list pywinrm / e34ad45
Import upstream version 0.4.3 Kali Janitor 1 year, 4 months ago
23 changed file(s) with 167 addition(s) and 327 deletion(s). Raw diff Collapse all Expand all
+0
-4
.coveragerc less more
0 [run]
1 omit =
2 */tests*
3 */vendor*
+0
-31
.gitignore less more
0 # File artifacts which may by produced regular software on Windows, Mac OS X and Linux
1 Thumbs.db
2 .DS_Store
3 *.bak
4
5 # Unit test / coverage reports
6 .coverage
7 .cache
8
9 # JetBrains PyCharm configuration and working files
10 .idea
11
12 # Folder which should be used for temporary working files
13 /sandbox/
14
15 # Python virtual environment
16 /env/
17
18 # build outputs
19 /build/
20 /dist/
21 /pywinrm.egg-info/
22 /MANIFEST
23 *.py[co]
24 __pycache__
25 ~temp/
26 *~
27
28 /winrm/tests/config.json
29 .pytest_cache
30 venv
+0
-52
.travis.yml less more
0 # http://travis-ci.org/#!/diyan/pywinrm
1 # pyenv used instead of native Python support in Travis CI to:
2 # - Make build steps exactly the same on both Linux and Mac OS workers
3 # - Make possible to debug build steps on local workstation
4 # - Integrate new Python / PyPy releases earlier; pyenv does it with less lag than Travis
5 language: generic
6 cache:
7 directories:
8 - $HOME/.cache/pip
9 - $HOME/.cache/pyenv
10 matrix:
11 include:
12 # Define 'sudo: false' to run on container-based workers
13 - { os: linux, dist: xenial, sudo: false, env: UBUNTU=16.04 PYENV=2.7.16 }
14 - { os: linux, dist: xenial, sudo: false, env: UBUNTU=16.04 PYENV=3.5.7 }
15 - { os: linux, dist: xenial, sudo: false, env: UBUNTU=16.04 PYENV=3.6.8 }
16 - { os: linux, dist: xenial, sudo: false, env: UBUNTU=16.04 PYENV=3.7.3 }
17 - { os: linux, dist: xenial, sudo: false, env: UBUNTU=16.04 PYENV=3.8-dev }
18 - { os: linux, dist: xenial, sudo: false, env: UBUNTU=16.04 PYENV=pypy2.7-7.1.1 }
19
20 # pyenv won't build on current Mac versions without some extra conditional help, try to fix this later...
21 # - { os: osx, osx_image: xcode10.2, language: generic, env: OSX=10.14 PYENV=2.7.16 }
22 # - { os: osx, osx_image: xcode10.2, language: generic, env: OSX=10.14 PYENV=3.7.3 }
23
24 install:
25 # Always use latest pyenv but keep installed Python versions in cache
26 - rm -rf ~/.pyenv
27 - git clone https://github.com/pyenv/pyenv.git ~/.pyenv
28 - mkdir -p ~/.cache/pyenv/versions
29 - which pyenv
30 - printenv
31 - ln -s ~/.cache/pyenv/versions ~/.pyenv/versions
32 - export PATH="$HOME/.pyenv/shims:$HOME/.pyenv/bin:$PATH"
33 - export PYENV_ROOT="$HOME/.pyenv"
34 - pyenv --version
35 - pyenv install --skip-existing $PYENV
36 - pyenv global $PYENV
37 - pyenv rehash
38 - python --version
39 - pip --version
40 - pip install virtualenv
41 - python -m virtualenv ~/.venv
42 - source ~/.venv/bin/activate
43 - pip install coveralls
44 - pip install .[credssp]
45 - pip install .[kerberos]
46 - pip install -r requirements-test.txt
47 script:
48 - pytest -v --flake8 --cov=winrm --cov-report=term-missing winrm/tests/
49
50 after_success:
51 - coveralls
+0
-60
CHANGELOG.md less more
0 # Changelog
1
2 ### Version 0.4.1
3 - HOT FIX: Fixing an issue with `requests_kerbose` not imported correctly from the changes in `0.4.0`.
4
5 ### Version 0.4.0
6 - Ensure `server_cert_validation=ignore` supersedes ca_trust_path/env overrides
7 - Added deprecated warnings if CA trusts defined by environment variables are used.
8 - Set minimum version of requests-credssp to support Kerberos auth over CredSSP and other changes
9 - Added `proxy` support where it can be defined within the application, with the ability to specify the proxy within the application
10 - Fix for shell not setting all environment variables.
11 - Fix session clixml encoding on Python 3
12 - `Protocol.close_shell(shell_id)` will now close the session(and TCP connections) to the Windows machine. `close_session` option has been added in case of leaving the session alone.
13 - Add a function to send input to a running process.
14
15 ### Version 0.3.0
16 - Added support for message encryption over HTTP when using NTLM/Kerberos/CredSSP
17 - Added parameter to disable TLSv1.2 when using CredSSP for Server 2008 support
18 - Error detail from SOAP fault (if present) is now included with HTTP 500 errors
19 - Fixed CA path override (incl envvar)
20 - Fixed Kerberos service override
21 - Try harder to suppress urllib3 InsecureRequestWarnings on various OSs
22 - Fixed timeout values to parse correctly if passed as strings
23 - Various updates to CI/tests
24
25 ### Version 0.2.2
26 - Added support for CredSSP authenication (via requests-credssp)
27 - Improved README, see 'Valid transport options' section
28 - Run unit tests on Linux / Travis CI on Python 2.6-2.7, 3.3-3.6, PyPy2
29 - Run integration tests on Windows / AppVeyor on Python 2.7, 3.3-3.5
30 - Drop support for Python 3.0-3.2 due to lack of explicit unicode literal, see pep-0414
31 - Drop support for Python 2.6 on Windows
32 - Add support for Python 3.6-dev on Linux
33
34 ### Version 0.2.1
35 - Minor import bugfix for error "'module' object has no attribute 'util'" when using Kerberos delegation on older Python builds
36
37 ### Version 0.2.0
38 - Switched core HTTP transport from urllib2 to requests
39 - Added support for NTLM (via requests_ntlm)
40 - Added support for kerberos delegation (via requests_kerberos)
41 - Added support for explicit kerberos principals (in conjuction w/ pykerberos bugfix)
42 - Timeouts are more configurable
43
44 ### Version 0.1.1
45 - Force basic auth header to avoid additional HTTP request and reduce latency
46 - Python 2.7.9+. Allow server cert validation to be ignored using SSLContext.verify_mode
47 - Tests. Enable Python 3.4 on Travis CI
48
49 ### Version 0.0.3
50
51 - Use xmltodict instead of not supported xmlwitch
52 - Add certificate authentication support
53 - Setup PyPI classifiers
54 - Fix. Include UUID when sending request
55 - Fix. Python 2.6.6/CentOS. Use tuples instead of lists in setup.py
56 - Fix. Python 2.6. String formatting
57 - Handle unauthorized response and raise UnauthorizeError
58 - Convert different forms of short urls into full well-formed endpoint
59 - Add Session.run_ps() helper to execute PowerShell scripts
0 Metadata-Version: 2.1
1 Name: pywinrm
2 Version: 0.4.3
3 Summary: Python library for Windows Remote Management
4 Home-page: http://github.com/diyan/pywinrm/
5 Author: Alexey Diyan
6 Author-email: [email protected]
7 License: MIT license
8 Keywords: winrm,ws-man,devops,ws-management
9 Classifier: Development Status :: 4 - Beta
10 Classifier: Environment :: Console
11 Classifier: Intended Audience :: Developers
12 Classifier: Intended Audience :: System Administrators
13 Classifier: Natural Language :: English
14 Classifier: License :: OSI Approved :: MIT License
15 Classifier: Programming Language :: Python
16 Classifier: Programming Language :: Python :: 2
17 Classifier: Programming Language :: Python :: 2.7
18 Classifier: Programming Language :: Python :: 3
19 Classifier: Programming Language :: Python :: 3.6
20 Classifier: Programming Language :: Python :: 3.7
21 Classifier: Programming Language :: Python :: 3.8
22 Classifier: Programming Language :: Python :: 3.9
23 Classifier: Programming Language :: Python :: 3.10
24 Classifier: Programming Language :: Python :: Implementation :: PyPy
25 Classifier: Topic :: Software Development :: Libraries :: Python Modules
26 Classifier: Topic :: System :: Clustering
27 Classifier: Topic :: System :: Distributed Computing
28 Classifier: Topic :: System :: Systems Administration
29 Provides-Extra: credssp
30 Provides-Extra: kerberos
31 License-File: LICENSE
33 that can run Python.
44
55 [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/diyan/pywinrm/blob/master/LICENSE)
6 [![Travis Build](https://travis-ci.org/diyan/pywinrm.svg)](https://travis-ci.org/diyan/pywinrm)
7 [![AppVeyor Build](https://ci.appveyor.com/api/projects/status/github/diyan/pywinrm?svg=true)](https://ci.appveyor.com/project/diyan/pywinrm) [![Coverage](https://coveralls.io/repos/diyan/pywinrm/badge.svg)](https://coveralls.io/r/diyan/pywinrm)
6 [![Test workflow](https://github.com/diyan/pywinrm/workflows/Test%20pywinrm/badge.svg)](https://github.com/diyan/pywinrm/actions/workflows/ci.yml)
7 [![Coverage](https://coveralls.io/repos/diyan/pywinrm/badge.svg)](https://coveralls.io/r/diyan/pywinrm)
88 [![PyPI](https://img.shields.io/pypi/dm/pywinrm.svg)](https://pypi.python.org/pypi/pywinrm)
99
1010 WinRM allows you to perform various management tasks remotely. These include,
+0
-68
appveyor.yml less more
0 environment:
1 global:
2 # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the
3 # /E:ON and /V:ON options are not enabled in the batch script intepreter
4 # See: http://stackoverflow.com/a/13751649/163740
5 WITH_COMPILER: "cmd /E:ON /V:ON /C .\\scripts\\run_with_compiler.cmd"
6 matrix:
7 # https://www.appveyor.com/docs/installed-software/#python
8 # NOTE Python 2.6 for Windows is no longer supported by the Python core team
9 - PYTHON: Python27
10 - PYTHON: Python27-x64
11 - PYTHON: Python35
12 - PYTHON: Python35-x64
13 - PYTHON: Python36
14 - PYTHON: Python36-x64
15 - PYTHON: Python37
16 - PYTHON: Python37-x64
17
18 init:
19 - ps: |
20 $ErrorActionPreference = "Stop"
21 # Override default Python version/architecture
22 $env:Path="C:\$env:PYTHON;C:\$env:PYTHON\Scripts;$env:PATH"
23 # disable "Python 2.7 is going away soon" warnings
24 $env:PYTHONWARNINGS="ignore:DEPRECATION"
25 python -c "import platform; print('Python', platform.python_version(), platform.architecture()[0])"
26 # always install latest pip
27 $(curl -UseBasicParsing https://bootstrap.pypa.io/get-pip.py).Content | python
28 pip --version
29
30 install:
31 - ps: |
32 Enable-WSManCredSSP -Role Server -Force
33 Set-Item WSMan:\localhost\Service\Auth\Basic $true
34 Set-Item WSMan:\localhost\Service\Auth\CredSSP $true
35 Set-Item WSMan:\localhost\Service\AllowUnencrypted $true
36 Invoke-Expression $($env:WITH_COMPILER + " pip install cffi coveralls")
37 pip install .
38 pip install -r requirements-test.txt
39 pip install .[credssp]
40
41 build: off # Do not run MSBuild, build stuff at install step
42
43 build_script:
44 - echo build_script
45
46 test_script:
47 # configure winrm envvars for tests
48 - ps: |
49 $ErrorActionPreference = "Stop"
50 $env:WINRM_USERNAME=$($env:USERNAME)
51 $env:WINRM_PASSWORD=[Microsoft.Win32.Registry]::GetValue("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon", "DefaultPassword", '')
52 $env:WINRM_TRANSPORT="basic"
53 $env:WINRM_ENDPOINT="http://localhost:5985/wsman"
54
55 py.test -v --cov-report=term-missing --cov=.
56
57 # Run integration tests with NTLM to check message encryption
58 $env:WINRM_TRANSPORT="ntlm"
59 Set-Item WSMan:\localhost\Service\AllowUnencrypted $false
60 py.test -v winrm/tests/test_integration_protocol.py winrm/tests/test_integration_session.py
61
62 # Run integration tests with CredSSP to check message encryption
63 $env:WINRM_TRANSPORT="credssp"
64 py.test -v winrm/tests/test_integration_protocol.py winrm/tests/test_integration_session.py
65
66 after_test:
67 - echo after_test
0 Metadata-Version: 2.1
1 Name: pywinrm
2 Version: 0.4.3
3 Summary: Python library for Windows Remote Management
4 Home-page: http://github.com/diyan/pywinrm/
5 Author: Alexey Diyan
6 Author-email: [email protected]
7 License: MIT license
8 Keywords: winrm,ws-man,devops,ws-management
9 Classifier: Development Status :: 4 - Beta
10 Classifier: Environment :: Console
11 Classifier: Intended Audience :: Developers
12 Classifier: Intended Audience :: System Administrators
13 Classifier: Natural Language :: English
14 Classifier: License :: OSI Approved :: MIT License
15 Classifier: Programming Language :: Python
16 Classifier: Programming Language :: Python :: 2
17 Classifier: Programming Language :: Python :: 2.7
18 Classifier: Programming Language :: Python :: 3
19 Classifier: Programming Language :: Python :: 3.6
20 Classifier: Programming Language :: Python :: 3.7
21 Classifier: Programming Language :: Python :: 3.8
22 Classifier: Programming Language :: Python :: 3.9
23 Classifier: Programming Language :: Python :: 3.10
24 Classifier: Programming Language :: Python :: Implementation :: PyPy
25 Classifier: Topic :: Software Development :: Libraries :: Python Modules
26 Classifier: Topic :: System :: Clustering
27 Classifier: Topic :: System :: Distributed Computing
28 Classifier: Topic :: System :: Systems Administration
29 Provides-Extra: credssp
30 Provides-Extra: kerberos
31 License-File: LICENSE
0 LICENSE
1 MANIFEST.in
2 README.md
3 setup.cfg
4 setup.py
5 pywinrm.egg-info/PKG-INFO
6 pywinrm.egg-info/SOURCES.txt
7 pywinrm.egg-info/dependency_links.txt
8 pywinrm.egg-info/requires.txt
9 pywinrm.egg-info/top_level.txt
10 winrm/__init__.py
11 winrm/encryption.py
12 winrm/exceptions.py
13 winrm/protocol.py
14 winrm/transport.py
15 winrm/tests/__init__.py
16 winrm/tests/conftest.py
17 winrm/tests/sample_script.ps1
18 winrm/tests/test_cmd.py
19 winrm/tests/test_encryption.py
20 winrm/tests/test_integration_protocol.py
21 winrm/tests/test_integration_session.py
22 winrm/tests/test_nori_type_casting.py
23 winrm/tests/test_powershell.py
24 winrm/tests/test_protocol.py
25 winrm/tests/test_session.py
26 winrm/tests/test_transport.py
27 winrm/tests/test_wql.py
28 winrm/vendor/__init__.py
29 winrm/vendor/requests_kerberos/__init__.py
30 winrm/vendor/requests_kerberos/compat.py
31 winrm/vendor/requests_kerberos/exceptions.py
32 winrm/vendor/requests_kerberos/kerberos_.py
0 requests>=2.9.1
1 requests_ntlm>=1.1.0
2 six
3 xmltodict
4
5 [credssp]
6 requests-credssp>=1.0.0
7
8 [kerberos:sys_platform!="win32"]
9 pykerberos<2.0.0,>=1.2.1
10
11 [kerberos:sys_platform=="win32"]
12 winkerberos>=0.5.0
+0
-6
requirements-test.txt less more
0 # this assumes the base requirements have been satisfied via setup.py
1 # pin specific versions to keep things more stable over time; only pin sub-packages if necessary
2 pytest==4.4.2
3 pytest-cov==2.7.1
4 pytest-flake8==1.0.4
5 mock==3.0.5
+0
-47
scripts/run_with_compiler.cmd less more
0 :: To build extensions for 64 bit Python 3, we need to configure environment
1 :: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of:
2 :: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1)
3 ::
4 :: To build extensions for 64 bit Python 2, we need to configure environment
5 :: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of:
6 :: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0)
7 ::
8 :: 32 bit builds do not require specific environment configurations.
9 ::
10 :: Note: this script needs to be run with the /E:ON and /V:ON flags for the
11 :: cmd interpreter, at least for (SDK v7.0)
12 ::
13 :: More details at:
14 :: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows
15 :: http://stackoverflow.com/a/13751649/163740
16 ::
17 :: Author: Olivier Grisel
18 :: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
19 @ECHO OFF
20
21 SET COMMAND_TO_RUN=%*
22 SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows
23
24 SET MAJOR_PYTHON_VERSION="%PYTHON_VERSION:~0,1%"
25 IF %MAJOR_PYTHON_VERSION% == "2" (
26 SET WINDOWS_SDK_VERSION="v7.0"
27 ) ELSE IF %MAJOR_PYTHON_VERSION% == "3" (
28 SET WINDOWS_SDK_VERSION="v7.1"
29 ) ELSE (
30 ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%"
31 EXIT 1
32 )
33
34 IF "%PYTHON_ARCH%"=="64" (
35 ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture
36 SET DISTUTILS_USE_SDK=1
37 SET MSSdk=1
38 "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION%
39 "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release
40 ECHO Executing: %COMMAND_TO_RUN%
41 call %COMMAND_TO_RUN% || EXIT 1
42 ) ELSE (
43 ECHO Using default MSVC build environment for 32 bit architecture
44 ECHO Executing: %COMMAND_TO_RUN%
45 call %COMMAND_TO_RUN% || EXIT 1
46 )
88 flake8-ignore = tests/*.py E501
99 flake8-max-line-length = 160
1010
11 [egg_info]
12 tag_build =
13 tag_date = 0
14
00 from setuptools import setup, find_packages
11
2 __version__ = '0.4.1'
2 __version__ = '0.4.3'
33 project_name = 'pywinrm'
44
55 # PyPi supports only reStructuredText, so pandoc should be installed
2222 license='MIT license',
2323 packages=find_packages(),
2424 package_data={'winrm.tests': ['*.ps1']},
25 install_requires=['xmltodict', 'requests>=2.9.1', 'requests_ntlm>=0.3.0', 'six'],
25 install_requires=['xmltodict', 'requests>=2.9.1', 'requests_ntlm>=1.1.0', 'six'],
2626 extras_require={
2727 'credssp': ['requests-credssp>=1.0.0'],
2828 'kerberos:sys_platform=="win32"': ['winkerberos>=0.5.0'],
3939 'Programming Language :: Python :: 2',
4040 'Programming Language :: Python :: 2.7',
4141 'Programming Language :: Python :: 3',
42 'Programming Language :: Python :: 3.5',
4342 'Programming Language :: Python :: 3.6',
4443 'Programming Language :: Python :: 3.7',
4544 'Programming Language :: Python :: 3.8',
45 'Programming Language :: Python :: 3.9',
46 'Programming Language :: Python :: 3.10',
4647 'Programming Language :: Python :: Implementation :: PyPy',
4748 'Topic :: Software Development :: Libraries :: Python Modules',
4849 'Topic :: System :: Clustering',
11 import re
22 from base64 import b64encode
33 import xml.etree.ElementTree as ET
4 import warnings
45
56 from winrm.protocol import Protocol
67
7778 new_msg += s.text.replace("_x000D__x000A_", "\n")
7879 except Exception as e:
7980 # if any of the above fails, the msg was not true xml
80 # print a warning and return the orignal string
81 # TODO do not print, raise user defined error instead
82 print("Warning: there was a problem converting the Powershell"
83 " error message: %s" % (e))
81 # print a warning and return the original string
82 warnings.warn(
83 "There was a problem converting the Powershell error "
84 "message: %s" % (e))
8485 else:
8586 # if new_msg was populated, that's our error message
8687 # otherwise the original error message will be used
103104 @staticmethod
104105 def _build_url(target, transport):
105106 match = re.match(
106 '(?i)^((?P<scheme>http[s]?)://)?(?P<host>[0-9a-z-_.]+)(:(?P<port>\d+))?(?P<path>(/)?(wsman)?)?', target) # NOQA
107 r'(?i)^((?P<scheme>http[s]?)://)?(?P<host>[0-9a-z-_.]+)(:(?P<port>\d+))?(?P<path>(/)?(wsman)?)?', target) # NOQA
107108 scheme = match.group('scheme')
108109 if not scheme:
109110 # TODO do we have anything other than HTTP/HTTPS
9191 """
9292 Takes in the encrypted response from the server and decrypts it
9393
94 :param response: The response that needs to be decrytped
94 :param response: The response that needs to be decrypted
9595 :return: The unencrypted message from the server
9696 """
9797 content_type = response.headers['Content-Type']
66
77
88 class WinRMTransportError(Exception):
9 """WinRM errors specific to transport-level problems (unexpcted HTTP error codes, etc)"""
9 """WinRM errors specific to transport-level problems (unexpected HTTP error codes, etc)"""
1010
1111 @property
1212 def protocol(self):
5555 Any other value will be considered the CA trust path to use.
5656 @param string cert_pem: client authentication certificate file path in PEM format # NOQA
5757 @param string cert_key_pem: client authentication certificate key file path in PEM format # NOQA
58 @param string server_cert_validation: whether server certificate should be validated on Python versions that suppport it; one of 'validate' (default), 'ignore' #NOQA
58 @param string server_cert_validation: whether server certificate should be validated on Python versions that support it; one of 'validate' (default), 'ignore' #NOQA
5959 @param bool kerberos_delegation: if True, TGT is sent to target server to allow multiple hops # NOQA
6060 @param int read_timeout_sec: maximum seconds to wait before an HTTP connect/read times out (default 30). This value should be slightly higher than operation_timeout_sec, as the server can block *at least* that long. # NOQA
6161 @param int operation_timeout_sec: maximum allowed time in seconds for any single wsman HTTP operation (default 20). Note that operation timeouts while receiving output (the only wsman operation that should take any significant time, and where these timeouts are expected) will be silently retried indefinitely. # NOQA
435435 @param string command_id: The command id on the remote machine.
436436 See #run_command
437437 #@return [Hash] Returns a Hash with a key :exitcode and :data.
438 Data is an Array of Hashes where the cooresponding key
438 Data is an Array of Hashes where the corresponding key
439439 # is either :stdout or :stderr. The reason it is in an Array so so
440 we can get the output in the order it ocurrs on
440 we can get the output in the order it occurs on
441441 # the console.
442442 """
443443 stdout_buffer, stderr_buffer = [], []
0 import pytest
1
02 from winrm import Session
13
24
7779 expected = msg
7880 actual = s._clean_error_msg(msg)
7981 assert actual == expected
82
83
84 def test_decode_clixml_invalid_xml():
85 s = Session('windows-host.example.com', auth=('john.smith', 'secret'))
86 msg = b'#< CLIXML\r\n<in >dasf<?dsfij>'
87
88 with pytest.warns(UserWarning, match="There was a problem converting the Powershell error message"):
89 actual = s._clean_error_msg(msg)
90
91 assert actual == msg
00 from __future__ import unicode_literals
11 import sys
22 import os
3 import inspect
43 import requests
54 import requests.auth
65 import warnings
76
8 from distutils.util import strtobool
97 from winrm.exceptions import InvalidCredentialsError, WinRMError, WinRMTransportError
108 from winrm.encryption import Encryption
119
4543 pass
4644
4745 __all__ = ['Transport']
46
47
48 def strtobool(value):
49 value = value.lower()
50 if value in ('true', 't', 'yes', 'y', 'on', '1'):
51 return True
52
53 elif value in ('false', 'f', 'no', 'n', 'off', '0'):
54 return False
55
56 else:
57 raise ValueError("invalid truth value '%s'" % value)
4858
4959
5060 class UnsupportedAuthArgument(Warning):
216226
217227 if self.auth_method == 'kerberos':
218228 if not HAVE_KERBEROS:
219 raise WinRMError("requested auth method is kerberos, but requests_kerberos is not installed")
220
221 man_args = dict(
229 raise WinRMError("requested auth method is kerberos, but pykerberos is not installed")
230
231 session.auth = HTTPKerberosAuth(
222232 mutual_authentication=REQUIRED,
223 )
224 opt_args = dict(
225233 delegate=self.kerberos_delegation,
226234 force_preemptive=True,
227235 principal=self.username,
230238 service=self.service,
231239 send_cbt=self.send_cbt
232240 )
233 kerb_args = self._get_args(man_args, opt_args, HTTPKerberosAuth.__init__)
234 session.auth = HTTPKerberosAuth(**kerb_args)
235241 encryption_available = hasattr(session.auth, 'winrm_encryption_available') and session.auth.winrm_encryption_available
236242 elif self.auth_method in ['certificate', 'ssl']:
237243 if self.auth_method == 'ssl' and not self.cert_pem and not self.cert_key_pem:
245251 elif self.auth_method == 'ntlm':
246252 if not HAVE_NTLM:
247253 raise WinRMError("requested auth method is ntlm, but requests_ntlm is not installed")
248 man_args = dict(
254
255 session.auth = HttpNtlmAuth(
249256 username=self.username,
250 password=self.password
257 password=self.password,
258 send_cbt=self.send_cbt,
251259 )
252 opt_args = dict(
253 send_cbt=self.send_cbt
254 )
255 ntlm_args = self._get_args(man_args, opt_args, HttpNtlmAuth.__init__)
256 session.auth = HttpNtlmAuth(**ntlm_args)
257260 # check if requests_ntlm has the session_security attribute available for encryption
258261 encryption_available = hasattr(session.auth, 'session_security')
259262 # TODO: ssl is not exactly right here- should really be client_cert
263266 if not HAVE_CREDSSP:
264267 raise WinRMError("requests auth method is credssp, but requests-credssp is not installed")
265268
266 man_args = dict(
269 session.auth = HttpCredSSPAuth(
267270 username=self.username,
268 password=self.password
269 )
270 opt_args = dict(
271 password=self.password,
271272 disable_tlsv1_2=self.credssp_disable_tlsv1_2,
272273 auth_mechanism=self.credssp_auth_mechanism,
273274 minimum_version=self.credssp_minimum_version
274275 )
275 credssp_args = self._get_args(man_args, opt_args, HttpCredSSPAuth.__init__)
276 session.auth = HttpCredSSPAuth(**credssp_args)
277276 encryption_available = True
278277 else:
279278 raise WinRMError("unsupported auth method: %s" % self.auth_method)
343342 else:
344343 response_text = response.content
345344 return response_text
346
347 def _get_args(self, mandatory_args, optional_args, function):
348 argspec = set(inspect.getargspec(function).args)
349 function_args = dict()
350 for name, value in mandatory_args.items():
351 if name in argspec:
352 function_args[name] = value
353 else:
354 raise Exception("Function %s does not contain mandatory arg "
355 "%s, check installed version with pip list"
356 % (str(function), name))
357
358 for name, value in optional_args.items():
359 if name in argspec:
360 function_args[name] = value
361 else:
362 warnings.warn("Function %s does not contain optional arg %s, "
363 "check installed version with pip list"
364 % (str(function), name))
365
366 return function_args
9797 else:
9898 # There's no need to re-compile this EVERY time it is called. Compile
9999 # it once and you won't have the performance hit of the compilation.
100 regex = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)
100 regex = re.compile(r'(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)
101101 _negotiate_value.regex = regex
102102
103103 authreq = response.headers.get('www-authenticate', None)