New-PSSession using python only (no subprocess module) - python

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.
Edit: After talking with #briantist I tried:
wsman = WSMan("exchange.intermedia.net", username="EMAILHERE",
password="PASSWORHERE",
auth="basic",
port=443,
path="powershell")
and it seemed like it was going to work but then it failed with:
Code: 2150858811, Machine: exchange.intermedia.net, Reason: The WS-Management service cannot process the request. The resource URI (http://schemas.microsoft.com/powershell/Microsoft.PowerShell) was not found in the WS-Management catalog.
I assume that is because the https:// was not there so I tried with the https:// and it gave the same error as earlier saying:
requests.exceptions.ConnectionError:
HTTPSConnectionPool(host='https', port=443): Max retries exceeded
with url: //exchange.intermedia.net:443/powershell (Caused by
NewConnectionError('<urllib3.connection.HTTPSConnection object at
0x0000020759047AC0>: Failed to establish a new connection: [Errno
11001] getaddrinfo failed'))

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", ...)
Update: OP confirmed it working with this code:
from pypsrp.powershell import PowerShell, RunspacePool
from pypsrp.wsman import WSMan
wsman = WSMan("exchange.intermedia.net", username="ENTEREMAIL",
password="ENTERPASSWORD",
auth="basic", port=443, path="powershell")
with RunspacePool(wsman, configuration_name="Hosting.PowerShell") as pool:
print("hello")
Key points:
URI-based endpoints need to be split into hostname and path with pypsrp
If using a non-default configuration name, be sure to pass that along to the RunspacePool object as well

Related

Why do I get a connection error using qBittorrentAPI?

I'm trying to run some code from this website but I don't understand why I get this error:
qbittorrentapi.exceptions.APIConnectionError: Failed to connect to qBittorrent. Connection Error: ConnectionError(MaxRetryError("HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /api/v2/auth/login (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001FA519F5840>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))"))
The code in question:
import qbittorrentapi
# instantiate a Client using the appropriate WebUI configuration
qbt_client = qbittorrentapi.Client(
host='localhost',
port=8080,
username='admin',
password='adminadmin',
)
# the Client will automatically acquire/maintain a logged-in state
# in line with any request. therefore, this is not strictly necessary;
# however, you may want to test the provided login credentials.
try:
qbt_client.auth_log_in()
except qbittorrentapi.LoginFailed as e:
print(e)
# display qBittorrent info
print(f'qBittorrent: {qbt_client.app.version}')
print(f'qBittorrent Web API: {qbt_client.app.web_api_version}')
for k,v in qbt_client.app.build_info.items(): print(f'{k}: {v}')
# retrieve and show all torrents
for torrent in qbt_client.torrents_info():
print(f'{torrent.hash[-6:]}: {torrent.name} ({torrent.state})')
# pause all torrents
qbt_client.torrents.pause.all()
I'd really appreciate some help with this, thanks ahead :)

Why is my simple firebase program trying to connect to the auth emulator?

im getting the following error when running the simple python program:
firebase_admin.exceptions.UnavailableError: Failed to establish a connection: HTTPConnectionPool(host='localhost', port=9099): Max retries exceeded with url: /identitytoolkit.googleapis.com/v1/projects/fir-api-test2-72710/accounts:lookup (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001B28FC6C4F0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
The python program I'm running that creates this error is very basic:
import json
# Firestore database
db = None
if __name__ == "__main__":
# FIRESTORE INITIALISATION
load_dotenv()
firebase_permisisions = json.loads(os.getenv('FIREBASE_CREDS'))
cred = credentials.Certificate(firebase_permisisions)
firebase_app = firebase_admin.initialize_app(cred)
db = firestore.client()
print('getting user')
# fails here
user = auth.get_user('1234')
print(user)
If my colleague runs this program on his machine it works.
Not sure why the connection pool is looking for the locahost? If I run the auth emulator on my machine it will work but picks up emulator users.
Ive test straight after rebooting my machine, and reinstall firebase admin but issue persists.
I do use the firebase emulator for other firebase projects
If anyone has any ideas that would be great,
Richard
Worked out that for some reason i had 'FIREBASE_AUTH_EMULATOR_HOST' set as environment variable. Now it works as expected

Django can't make external connections with requests or urllib2 on development server

Everytime I make an external request (including to google.com) I get this response:
HTTPConnectionPool(host='EXTERNALHOSTSITE', port=8080): Max retries exceeded with url: EXTERNALHOSTPARAMS (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x105d8d6d0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))
It does seem that your server cannot resolve the hostname into IP, this is probably not Django nor Python problem but your server network setup issue.
Try to reach the same URL with ping tool / wget/curl or troubleshoot DNS with nslookup.

Python: How can I use urllib or requests modules from a corporate domain (firewall, proxy, cntlm etc)

I am trying to do the following:
from urllib.request import urlopen
data = urlopen("https://www.duolingo.com/users/SaifullahS6").read()
I get the following error:
URLError: <urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
Similarly, when I try this:
import requests
session = requests.Session()
data = {"login": "SaifullahS6", "password": "mypassword"}
req = requests.Request('POST', "https://www.duolingo.com/login", data=data,
cookies=session.cookies)
prepped=req.prepare()
returned = session.send(prepped)
I get:
ConnectionError: HTTPSConnectionPool(host='www.duolingo.com', port=443): Max retries exceeded with url: /login (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000000000E6948D0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',))
I am not sure how to give details of my internet connection.
I'm at work and I know we have a corporate proxy.
We have Windows Firewall turned on, but i have checked that python and pythonw are ticked in the "Domain" column of the control panel for allowing a program through the firewall.
When I ping google.co.uk from a command shell, all four requests time out, but I can access it from a browser.
In the Internet Options control panel, I click on the Connections tab and then LAN settings, and I have "Automatically detect settings" turned on, and also "Use a proxy server for your LAN", "Address" is "localhost" and "Port" is 3128. This is cntlm. I set it up once to do download python packages, and it appears to still be active because I have just managed to update one of my packages.
I don't even need a direct answer to my question; at this point I'll just settle for some clarity on what is actually going on behind the scenes. Any help much appreciated!
For the first case above (urllib module), I solved it by inserting the following lines before the data = urlopen(...).read() line:
proxies = { "http": "localhost:3128",
"https": "localhost:3128"}
proxy = urllib.request.ProxyHandler(proxies)
opener = urllib.request.build_opener(proxy)
urllib.request.install_opener(opener)
For the second case (requests module), everything was the same except the last line:
proxies = { "http": "localhost:3128",
"https": "localhost:3128"}
returned = session.send(prepped, proxies=proxies)
Hope this note helps others who come across this page.

Calling self-made Python API with another Python program

I'm running a local server with my Flask Python program. I am able to GET request the server with curl:
curl http://localhost:5000/ -d "input_data=something" -X GET
and everything goes well.
However, if I try to call it from another Python program this way:
import requests
r=requests.get('http://localhost:5000', json={"input_data": "something"})
I get an error:
HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7fe3b510a310>: Failed to establish a new connection: [Errno 111] Connection refused',))
What is the problem here?
Besides, is there a way to insert the server program into a standard Linux pipeline? I mean something along this logic (of course, I know that this concretely doesn't work):
cat "something" | http://localhost:5000 > output

Categories