pysimplesoap Cannot determine service in WSDL: SOAP version: soap11 - python

I created a simple web service and consumed it with pysimplesoap. Then I added ssl to the service(self signed) and tried to do the same but I am getting the error:
RuntimeError: Cannot determine service in WSDL: SOAP version: soap11
This is my code:
from pysimplesoap.client import SoapClient
import base64
import ssl
base64string = base64.encodestring('%s:%s' % ('username', 'password')).replace('\n', '')
ssl._create_default_https_context = ssl._create_unverified_context
authenticationHeader = {
"Authorization" : "Basic %s" % base64string,
}
client = SoapClient(wsdl="https://10.0.120.138/service.svc?wsdl",trace=True,http_headers=authenticationHeader)
response = client.method("param")
print response
Does anyone know why I am getting the error? I have a feeling I need to configure something..

This is not really an answer for the problem above but it is a solution..
I switched to zeep library and everything works now.

Related

Fhir Epic Sandbox : Using a JWT to Obtain an Access Token for a Backend Service

I'm trying to use the sandbox from https://fhir.epic.com/ for Backend Services.
I am following this tutorial : https://fhir.epic.com/Documentation?docId=oauth2&section=BackendOAuth2Guide :
I already register a new app,
created a JWT (using SSL keys)
tested the JWT on https://jwt.io/ : works fine!
But I cannot POST the JWT to the endpoint to obtain the access token. I should send a POST request to this URL: https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token.
I'm using python and this is my code so far:
import json
import requests
from datetime import datetime, timedelta, timezone
from requests.structures import CaseInsensitiveDict
from jwt import (
JWT,
jwk_from_dict,
jwk_from_pem,
)
from jwt.utils import get_int_from_datetime
def main():
instance = JWT()
message = {
# Client ID for non-production
'iss': '990573e-13e3-143b-8b03-4fbb577b660',
'sub': '990573e-13e3-143b-8b03-4fbb577b660',
'aud': 'https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token',
'jti': 'f9eaafba-2e49-11ea-8880-5ce0c5aee679',
'iat': get_int_from_datetime(datetime.now(timezone.utc)),
'exp': get_int_from_datetime(datetime.now(timezone.utc) + timedelta(hours=1)),
}
# Load a RSA key from a PEM file.
with open('/home/user/ssl/privatekey.pem', 'rb') as fh:
signing_key = jwk_from_pem(fh.read())
compact_jws = instance.encode(message, signing_key, alg='RS384')
print(compact_jws)
headers = CaseInsensitiveDict()
headers['Content-Type'] = 'application/x-www-form-urlencoded'
data = {
'grant_type': 'client_credentials',
'client_assertion_type': 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
'client_assertion': compact_jws
}
x = requests.post('https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token', headers=headers, data=data)
print(x.text)
But I always get a 400 error:
{
"error": "invalid_client",
"error_description": null
}
Is the URL correct? How can I get an Access Token to play with the Sandbox?
'exp': get_int_from_datetime(datetime.now(timezone.utc) + timedelta(hours=1)),
At first glance, this appears to be your issue. Epic requires that exp be no more than 5 minutes in the future.
Couple of pieces of advice, beyond that:
Use a library available from jwt.io
Jwt.io also has a debugger where you can paste in your JWT to verify it is valid

Python HTTPSConnection encryption and Name or service not found error

