Python requests.get() getting error invalid msg - python

I am trying to make simple script in Python to request API GET responses from Bitcoin mining machines. I need to request a certain JSON key and value {"command":"summary"}. I will extract data from the JSON payload obtained with this to monitor some machines on Zabbix.
If I send the request with bash like this:
# echo '{"cmd":"summary"}' | timeout 1.5 nc IPADDRESS PORT
I will get the data I need, and I could even process it with bash using tr, sed and jq...
However if I send the request with my Python Script I always get "invalid msg". I would much rather do it with Python because I am learning and I can imagine my error is pretty dumb.
This is the python code.
#!/usr/bin/python3
import sys
import logging
import requests
import json
server = 'http://10.136.132.140:4028'
payload = {
"command":"summary"
}
jsonpayload = json.dumps(payload)
print(payload)
print(jsonpayload)
response = requests.get(server,
jsonpayload
)
print(response.json())
This won't work no matter what I do. I have tried using directly payload as params for requests.get to send the string only. Nothing works. Everytime I get the same invalid msg. I have tried typing response = requests.get('http://IPADDRESS:PORT', '{"command":"summary"}') directly, any combination possible of single quotes or double quotes... Nothing works.
I get three exceptions when I call it. The important tracebacks are the following:
http.client.BadStatusLine: STATUS=E,When=1608811559,Code=14,Msg=invalid cmd,Description=whatsminer v1.1
urllib3.exceptions.ProtocolError: ('Connection aborted.', BadStatusLine('STATUS=E,When=1608811559,Code=14,Msg=invalid cmd,Description=whatsminer v1.1'))
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.',
BadStatusLine('STATUS=E,When=1608811559,Code=14,Msg=invalid
cmd,Description=whatsminer v1.1'))
What am I doing wrong here?
Thanks for your help in advance!

If you want to send a json payload, try this:
server = '' # server url
payload = {
"command":"summary"
}
response = requests.get(server, json=payload)

Related

Send API request with request body data using Python to create or update RunCommands within Powershell script .ps1 file

I want to send API requests to create or update commands in a ,Powershell script, .ps1 file.
I'm using Python requests library.
I followed the microsoft document HERE to construct the api to be send PUT request.
The format of the .ps1 file that I want to link with the request is something like;
$Comp = $env:computername
$Timezone = (Get-Timezone).Id
If ($Timezone -ne "UTC-04:00")
{write-host "Timezone: Problem Occured!" $timezone -backgroundcolor red}89
else {write-host "TimeZone: OK" $timezone}
and allowed to contain other commands. New commands should be created with sent api request.
The function, takes rgName,vmName,CommandName as parameter and forms an API
to send request with
requests.put(url:"",data:{},params:{}) in python.
The function template as follows;
`subscription_id =os.environ['AZURE_SUBSCRIPTION_ID']
source="https://management.azure.com"
token_context=access_token()
tokens=json.loads(token_context.text)
token=tokens['access_token']
url=" {}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}/
runCommands/{}?api-version==2021-04-01".format(source,subscription_id,vmRG,vmName,command)
data={"location": "West US","commandId":
"RunShellScript","script": "<urlAdress_toScriptFileinBlobStorage>","asyncExecution":
False,"timeoutInSeconds": 3600}
headers = {'Authorization': 'Bearer ' +token,
'Content-Type': 'application/json'}
response = requests.put(url,data=data,headers=headers)
return response`
But I cannnot get a response body.
The error message I got "
"error": {
"code": "InvalidRequestContent",
"message": "The request content was invalid and could not be deserialized:
'Unexpected character encountered while parsing value: l. Path '', line 0, position 0.'."
"
How can I achieve this task? Is it possible to do with an another method?
What're your opinions about source of the error and how could I fix it?
Any suggestions and solution methods would be appreciated. Thanks in Advance,

Using python zeep to consume web service. How to handle this response?

I am using a zeep client to consume a web service that is supposed to return me a file in base64binary format. I am using the following code.
try:
client = Client('https://host.com/xmlpserver/services/v2/CatalogService?wsdl')
response = client.service.downloadObject('/~fin_impl/INVITEM20.xdo','username','password')
print(response)
except zeepExceptions.Fault as fault:
print(fault.detail)
However, I am not sure what format is this response in and how to decode it.
b'PK\x03\x04\x14\x00\x08\x08\x08\x00o\xb8\x9cP\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00_report.xdo\x8dT\xcbN\xdc0\x14\xdd\xf3\x15V6\xacH\x02tQ\x01\x03*/i\xa4\x99\x01\r\x94v\x87\x8cs\x87\xb1\xf0K\xf65\xc9t\xd1o\xefu^\xa2\x14\xaaI\x94\x85\x8f\x8f}\xcf\xb99\xf6\xc9Y\xa3\x15{\x05\x1f\xa45l\xc2v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a{\x04\xed\x14G\x08\xac\x82\x15\x8f\n\'Y\x1f\xbf\xc7\x83\x92\xde\xfd\xb2\xfc\xd2\x05\xf6-\x9b)\xfe\x94N\xe3\xbf\xd4.\xcco\xf1\x04\xe7MJ%n\x1c\xa9\x85F\x80\xca\x98\x8d\xe8"^\xa7\x86\xe2\x08\xf6\x1a\xde\xa1\x8a\x94\'\x9f#]\xadd\xe0O\n\xe6<\xa4\xf3\xda\xcb\x19\x8e"\x17(_\xc7\xd1\xab\x84\xfa\xa6\x8d\xf9\xdf\xc1(F\xcft\x8d\x15\xdd=v\xba\xf3\x07PK\x07\x08\xe8\xc9\xba\xb2-\x02\x00\x00\xfc\x04\x00\x00PK\x03\x04\x14\x00\x08\x08\x08\x00o\xb8\x9cP\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x18\x00\x00\x00INVITEM_20201004.xls.png\x03\x00PK\x07\x08\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00PK\x03\x04\x14\x00\x08\x08\x08\x00o\xb8\x9cP\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\x00\x00\x00INVITEM_20201004_en.xls\xed]\x07\\SI ........'
Please suggest, Thanks

How to get HTTP error stream using Python requests library?

How do I access the error stream using the Python requests library? For example, using HttpURLConnection in Java, I would do something like:
InputStream errorStream = conn.getErrorStream();
Is there a function like this with requests?
I'm looking for the error message in the response that was supplied by the source, NOT the error status e.g. Internal Server Error
requests won't raise an exception if HTTP error occurs, but you can get the error message in the response content. Example:
url = 'https://stackoverflow.com/does_not_exist'
r = requests.get(url)
print(r.status_code, r.reason)
print(r.text)

Python SUDS - Getting Exception 415 when calling a SOAP method

from suds.client import Client
url = r'http://*********?singleWsdl'
c = Client(url)
The requests work fine till here, but when I execute the below statement, I get the error message shown at the end. Please help.
c.service.Method_Name('parameter1', 'parameter2')
The Error message is :
Exception: (415, u'Cannot process the message because the content type
\'text/xml; charset=utf-8\' was not the expected type
\'multipart/related; type="application/xop+xml"\'.')
A Content-Type header of multipart/related; type="application/xop+xml" is the type used by MTOM, a message format used to efficiently send attachments to/from web services.
I'm not sure why the error claims to be expecting it, because the solution I found for my situation was the override the Content-Type header to 'application/soap+xml;charset=UTF-8'.
Example:
soap_client.set_options(headers = {'Content-Type': 'application/soap+xml;charset=UTF-8'})
If you are able, you could also trying checking for MTOM encoding in the web service's configuration and changing it.

WebService request with python suds by XML

i'm trying to comunicate with a webserver with python. I'm using the suds library. Actually i'm pretty new with this.
Usually, to comunicate with this WebServer a send a xml message and i get a response. So this is what i would like to do with python.
Here's the code i wrote:
from suds.client import Client
with open("PATH","r") as f:
file=f.read()
url='URL'
client = Client(url)
httpHeaders = {'Content-Type': 'text/xml', 'SOAPAction': 'ACTION'}
client.set_options(headers=httpHeaders)
Now i don't know how to make the request. I tried this:
print client.service.test(__inject={'msg': file})
But i got the error:
Exception: No services defined
The problem seems clear, but i don't know haw to procede. Any suggestion ?

Categories