HTTP POST in GROOVY - groovy

I'm trying desperately to translate this python code into groovy, but I can't find the right solution.
It could be great if someone could help me a bit. :)
#! /usr/bin/env python3
# coding: utf-8
import requests
url = "http://localhost:8088/mockServiceSoapBinding"
xml = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sam="http://www.soapui.org/sample/">
<soapenv:Header/>
<soapenv:Body>
<sam:login>
<username>Login</username>
<password>Login123</password>
</sam:login>
</soapenv:Body>
</soapenv:Envelope>'''
headers = {'content-type': 'text/xml;charset=UTF-8', 'Accept-Encoding': 'gzip,deflate'}
r1 = requests.post(url, data=xml, headers=headers, auth=('user', 'pass'))
print(r1.text)

Making HTTP POST call from Groovy can be done by initializing the URL connection.
Here is a working example:
url = 'http://localhost:8088/mockServiceSoapBinding'
def username = 'user'
def password = 'pass'
xml = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sam="http://www.soapui.org/sample/">
<soapenv:Header/>
<soapenv:Body>
<sam:login>
<username>Login</username>
<password>Login123</password>
</sam:login>
</soapenv:Body>
</soapenv:Envelope>'''
def connection = new URL(url).openConnection()
connection.setRequestMethod('POST')
// set headers
connection.setRequestProperty('Content-Type', 'text/xml;charset=UTF-8')
connection.setRequestProperty('Accept-Encoding', 'gzip,deflate')
if (username && password) {
String userCredentials = username + ':' + password
String basicAuth = 'Basic ' + Base64.getEncoder().encode(userCredentials.getBytes())
connection.setRequestProperty('Authorization', basicAuth)
}
connection.doOutput = true
connection.outputStream.write(xml.getBytes('UTF-8'))
println "XX: connect"
connection.connect()
println "XX: get content"
def text = connection.content.text
println(text)

Related

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

Part of response ( API )

i have done the below script.
def token() :
url = "https://" +ip_add + ":8443/cas/v1/tickets"
payload = 'username=' +usr + '&password='+ pwd
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.post(url, headers=headers,data = payload, verify=False)
response.raise_for_status()
print(response.text)
if response.status_code == 201:
print(response.status_code , "OK", " >>> Normal")
else:
print("Status : ", response.status_code)
and giving me that output :
<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"><html><head><title>201 Created</title></head><body><h1>TGT Created</h1><form action="https://xx.xx.xx.xx:8443/cas/v1/tickets/TGT-86-wFHhWf7Yt5e1WkYggRcDwvZx9H1x05LlfdFFG6ZfVEwL196oC7-cas01.example.org" method="POST">Service:<input type="text" name="service" value=""><br><input type="submit" value="Submit"></form></body></html>
201 OK >>> Normal
so i need to print or save only part of this output which is :
https://xx.xx.xx.xx:8443/cas/v1/tickets/TGT-86-wFHhWf7Yt5e1WkYggRcDwvZx9H1x05LlfdFFG6ZfVEwL196oC7-cas01.example.org
SOLUTION :
for anyone who is searching for a solution, i have tried the below and it worked with me.
tgt = response.headers['location']
print(tgt)
i dont get what you mean but simple regex will do
action="(.+)?" method
or maybe
action=\"(.+)?\" method
to escaped double quotes

get a reuse the token for the Huawei modem E3372h

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?

How to convert Postman OAuth 2.0 to Python

I have been getting the issue when I'm trying to convert Postman OAuth 2.0 to Python3. I tried to research but seems unfortunate for me, I did not find any example
Here is my code:
from rauth import OAuth2Service
import json
def get_token(client_id, client_secret):
access_token = None
service = OAuth2Service(
name="Viafoura",
client_id=client_id,
client_secret=client_secret,
access_token_url='https://auth.viafoura.io/authorize_client'
)
data = {
'scope': 'xxxxx-xxxx-xxxx-xxxx-xxxxx',
'grant_type': 'client_credentials'
}
session = service.get_auth_session(data=data)
access_token = session
Here is OAuth 2.0 on Postman and it's working:
I want to get the access_token via Python3. Could anyone please help me on it?
Maybe it can help you, an example with the basic algorithm of OAuth2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from requests import post, auth, exceptions
from json import loads
if __name__ == '__main__':
client_id = ''
client_secret = ''
user = ''
password = ''
access_point = 'https://account.lab.fiware.org/oauth2/token'
grant_type = 'password'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
auth = auth.HTTPBasicAuth(client_id, client_secret)
data = {'grant_type': grant_type,
'username': user,
'password': password}
resp = None
try:
resp = post(access_point, auth=auth, data=data, headers=headers, timeout=5)
except exceptions.ConnectionError:
exit(1)
if resp.status_code == 200:
resp = loads(resp.text)
if 'access_token' in resp:
print(resp['access_token'])
exit(0)
exit(1)
You need to fix access point, grant type. This source code can be found here
Sorry, I can't help directly with Viafoura and OAuth2Service library.

Unable to retrieve data while parsing soap message with escaped xml using groovy

I try to select value of node from soap message (with gt and lt symbols) , but cant do that, i can only get body (root.Body) and other nodes are not visible, it is empty result. What i'm making wrong?
Thanks!
import groovy.util.slurpersupport.Node
import groovy.util.slurpersupport.NodeChild
import groovy.xml.XmlUtil
String source=
'''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns0:GetListBy_QualificationResponse xmlns:ns0="urn:WS_CTM_People_ICEVA">
<ns0:getListValues>
<ns0:Person_ID>PPL000000301739</ns0:Person_ID>
<ns0:Submitter>soehler</ns0:Submitter>
<ns0:Profile_Status>Enabled</ns0:Profile_Status>
<ns0:Locale2>en_US</ns0:Locale2>
<ns0:VIP>No</ns0:VIP>
<ns0:Client_Sensitivity>Standard</ns0:Client_Sensitivity>
</ns0:getListValues>
</ns0:GetListBy_QualificationResponse>
</soapenv:Body>
</soapenv:Envelope>'''
def root = new XmlSlurper().parseText(source)
def Submitter =root.Body.GetListBy_QualificationResponse.getListValues.'*'.find { node->
node.name() == 'Submitter'
}
It is because the xml is escaped. In order to be able to retrieve the data property, it is required to unescape the xml string and pass it XmlSlurper.
Here is how it can be done:
String source='''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns0:GetListBy_QualificationResponse xmlns:ns0="urn:WS_CTM_People_ICEVA">
<ns0:getListValues>
<ns0:Person_ID>PPL000000301739</ns0:Person_ID>
<ns0:Submitter>soehler</ns0:Submitter>
<ns0:Profile_Status>Enabled</ns0:Profile_Status>
<ns0:Locale2>en_US</ns0:Locale2>
<ns0:VIP>No</ns0:VIP>
<ns0:Client_Sensitivity>Standard</ns0:Client_Sensitivity>
</ns0:getListValues>
</ns0:GetListBy_QualificationResponse>
</soapenv:Body>
</soapenv:Envelope>'''
//map the unescape characters
def map = ['<' : '<', '>' : '>', '"' : '"', '&apos;':'\'', '&':'&']
//Replace them in source string
map.collect {k,v -> source = source.replaceAll(k,v)}
//Now parse it
def root = new XmlSlurper().parseText(source)
//Get the submitter
def submitter = root.'**'.find { it.name() == 'Submitter' }
println submitter
You can quickly try online Demo

Resources