I’m trying to connect to the OPS API but get an error when trying to connect to the url. I get the access_token just fine as detailed in the documentation (page 34), but when I try to connect to the url I’m interested in, I get a ‘Name or Service not found’ error.
The documentation states (page 35) that the client should access the OPS resource over an encrypted HTTPS connection, which I think might be the missing step in my code creating this error (or not).
Below is the code I use (replacing #### with my access_token):
from http.client import HTTPSConnection
c = HTTPSConnection('ops.epo.org/3.2/rest-services/published-data/search?q=Automation', port=443)
headers2 = {'Authorization': ‘Bearer ########kv5’}
c.request('GET', '/', headers=headers2)
res = c.getresponse()
data = res.read()
Many thanks.
Not sure why this issue was happening earlier, but it seems to be fine now when I run the following code:
headers = {'Authorization': 'Bearer %s' % token }
query = requests.get('http://ops.epo.org/3.2/rest-services/published-data/search?q=Automation', headers=headers)
query.content
I get a status response code of 200, and I can parse the content just fine.

Issue with AppDynamics REST call with Python

I tried to call AppDynamics API using python requests but face an issue.
I wrote a sample code using the python client as follows...
from appd.request import AppDynamicsClient
c = AppDynamicsClient('URL','group','appd#123')
for app in c.get_applications():
print app.id, app.name
It works fine.
But if I do a simple call like the following
import requests
usr =<uid>
pwd =<pwd>
url ='http://10.201.51.40:8090/controller/rest/applications?output=JSON'
response = requests.get(url,auth=(usr,pwd))
print 'response',response
I get the following response:
response <Response [401]>
Am I doing anything wrong here ?
Couple of things:
I think the general URL format for app dynamics applications are (notice the '#'):
url ='http://10.201.51.40:8090/controller/#/rest/applications?output=JSON'
Also, I think the requests.get method needs an additional parameter for the 'account'. For instance, my auth format looks like:
auth = (_username + '#' + _account, _password)
I am able to get a right response code back with this config. Let me know if this works for you.
You could also use native python code for more control:
example:
import os
import sys
import urllib2
import base64
# if you have a proxy else comment out this line
proxy = urllib2.ProxyHandler({'https': 'proxy:port'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
username = "YOUR APPD REST API USER NAME"
password = "YOUR APPD REST API PASSWORD"
#Enter your request
request = urllib2.Request("https://yourappdendpoint/controller/rest/applications/141/events?time-range-type=BEFORE_NOW&duration-in-mins=5&event-types=ERROR,APPLICATION_ERROR,DIAGNOSTIC_SESSION&severities=ERROR")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)
html = response.read()
This will get you the response and you can parse the XML as needed.
If you prefer it in JSON simply specify it in the request.

400 - Bad Request when using the pushalot api under python

I have the below code that I trying to send messages to a Windows Phone using the Pushalot Api as Pushalot haven't got any examples.
I know my api key works fine as the cURL method works fine, but my modified python script isn't working, keep getting -- 400, Bad Request and I'm not sure why.
Any ideas?
#!/usr/bin/python
from urllib import urlencode
from httplib import HTTPSConnection, HTTPException
from ssl import SSLError
pushalot_authorizationtoken = 'xxxxxxxxxxxxxxx'
pushalot_title = 'title'
pushalot_body = 'body'
http_handler = HTTPSConnection("pushalot.com")
data = {'AuthorizationToken': pushalot_authorizationtoken,
'Title': pushalot_title.encode('utf-8'),
'Body': pushalot_body.encode('utf-8') }
try:
http_handler.request("POST",
"/api/sendmessage",
headers = {'Content-type': "application/x-www-form-urlencoded"},
body = urlencode(data))
except (SSLError, HTTPException):
print("Pushalot notification failed.")
response = http_handler.getresponse()
print(response.status, response.reason)
Working today, weird, above code works.
Will leave this here for anyone else that needs the python code for pushalot api

How to create a HTTP proxy handler with Python 3 HTTP lib

I'm trying define a proxy handler to use http.client behind a proxy company. I know just how to use or define a proxy handler to urllib.:
http_proxy_full_auth_string = "http://"+"%s:%s#%s:%s" % (http_proxy_user,
http_proxy_passwd,
http_proxy_server,
http_proxy_port)
proxy_handler = urllib.request.ProxyHandler({"http": http_proxy_full_auth_string})
opener = urllib.request.build_opener(proxy_handler)
urllib.request.install_opener(opener)
resp = urllib.request.urlopen(uri).read()
And using http.client...?
P.S: sorry for the low english skills...
This might be old thread but folks may stumble upon it like I did and dont know how to authenticate.
import http.client
import base64
auth_hash = base64.b64encode(b"username:password").decode("utf-8")
conn = http.client.HTTPSConnection("proxy-ip or hostname", port="proxy-port")
conn.set_tunnel(
"example.com",
headers={"Proxy-Authorization": f"Basic {auth_hash}"})
conn.request("GET", "/")
This is how you do it with basic authentication.
See the httplib python 3 documentation
import http.client
conn = http.client.HTTPSConnection("proxy_domain", 8080)
conn.set_tunnel("www.python.org")
conn.request("HEAD","/index.html")

Categories