Add smarter api call function

master
Cole Deck 7 months ago
parent 181a3b0fd3
commit ed690495d2

4
.gitignore vendored

@ -4,4 +4,6 @@ firmware/*
*.csv
listing.txt
*.pyc
__pycache__
__pycache__
build
*.crt

@ -1,4 +1,25 @@
import requests
from read_api_details import parse_csv_to_dict
from sys import platform
import subprocess
def ping(host):
#Returns True if host (str) responds to a ping request.
# Option for the number of packets as a function of
if platform == "win32":
param1 = '-n'
param2 = '-w'
param3 = '250'
else:
param1 = '-c'
param2 = '-W'
param3 = '0.25'
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param1, '1', param2, param3, host]
return subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) == 0
def call_api(api_url, method, params):
"""
@ -15,10 +36,62 @@ def call_api(api_url, method, params):
print("Calling API",api_url,"with method",method,"and parameters",params)
if method.upper() == 'POST':
response = requests.post(api_url, data=params, verify=False)
response = requests.post(api_url, data=params, verify='./apicert.crt', timeout=8)
elif method.upper() == 'GET':
response = requests.get(api_url, params=params, verify=False)
response = requests.get(api_url, params=params, verify='./apicert.crt', timeout=8)
else:
raise ValueError("Method must be 'POST' or 'GET'")
return response
def call_api_preloaded(callname, method="auto", params={}, baseaddr="https://192.168.49.1/tool/", conntype="eth"):
details = parse_csv_to_dict("apidetails.csv")
if not callname.find(".php") > 0:
callname += ".php"
full_url = baseaddr + callname
auto_include = []
methodcount = {}
if 'PARAM' in details[callname]:
for param, val in details[callname]["PARAM"].items():
if not val in methodcount:
methodcount[val] = 0
methodcount[val] += 1
mx = (None, 0)
if method == "auto" or method == "":
for mt, ct in methodcount.items():
if ct > mx[1]:
mx = (mt, ct)
if mx[0] is None:
# no methods?
return None
else:
method = mx[0]
if 'PARAM' in details[callname]:
for param, val in details[callname]["PARAM"].items():
# print(param, val)
if val == method:
print(param, end="")
if 'KEY' in details[callname]:
for keyname, key in details[callname]["KEY"].items():
if keyname == param:
print("=" + key, end="")
auto_include.append((keyname, key))
if param == "type":
# common parameter checks if in BLE mode
print("=" + conntype, end="")
auto_include.append(("type", conntype))
print("")
for param in auto_include:
params[param[0]] = param[1]
if not ping("192.168.49.1"):
print("Connecting to netool...")
while not ping("192.168.49.1"):
pass
return call_api(full_url, method, params)

@ -1,3 +1,7 @@
#!/bin/sh
rm -rfv firmware *.bin* fwname listing.txt
rm -rfv firmware *.bin* fwname listing.txt
sleep 1
echo "HELLO"
echo "GOODBYE"
sleep 1

@ -0,0 +1,8 @@
mkdir -p build
cd build
# wget https://busybox.net/downloads/busybox-1.36.1.tar.bz2
# tar -xvf busybox-1.36.1.tar.bz2
cd busybox-*

@ -1,5 +1,7 @@
#!/bin/sh
set -euo pipefail
# Firmware downloader
DEVICE=NE1D
@ -9,16 +11,16 @@ VERSION=194
BASEURL=https://updates.netool.io/bin/
wget -O listing.txt $BASEURL
wget -q --show-progress -O listing.txt $BASEURL
filename=$DEVICE-$VERSION-UP-$SERIAL.bin
rm *.bin*
if cat listing.txt | grep $filename && wget $BASEURL$filename; then
rm -f *.bin*
if cat listing.txt | grep $filename > /dev/null && wget -q --show-progress $BASEURL$filename; then
# exact version match
echo $filename > fwname
else
filename=$DEVICE-$VERSION-UP-1133333.bin
if cat listing.txt | grep $filename && wget $BASEURL$filename; then
if cat listing.txt | grep $filename > /dev/null && wget -q --show-progress $BASEURL$filename; then
echo $filename > fwname
else
echo "ERROR: Unable to find firmware!"

@ -1,5 +1,7 @@
#!/bin/sh
set -euo pipefail
# Define the paths to the SquashFS images
IMAGE="$1"
@ -11,11 +13,11 @@ MOUNTPOINT="./firmware"
# Create the mount points if they don't exist
mkdir -p $MOUNTPOINT
# Mount the SquashFS images
7z x -o$MOUNTPOINT $IMAGE
# Extract the files we need
7z x -o$MOUNTPOINT $IMAGE www/tool/ etc/*.crt -bsp1 -bso0 -bse0 -y
echo "Extracting certificate..."
cp $MOUNTPOINT/etc/*.crt ./apicert.crt
# Perform the diff and show only the differences
#diff --no-dereference -r $MOUNTPOINT
# Remove the mount points
#rm -rf $MOUNTPOINT

@ -40,7 +40,7 @@ def read_php_files(input, output):
add += ",PARAM:," + quoted_strings[0] + "," + paramtype
for codetype in search_list:
for match in re.finditer("\$" + codetype, contents):
for match in re.finditer("\\$" + codetype, contents):
# Extract the line containing the matched string
start_line = contents.rfind('\n', 0, match.start()) + 1
end_line = contents.find('\n', match.end(), -1)

@ -1,30 +1,17 @@
from call_api import call_api
from call_api import *
from read_api_details import parse_csv_to_dict
import json
def main():
base_url = "https://192.168.49.1/tool/" # Replace with your actual base URL
details = parse_csv_to_dict("apidetails.csv")
print(details.keys())
# Prompt the user for the API call
api_call = input("Enter the API call (e.g., about.php): ").strip()
full_url = base_url + api_call
if not api_call.find(".php") > 0:
api_call += ".php"
print(details[api_call])
# Prompt the user for the method
method = input("Enter the HTTP method (POST/GET): ").strip().upper()
auto_include = []
if 'PARAM' in details[api_call]:
for param, val in details[api_call]["PARAM"].items():
# print(param, val)
if val == method:
print(param, end="")
if 'KEY' in details[api_call]:
for keyname, key in details[api_call]["KEY"].items():
if keyname == param:
print("=" + key, end="")
auto_include.append((keyname, key))
print("")
method = input("Enter the HTTP method (POST/GET): ").strip().upper()
# Prompt the user for parameters
params = {}
@ -35,11 +22,9 @@ def main():
param_value = input(f"Enter value for '{param_name}': ").strip()
params[param_name] = param_value
for param in auto_include:
params[param[0]] = param[1]
# Call the API
try:
response = call_api(full_url, method, params)
response = call_api_preloaded(api_call, method, params)
print("Response Status Code:", response.status_code)
try:
print("Response JSON:", json.dumps(response.json(), indent=2))

@ -0,0 +1,24 @@
#!/bin/sh
set -euo pipefail
if (! [ -e apidetails.csv ]) || (! [ -e apicert.crt ]); then
echo "Downloading firmware for device..."
./download-fw.sh
echo "Extracting firmware..."
./extract.sh $(cat fwname)
DIR=./firmware/www/tool/
echo "tool_directory: $DIR
app_config_directory: ." > config.yml
echo "Extracting API keys..."
python get_codes.py > /dev/null
echo "Cleaning up..."
./cleanup.sh > /dev/null
echo "API client is setup."
else
echo "Already setup."
fi

@ -1,15 +0,0 @@
#!/bin/sh
if ! [ -e apidetails.csv ]; then
./download-fw.sh
./extract.sh $(cat fwname)
DIR=./firmware/www/tool/
echo "tool_directory: $DIR
app_config_directory: ." > config.yml
python get_codes.py
./cleanup.sh
fi
Loading…
Cancel
Save