Home > Software engineering >  New-PSSession using python only (no subprocess module)
New-PSSession using python only (no subprocess module)

Time:01-29

I wanted to know if it was possible to use New-PsSession and Invoke-Command to an exchange server using python only? I am doing testing and DON'T want to use the subprocess module but instead wanted to know if there are any python modules that can handle powershell commands to a remote server?

I usually use this to connect to the exchange server in powershell:

    $password = ConvertTo-SecureString "SOMEPASSWORD" -AsPlainText -Force
    $Cred = New-Object System.Management.Automation.PSCredential ("ENTEREMAILHERE", $password)
    $ses = New-PSSession -Name "ENTEREMAILHERE" -ConnectionUri https://exchange.intermedia.net/powershell -ConfigurationName Hosting.PowerShell -Credential $Cred -Authentication Basic

What I tried

I tried googling some modules and came across two different modules but they both didn't seem to work for me.

I tried using pypsrp but I don't think I was able to configure it correctly

from httpx import BasicAuth
from pypsrp.powershell import PowerShell, RunspacePool
from pypsrp.wsman import WSMan

wsman = WSMan("https://exchange.intermedia.net/powershell", username="enteremail",
              password="enterpassword",
              auth="basic")

with RunspacePool(wsman) as pool:
    ps = PowerShell(pool)
    ps.add_cmdlet("Get-PSDrive").add_parameter("Name", "C")
    ps.invoke()
    # we will print the first object returned back to us
    print(ps.output[0])

I get an error saying:

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: //exchange.intermedia.net/powershell:5986/wsman (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000002449336F610>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

I know the url works as I use it with powershell everyday.

CodePudding user response:

My experience with pysprp is mostly through Ansible since it powers the psrp connection plugin, but I did chat briefly with the library's creator who suggested using the host name and setting the path separately, like so:

WSMan("exchange.intermedia.net", port=443, path="powershell", ...)

I don't have an exchange server or other URI-based endpoint to test with unfortunately, but give this a try and see how it goes.

  •  Tags:  
  • Related