get a reuse the token for the Huawei modem E3372h - python-3.x

so i want to read some sms received in my huawei modem.
For that i m tryin to first get the token and session id from the 'http://192.168.8.1/api/webserver/SesTokInfo page
then try to reuse this token in the page http://192.168.8.1/api/sms/sms-list
but i got this error
<error>
<code>125002</code>
<message></message>
</error>
which mean that i don t have the right token value, what i m wondering about.
so this is how my code looks
import hashlib
import base64
import binascii
import xml.etree.ElementTree as ET
from datetime import datetime
import requests
from bs4 import BeautifulSoup
BASEURL = 'http://192.168.8.1'
session = requests.Session()
reqresponse = session.get(BASEURL + '/api/webserver/SesTokInfo')
if reqresponse.status_code == 200:
root = ET.fromstring(reqresponse.text)
for results in root.iter('SesInfo'):
sessionid = results.text
print("the sessionId is", sessionid)
for results in root.iter('TokInfo'):
token = results.text
print("The token is", token)
sessioncookies = reqresponse.cookies
post_data = '<?xml version = "1.0" encoding = "UTF-8"?>\n'
post_data += '<request><PageIndex>1</PageIndex><ReadCount>3</ReadCount><BoxType>1</BoxType><SortTyp$
headers = {'Content-Type': 'text/xml; charset=UTF-8',
'__RequestVerificationToken': token
}
api_url = BASEURL + '/api/sms/sms-list'
logonresponse = session.post( api_url, data=post_data, headers=headers, cookies=sessioncookies)
logonresponse2 = session.get( api_url, data=post_data, headers=headers, cookies=sessioncookies)
result = BeautifulSoup(logonresponse.text, 'html.parser')
for r in result:
print(r)
can someone helo me with the troubleshooting please?

Related

bithumb Api error -{'status': '5100', 'message': 'Bad Request.(Auth Data)'}

