Добрый вечер, у меня вопрос.
Как получить код результата (returncode) и возвращаемые данные в RestAPI
Good evening, I have a question.
How to get both result code(returncode) and return data in RestAPI
Добрый вечер, у меня вопрос.
Как получить код результата (returncode) и возвращаемые данные в RestAPI
Good evening, I have a question.
How to get both result code(returncode) and return data in RestAPI
Can you be more specific about your problem/use case?
Use the new API, i.e. use access key
and secret key
, configure returncode
to no
, save the headers to a file and extract the exit code from the headers.
Example with curl:
curl -sS -X POST -D "$headers_file" -d "{\"access_key\":\"$akey\",\"secret_key\":\"$skey\",\"returncode\":\"no\",\"cmd\":\"$cmd\"""${arg_data}""}" "$api_url"
Then you can extract the header hestia-exit-code
from $headers_file
:
awk '/hestia-exit-code/ {print $2}' "$headers_file" | sed 's/\r//'
Here an example script:
#!/usr/bin/env bash
api_url="https://hestiacp.example.net:8083/api/"
headers_file="$(mktemp)"
akey="HereTheAccessKey"
skey="HereTheSecretKey"
cmd="${1:-v-list-sys-services}"
narguments="$#"
arguments="$((narguments - 1))"
arg_data=""
if [[ "$arguments" -gt 0 ]]; then
i=1
while [[ $i -le "$arguments" ]]; do
z=$((i + 1))
# shellcheck disable=SC1083
arg_data="${arg_data},\"arg${i}\":\"$(eval echo \${$z})\""
((++i))
done
fi
_check_hestia_exit_code() {
if grep -q -E '^hestia-exit-code:\s{1,}[0-9]{1,}' "$headers_file"; then
rc="$(awk '/hestia-exit-code/ {print $2}' "$headers_file" | sed 's/\r//')"
else
rc="I couldn't get hestia-exit-code header from API response."
fi
echo "$rc"
}
output="$(curl -sS -k -X POST --connect-timeout 15 -m 300 -D "$headers_file" -d "{\"access_key\":\"$akey\",\"secret_key\":\"$skey\",\"returncode\":\"no\",\"cmd\":\"$cmd\"""${arg_data}""}" "$api_url")"
echo "$output"
echo
echo "Return code: $(_check_hestia_exit_code)"
rm -f "$headers_file"
If you use above script to list services you will see an output like this:
$ ./test v-list-sys-services
NAME STATE CPU MEM UPTIME
---- ----- --- --- ------
nginx running 0 282 822
php8.1-fpm running 0 12 9606
php8.2-fpm running 0 13 826
php8.3-fpm running 0 13 837
exim4 running 0 14 1408
dovecot running 0 0 1408
spamd running 0 338 9606
mariadb running 0 3542 9605
postgresql running 0 12 9605
vsftpd running 0 0 9605
cron running 0 0 9605
ssh running 0 2 9605
iptables running 0 0 0
fail2ban running 0.2 233 9606
Return code: 0
If you try to use an invalid command:
$ ./test v-list-whatever
Error: Command v-list-whatever not found
Return code: 10
If you try to use an invalid argument:
$ ./test v-add-user ----- whatever [email protected]
Error: invalid user format :: -----
Return code: 2