# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['pypsrp', 'pypsrp.pwsh_scripts']

package_data = \
{'': ['*']}

install_requires = \
['cryptography', 'pyspnego<1.0.0', 'requests>=2.9.1,<3.0.0']

extras_require = \
{'credssp': ['requests-credssp>=1.0.0,<2.0.0'],
 'kerberos:sys_platform != "win32"': ['gssapi>=1.5.0,<2.0.0', 'krb5<1.0.0']}

setup_kwargs = {
    'name': 'pypsrp',
    'version': '0.7.0',
    'description': 'PowerShell Remoting Protocol and WinRM for Python',
    'long_description': '# pypsrp - Python PowerShell Remoting Protocol Client library\n\n[![Test workflow](https://github.com/jborean93/pypsrp/actions/workflows/ci.yml/badge.svg)](https://github.com/jborean93/pypsrp/actions/workflows/ci.yml)\n[![codecov](https://codecov.io/gh/jborean93/pypsrp/branch/master/graph/badge.svg)](https://codecov.io/gh/jborean93/pypsrp)\n[![PyPI version](https://badge.fury.io/py/pypsrp.svg)](https://badge.fury.io/py/pypsrp)\n\npypsrp is a Python client for the PowerShell Remoting Protocol (PSRP) and\nWindows Remote Management (WinRM) service. It allows your to execute commands\non a remote Windows host from any machine that can run Python.\n\nThis library exposes 4 different types of APIs;\n\n* A simple client API that can copy files to and from the remote Windows host as well as execute processes and PowerShell scripts\n* A WSMan interface to execute various WSMan calls like `Send`, `Create`, `Connect`, `Disconnect`, etc\n* A Windows Remote Shell (WinRS) layer that executes cmd commands and executables using the base WinRM protocol\n* A PowerShell Remoting Protocol (PSRP) layer allows you to create remote Runspace Pools and PowerShell pipelines\n\nAt a basic level, you can use this library to;\n\n* Execute a cmd command\n* Run another executable\n* Execute PowerShell scripts\n* Copy a file from the localhost to the remote Windows host\n* Fetch a file from the remote Windows host to the localhost\n* Create a Runspace Pool that contains one or multiple PowerShell pipelines and execute them asynchronously\n* Support for a reference host base implementation of PSRP for interactive scripts\n\nCurrently this library only supports the WSMan transport method but is designed\nto support SSH at some point in the future (PR\'s are welcome). By default it\nsupports the following authentication methods with WSMan;\n\n* Basic\n* Certificate\n* NTLM\n\nIt also supports `Negotiate/Kerberos`, and `CredSSP` but require extra\nlibraries to be isntalled.\n\n\n## Requirements\n\nSee `How to Install` for more details\n\n* CPython 3.6+\n* [cryptography](https://github.com/pyca/cryptography)\n* [pyspnego](https://github.com/jborean93/pyspnego)\n* [requests](https://github.com/requests/requests)\n\n### Optional Requirements\n\nThe following Python libraries can be installed to add extra features that do\nnot come with the base package\n\n* [python-gssapi](https://github.com/pythongssapi/python-gssapi) for Kerberos authentication on Linux\n* [pykrb5](https://github.com/jborean93/pykrb5) for Kerberos authentication on Linux\n* [requests-credssp](https://github.com/jborean93/requests-credssp) for CredSSP authentication\n\n\n## How to Install\n\nTo install pypsrp with all basic features, run\n\n```\npip install pypsrp\n```\n\n### Kerberos Authentication\n\nWhile pypsrp supports Kerberos authentication, it isn\'t included by default for\nLinux hosts due to it\'s reliance on system packages to be present.\n\nTo install these packages, run the below\n\nFor Debian/Ubuntu\n\n```\n# For Python 2\napt-get install gcc python-dev libkrb5-dev\n\n# For Python 3\napt-get install gcc python3-dev libkrb5-dev\n\n# To add NTLM to the GSSAPI SPNEGO auth run\napt-get install gss-ntlmssp\n```\n\nFor RHEL/Centos\n\n```\nyum install gcc python-devel krb5-devel\n\n# To add NTLM to the GSSAPI SPNEGO auth run\nyum install gssntlmssp\n```\n\nFor Fedora\n\n```\ndnf install gcc python-devel krb5-devel\n\n# To add NTLM to the GSSAPI SPNEGO auth run\ndnf install gssntlmssp\n```\n\nFor Arch Linux\n\n```\npacman -S gcc krb5\n```\n\nOnce installed you can install the Python packages with\n\n```\npip install pypsrp[kerberos]\n```\n\nKerberos also needs to be configured to talk to the domain but that is outside\nthe scope of this page.\n\n### CredSSP Authentication\n\nLike Kerberos auth, CredSSP is supported but isn\'t included by default. To add\nsupport for CredSSP auth try to run the following\n\n```\npip install pypsrp[credssp]\n```\n\nIf that fails you may need to update pip and setuptools to a newer version\n`pip install -U pip setuptools`, otherwise the following system package may be\nrequired;\n\n```\n# For Debian/Ubuntu\napt-get install gcc python-dev\n\n# For RHEL/Centos\nyum install gcc python-devel\n\n# For Fedora\ndnf install gcc python-devel\n```\n\n\n## How to Use\n\nThere are 3 main components that are in use within this library;\n\n* `Transport`: Handles the raw transport of messages to and from the server\n* `Shell`: Handles the WSMV or PSRP protocol details used to create the remote shell that processes are run on, uses `Connection` to send the details\n* `Process`: Runs the process or script within a shell\n\n### Connection\n\nCurrently only the connection that is supported is the WSMan protocol over HTTP\nthrough `pypsrp.wsman.WSMan` and offers mostly all the same features in the\nWSMV spec including;\n\n* Basic, Certificate, Negotiate, Kerberos, and CredSSP authentication\n* TLS encryption\n* Message encryption with Negotiate, Kerberos, and CredSSP authentication\n* Definable proxy\n\nThese are the options that can be used to setup `WSMan`;\n\n* `server`: The hostname or IP address of the host to connect to\n* `max_envelope_size`: The maximum envelope size, in bytes, that can be sent to the server, default is `153600`\n* `operation_timeout`: The operation timeout, in seconds, of each WSMan operation, default is `20`. This should always be lower than `read_timeout`.\n* `port`: The port to connect to, default is `5986` if `ssl=True` else `5985`\n* `username`: The username to connect with, required for all auths except `certificate` and optionally required for `negotiate/kerberos`\n* `password`: The password for `username`. Due to a bug on MacOS/Heimdal GSSAPI implementations, this will persist in the user\'s ccache when using Negotiate or Kerberos authentication, run `kdestroy` manually to remove this\n* `ssl`: Whether to connect over `https` or `https`, default is `True`\n* `path`: The WinRM path to connect to, default is `wsman`\n* `auth`: The authentication protocol to use, default is `negotiate`, choices are `basic`, `certificate`, `negotiate`, `ntlm`, `kerberos`, `credssp`\n* `cert_validation`: Whether to validate the server\'s SSL certificate, default is `True`. Can be `False` to not validate or a path to a PEM file of trusted certificates\n* `connection_timeout`: The timeout for creating a HTTP connection, default is `30`\n* `read_timeout`: The timeout for receiving a response from the server after a request has been made, default is `30`\n* `encryption`: Controls the encryption settings, default is `auto`, choices are `auto`, `always`, `never`. Set to `always` to always run message encryption even over HTTPS, `never` to never use message encryption even over HTTP\n* `proxy`: The proxy URL used to connect to the remote host\n* `no_proxy`: Whether to ignore any environment proxy variable and connect directly to the host, default is `False`\n* `locale`: The `wsmv:Locale` value to set on each WSMan request. This specifies the language in which the cleint wants response text to be translated, default is `en-US`\n* `data_locale`: The `wsmv:DataLocale` value to set on each WSMan request. This specifies the format in which numerical data is presented in the response text, default is the value of `locale`\n* `reconnection_retries`: Number of retries on a connection problem, default is `0`\n* `reconnection_backoff`: Number of seconds to backoff in between reconnection attempts (first sleeps X, then sleeps 2*X, 4*X, 8*X, ...), default is `2.0`\n* `certificate_key_pem`: The path to the certificate key used in `certificate` authentication\n* `certificate_pem`: The path to the certificate used in `certificate` authentication\n* `credssp_auth_mechanism`: The sub-auth mechanism used in CredSSP, default is `auto`, choices are `auto`, `ntlm`, or `kerberos`\n* `credssp_disable_tlsv1_2`: Whether to used CredSSP auth over the insecure TLSv1.0, default is `False`\n* `credssp_minimum_version`: The minimum CredSSP server version that the client will connect to, default is `2`\n* `negotiate_delegate`: Whether to negotiate the credential to the host, default is `False`. This is only valid if `negotiate` auth negotiated Kerberos or `kerberos` was explicitly set\n* `negotiate_hostname_override`: The hostname used to calculate the host SPN when authenticating the host with Kerberos auth. This is only valid if `negotiate` auth negotiated Kerberos or `kerberos` was explicitly set\n* `negotiate_send_cbt`: Whether to binding the channel binding token (HTTPS only) to the auth or ignore, default is `True`\n* `negotiate_service`: Override the service part of the calculated SPN used when authenticating the server, default is `WSMAN`. This is only valid if `negotiate` auth negotiated Kerberos or `kerberos` was explicitly set\n\nWhen running over HTTP, this library will enforce encryption by default but if\nthat is not supported (Basic auth) or isn\'t available on the host then either\nuse HTTPS or disable encryption with `encryption="never"`.\n\nThere are plans to add support for SSH as a connection but this still needs to\nbe implemented. SSH will work on hosts that are running PowerShell Core but\nnot the standard PowerShell.\n\n### Shell\n\nThere are two shells that can be used in this library, `pypsrp.shell.WinRS` and\n`pypsrp.powershell.RunspacePool`.\n\n`WinRS` is a cmd shell that can be used to issue cmd commands, including but\nnot limited to other executables. Here are the options that can be used to\nconfigure a `WinRS` shell;\n\n* `wsman`: WinRS only works over WSMan, so this is the `pypsrp.wsman.WSMan` object to run the commands over\n* `resource_uri`: The resource uri of the shell, defaults to `http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd`\n* `id`: The ID if the shell, this should be kept as `None` as it is created dynamically by the server\n* `input_streams`: The input stream(s) of the shell, default is `stdin`\n* `output_streams`: The output stream(s) of the shell, default is `stdout, stderr`\n* `codepage`: The codepage of the shell, default is the default of the host\n* `environment`: A dictionary of environment key/values to set for the remote shell\n* `idle_time_out`: THe idle timeout in seconds of the shell\n* `lifetime`: The total lifetime of the shell\n* `name`: The name (description only) of the shell\n* `no_profile`: Whether to create the shell with the user profile loaded or not\n* `working_directory`: The default working directory of the created shell\n\n`RunspacePool` is a shell used by the PSRP protocol, it is designed to be a\nclose implementation of the .NET\n[System.Management.Automation.Runspaces.RunspacePool](https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.runspaces.runspacepool?view=powershellsdk-1.1.0)\nclass. The methods and properties are similar and can mostly do the same thing.\nHere are the options that can be used to configure a `RunspacePool` shell;\n\n* `connection`: The connection object used by the RunspacePool to send commands to the remote server, currently only supports `WSMan`\n* `apartment_state`: The int value of `pypsrp.complex_objects.ApartmentState` for the remote thread, default is `UNKNOWN`\n* `thread_options`: The int value of `pypsrp.complex_objects.ThreadOptions` that specifies the type of thread to create, default is `DEFAULT`\n* `host`: The local host info implementation, default is no host\n* `configuration_name`: The configuration name to connect to, default is `Microsoft.PowerShell` and can be used to specify the Just Enough Administration (JEA) to connect to\n* `min_runspaces`: The minimuum number of runspaces that a pool can hold, default is 1\n* `max_runspaces`: The maximum number of runspaces that a pool can hold. Each PowerShell pipeline is run in a single Runspace, default is 1\n* `session_key_timeout_ms`: The maximum time to wait for a session key transfer from the server\n\n### Process\n\nThere are two process objects that can be used, `pypsrp.shell.Process` for the\n`WinRS` shell and `pypsrp.powershell.PowerShell` for the `RunspacePool` shell.\nThese objects are ultimately used to execute commands, processes, or scripts on\nthe remote host.\n\n`Process` is used with the `WinRS` shell to execute a cmd command or another\nexecutable. The following options are used to configure the `Process` object;\n\n* `shell`: The `WinRS` shell the process is run over\n* `executable`: The executable or command to run\n* `arguments`: A list of arguments to the executable or command, default is no arguments\n* `id`: The ID of the created command, if not specified then this is dynamically created\n* `no_shell`: Whether to create a command in the cmd shell or bypass it, default is `False`. If `True` then the executable must be the full path to the exe. This only works on older OS\' before 2012 R2 (not including)\n\nTo execute the process, call `.invoke()`, the `stdout`, `stderr`, and `rc`\nproperties contain the output of the command once complete.\n\n`PowerShell` is used by the PSRP protocol, it is designed to be a close\nimplementation of the\n[System.Management.Automation.PowerShell](https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?view=powershellsdk-1.1.0)\nclass. The methods and properties are similar and can mostly do the same thing.\nHere are the options that can be used to configure a `PowerShell` process;\n\n* `runspace_pool`: The `RunspacePool` object to run the `PowerShell` process on\n\nTo execute the process, call `.invoke()`, the `output`, `had_erros`, and\n`streams` contains the execution status and output information of the process.\nBefore invoke can be called, cmdlets or scripts must be added. These can be\ndone with the following methods;\n\n* `add_script`: Add a raw PowerShell script to the pending commands\n* `add_cmdlet`: Add a cmdlet to the pending commands\n* `add_parameters`: Add a dictionary of key/value parameters to the last added command\n* `add_argument`: Add a value argument to the last added command\n* `add_statement`: Set the last command/script to be the end of that pipeline so the next command/script is like a newline\n\nSee the examples below for more details.\n\n### Examples\n\nHow to use the high level client API\n\n```python\nfrom pypsrp.client import Client\n\n# this takes in the same kwargs as the WSMan object\nwith Client("server", username="user", password="password") as client:\n\n    # execute a cmd command\n    stdout, stderr, rc = client.execute_cmd("dir")\n\n    stdout, stderr, rc = client.execute_cmd("powershell.exe gci $pwd")\n    sanitised_stderr = client.sanitise_clixml(stderr)\n\n    # execute a PowerShell script\n    output, streams, had_errors = client.execute_ps(\'\'\'$path = "%s"\nif (Test-Path -Path $path) {\n    Remove-Item -Path $path -Force -Recurse\n}\nNew-Item -Path $path -ItemType Directory\'\'\' % path)\n    output, streams, had_errors = client.execute_ps("New-Item -Path C:\\\\temp\\\\folder -ItemType Directory")\n\n    # copy a file from the local host to the remote host\n    client.copy("~/file.txt", "C:\\\\temp\\\\file.txt")\n\n    # fetch a file from the remote host to the local host\n    client.fetch("C:\\\\temp\\\\file.txt", "~/file.txt")\n```\n\nHow to use WinRS/Process to execute a command\n\n\n```python\nfrom pypsrp.shell import Process, SignalCode, WinRS\nfrom pypsrp.wsman import WSMan\n\n# creates a http connection with no encryption and basic auth\nwsman = WSMan("server", ssl=False, auth="basic", encryption="never",\n              username="vagrant", password="vagrant")\n\nwith wsman, WinRS(wsman) as shell:\n    process = Process(shell, "dir")\n    process.invoke()\n    process.signal(SignalCode.CTRL_C)\n\n    # execute a process with arguments in the background\n    process = Process(shell, "powershell", ["gci", "$pwd"])\n    process.begin_invoke()  # start the invocation and return immediately\n    process.poll_invoke()  # update the output stream\n    process.end_invoke()  # finally wait until the process is finished\n    process.signal(SignalCode.CTRL_C)\n```\n\nHow to use RunspacePool/PowerShell to execute a PowerShell script/command\n\n```python\nfrom pypsrp.powershell import PowerShell, RunspacePool\nfrom pypsrp.wsman import WSMan\n\n# creates a https connection with explicit kerberos auth and implicit credentials\nwsman = WSMan("server", auth="kerberos", cert_validation=False))\n\nwith wsman, RunspacePool(wsman) as pool:\n    # execute \'Get-Process | Select-Object Name\'\n    ps = PowerShell(pool)\n    ps.add_cmdlet("Get-Process").add_cmdlet("Select-Object").add_argument("Name")\n    output = ps.invoke()\n\n    # execute \'Get-Process | Select-Object -Property Name\'\n    ps.add_cmdlet("Get-Process").add_cmdlet("Select-Object")\n    ps.add_parameter("Property", "Name")\n    ps.begin_invoke()  # execute process in the background\n    ps.poll_invoke()  # update the output streams\n    ps.end_invoke()  # wait until the process is finished\n\n    # execute \'Get-Process | Select-Object -Property Name; Get-Service audiosrv\'\n    ps.add_cmdlet("Get-Process").add_cmdlet("Select-Object").add_parameter("Property", "Name")\n    ps.add_statement()\n    ps.add_cmdlet("Get-Service").add_argument("audiosrc")\n    ps.invoke()\n\n    # execute a PowerShell script with input being sent\n    script = \'\'\'begin {\n    $DebugPreference = "Continue"\n    Write-Debug -Message "begin"\n} process {\n    Write-Output -InputObject $input\n} end {\n    Write-Debug -Message "end"\n}\n\'\'\'\n    ps.add_script(script)\n    ps.invoke(["string", 1])\n    print(ps.output)\n    print(ps.streams.debug)\n```\n\n\n## Logging\n\nThis library takes advantage of the Python logging configuration and messages\nare logged to the `pypsrp` named logger as well as `pypsrp.*` where `*` is each\nPython script in the `pypsrp` directory.\n\nAn easy way to turn on logging for the entire library is to create the\nfollowing JSON file and run your script with\n`PYPSRP_LOG_CFG=log.json python script.py` (this does not work with Python\n2.6).\n\n```json\n{\n    "version": 1,\n    "disable_existing_loggers": false,\n    "formatters": {\n        "simple": {\n            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"\n        }\n    },\n\n    "handlers": {\n        "console": {\n            "class": "logging.StreamHandler",\n            "level": "DEBUG",\n            "formatter": "simple",\n            "stream": "ext://sys.stdout"\n        }\n    },\n\n    "loggers": {\n        "pypsrp": {\n            "level": "DEBUG",\n            "handlers": ["console"],\n            "propagate": "no"\n        }\n    }\n}\n```\n\nYou can adjust the log level by changing the level value in `logger` to `INFO`.\n\n_Note: `DEBUG` contains a lot of information and will output all the messages\nsent to and from the client. This can have the side effect of leaking sensitive\ninformation and should only be used for debugging purposes._\n\n\n## Testing\n\nAny changes are more than welcome in pull request form, you can run the current\ntest suite with tox like so;\n\n```\n# make sure tox is installed\npip install tox\n\n# run the tox suite\ntox\n\n# or run the test manually for the current Python environment\npy.test -v --pep8 --cov pypsrp --cov-report term-missing\n```\n\nA lot of the tests either simulate a remote Windows host but you can also run a\nlot of them against a real Windows host. To do this, set the following\nenvironment variables before running the tests;\n\n* `PYPSRP_SERVER`: The hostname or IP of the remote host\n* `PYPSRP_USERNAME`: The username to connect with\n* `PYPSRP_PASSWORD`: The password to connect with\n* `PYPSRR_PORT`: The port to connect with (default: `5986`)\n* `PYPSRP_AUTH`: The authentication protocol to auth with (default: `negotiate`)\n\nThere are further integration tests that require a specific host setup to run\ncorrectly. You can use `Vagrant` to set this host up. This is done by running\nthe following commands;\n\n```\n# download the Vagrant box and start it up based on the Vagrantfile\nvagrant up\n\n# once the above script is complete run the following\nvagrant ssh  # password is vagrant\n\npowershell.exe\nRegister-PSSessionConfiguration -Path "C:\\Users\\vagrant\\Documents\\JEARoleSettings.pssc" -Name JEARole -Force\n\n$sec_pass = ConvertTo-SecureString -String "vagrant" -AsPlainText -Force\n$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "vagrant", $sec_pass\n$thumbprint = (Get-ChildItem -Path Cert:\\LocalMachine\\TrustedPeople)[0].Thumbprint\n\nNew-Item -Path WSMan:\\localhost\\ClientCertificate `\n    -Subject "vagrant@localhost" `\n    -URI * `\n    -Issuer $thumbprint `\n    -Credential $credential `\n    -Force\n\n\n# exit the remote PowerShell session\nexit\n\n# exist the SSH session\nexit\n```\n\nOnce complete, set the following environment variables to run the integration\ntests;\n\n* `PYPSRP_RUN_INTEGRATION`: To any value\n* `PYPSRP_SERVER`: Set to `127.0.0.1`\n* `PYPSRP_USERNAME`: Set to `vagrant`\n* `PYPSRP_PASSWORD`: Set to `vagrant`\n* `PYPSRP_HTTP_PORT`: Set to `55985`\n* `PYPSRP_HTTPS_PORT`: Set to `55986`\n* `PYPSRP_CERT_DIR`: Set to the full path of the project directory\n\nFrom here you can run the normal test suite and it will run all the integration\ntests.\n\n\n## Backlog\n\n* Look at implementing the following transport options\n    * Named pipes\n    * SSH\n* Update CI to use named pipes for integration tests\n* Add Ansible playbook for better integration tests\n* Improved serialization between Python and .NET objects\n* Live interactive console for PSRP\n',
    'author': 'Jordan Borean',
    'author_email': 'jborean93@gmail.com',
    'maintainer': None,
    'maintainer_email': None,
    'url': 'https://github.com/jborean93/pypsrp',
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'extras_require': extras_require,
    'python_requires': '>=3.6,<4.0',
}


setup(**setup_kwargs)