I wanted to make a program where I can check the order details of my order at Bithumb Exchange.
So I looked at the docs(https://api.bithumb.com/info/orders) and made it, but the same error code kept coming out, so I don't know what to do.
import time
import math
import base64
import hmac, hashlib
import urllib.parse
import requests
class XCoinAPI:
api_url = "https://api.bithumb.com";
api_key = "";
api_secret = "";
def __init__(self, api_key, api_secret):
self.api_key = api_key;
self.api_secret = api_secret;
def body_callback(self, buf):
self.contents = buf;
def microtime(self, get_as_float = False):
if get_as_float:
return time.time()
else:
return '%f %d' % math.modf(time.time())
def usecTime(self) :
mt = self.microtime(False)
mt_array = mt.split(" ")[:2];
return mt_array[1] + mt_array[0][2:5];
def xcoinApiCall(self, endpoint, rgParams):
# 1. Api-Sign and Api-Nonce information generation.
# 2. Request related information from the Bithumb API server.
#
# - nonce: it is an arbitrary number that may only be used once.
# - api_sign: API signature information created in various combinations values.
endpoint_item_array = {
"endpoint" : endpoint
}
uri_array = dict(endpoint_item_array, **rgParams) # Concatenate the two arrays.
str_data = urllib.parse.urlencode(uri_array)
nonce = self.usecTime()
data = endpoint + chr(1) + str_data + chr(1) + nonce
utf8_data = data.encode('utf-8')
key = self.api_secret
utf8_key = key.encode('utf-8')
h = hmac.new(bytes(utf8_key), utf8_data, hashlib.sha512)
hex_output = h.hexdigest()
utf8_hex_output = hex_output.encode('utf-8')
api_sign = base64.b64encode(utf8_hex_output)
utf8_api_sign = api_sign.decode('utf-8')
headers = {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Api-Key": self.api_key,
"Api-Nonce": nonce,
"Api-Sign": utf8_api_sign
}
url = self.api_url + endpoint
r = requests.post(url, headers=headers, data=uri_array)
return r.json()
a = XCoinAPI(api_key="MYKEY1c", api_secret="MYKEY2")
aa= a.xcoinApiCall("/info/orders",{"order_currency":"LN","payment_currency":"BTC"})
print(aa)
{'status': '5100', 'message': 'Bad Request.(Auth Data)'}
Process finished with exit code 0
The error code 5100, bad request keeps coming up(https://apidocs.bithumb.com/docs/api-%EC%A3%BC%EC%9A%94-%EC%97%90%EB%9F%AC-%EC%BD%94%EB%93%9C)
I really don't know which code to modify.
I think it's a parameter problem with XcoinApiCall, but I don't know.

API in python Error 400 "invalid input parameters" - how to fix

I am programming an API in python to query a server if it has endpoint agents in it. The server and the endpoint belong to Apex central SaaS trend micro.
The error I get is that I'm putting the wrong parameters but I don't think the problem is there.
The code I have for the query is as follows:
import base64
import jwt
import hashlib
import requests
import time
import json
import urllib.parse
def create_checksum(http_method, raw_url, headers, request_body):
string_to_hash = http_method.upper() + '|' + raw_url.lower() + '|' + headers + '|' + request_body
base64_string = base64.b64encode(hashlib.sha256(str.encode(string_to_hash)).digest()).decode('utf-8')
return base64_string
def create_jwt_token(appication_id, api_key, http_method, raw_url, headers, request_body,
iat=time.time(), algorithm='HS256', version='V1'):
payload = {'appid': appication_id,
'iat': iat,
'version': version,
'checksum': create_checksum(http_method, raw_url, headers, request_body)}
token = jwt.encode(payload, api_key, algorithm=algorithm)
return token
# Use this region to setup the call info of the Apex Central server (server url, application id, api key)
# server info
use_url_base = 'https://arct3w.manage.trendmicro.com'
use_application_id = '52EB0005-B6DA-4249-9764-62AE3BFCDBB1'
use_api_key = 'B3FE1D91-5D05-490C-B45C-26A9EFF6C363'
productAgentAPIPath = '/WebApp/API/AgentResource/ProductAgents'
canonicalRequestHeaders = ''
useQueryString=''
payload = {
'computerId':'e34a13a1-1d0f-47bc-96e0-ae4db4288940'
}
useRequestBody = json.dumps(payload)
jwt_token = create_jwt_token(use_application_id, use_api_key, 'POST',
productAgentAPIPath + useQueryString,
canonicalRequestHeaders, useRequestBody, iat=time.time())
headers = {'Authorization': 'Bearer ' + jwt_token , 'Content-Type': 'application/json;charset=utf-8'}
#Choose by call type.
r = requests.post(use_url_base + productAgentAPIPath + useQueryString, data=useRequestBody, headers=headers, verify=False)
print(r.status_code)
if 'application/json' in r.headers.get('Content-Type', '') and len(r.content):
print(json.dumps(r.json(), indent=4))
else:
print(r.text)
I tried to do something similar to an api belonging to Vision One but it didn't work:
https://automation.trendmicro.com/xdr/api-v2#tag/Search/paths/~1v2.0~1xdr~1eiqs~1query~1endpointInfo/post
the original code of the query is :
https://automation.trendmicro.com/apex-central/api#tag/Security-Agents/operation/AgentResource_GetProductAgentsV2

Unable to Access API

I am unable to access an API.
This is what I am doing:
import os, re
import requests
import logger
from requests_oauthlib import OAuth1
oauth_consumer_key = "123abc"
oauth_secret = "aaabbbccc"
url = "https://example_testing/v1/<ID_VALUE>/reports?"
oauth = OAuth1(oauth_consumer_key, oauth_secret)
output = requests.get(url,auth=oauth)
I keep getting a 500 error.
What am I doing wrong?
I didn't know this but apparently I needed to set values for headers and the payload. This solved my problem.
headers = {"Content-Type": "application/json"}
payload = json.dumps({
"report_format":"csv",
<other stuff>
}
output = requests.get(url=url, auth=oauth, headers=headers, data=payload)
Problem Solved

Problem with Python encrypted request.post

I have a problem with encrypted post requests. The encrypted algorithm is AES/ECB/PKCS5Padding and API settings are here: https://bondevalue.com/app/apiInstructions client_token is working. But I always receive 'Seems you are providing invalid input data. Provide data in valid format.'
import requests
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
client_token = b'ae3rncr14cngemft'
requestData = b'{\"data\":{\"userToken\":\"[ae3rncr14cngemft]\"},\"bondISINId\":\"[XS1401197253]\", \"fromDate\":\"[2016-12-07]\"}'
cipher1 = AES.new(client_token, AES.MODE_ECB)
requestEncrypted = str(base64.b64encode(cipher1.encrypt(pad(requestData, 16, 'pkcs7'))), 'utf-8')
url = 'https://bondevalue.com/app/bondDetailsHistoryData'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {'requestData': requestEncrypted}
answer = requests.post(url=url, data=requestEncrypted, headers=headers)
response = answer.json()

Requests for Poloniex API

I trying work with Poloniex API. And I try get balances via Trading API methods. And I try do it with requests library like this:
import requests
import hmac
import hashlib
import time
import urllib
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
polo_request = requests.post('https://poloniex.com/tradingApi', data=post_data, headers=headers, timeout=20)
polo_request = polo_request.json()
print('Request: {0}'.format(polo_request))
return polo_request
With this code I always get error with message: "Request: {'error': 'Invalid command.'}". What I do wrong?
From other side code below returns data without any problem! Look at this, please:
import requests
import hmac
import hashlib
import json
import time
import urllib
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
req = urllib.request.Request('https://poloniex.com/tradingApi', data=post_data, headers=headers)
res = urllib.request.urlopen(req, timeout=20)
Ret_data = json.loads(res.read().decode('utf-8'))
print('Request: {0}'.format(Ret_data))
return Ret_data
I using Python 3.6
It's best to let requests handle post data because it creates the appropriate headers. Other than that i don't see anything wrong with your code.
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(
str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512
).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
polo_request = requests.post(
'https://poloniex.com/tradingApi', data=poloniex_data, headers=headers, timeout=20
)
polo_request = polo_request.json()
print('Request: {0}'.format(polo_request))
return polo_request
Or you could specify the 'Content-Type' in headers if you want to have a string in data, example,
headers = {
'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey'],
'Content-Type': 'application/x-www-form-urlencoded'
}
polo_request = requests.post(
'http://httpbin.org/anything', data=post_data, headers=headers, timeout=20
)

Resources