This question already has answers here:
When to wrap quotes around a shell variable?
(5 answers)
Closed 1 year ago.
My script is creating pull requests using the github API:
./my-script.sh my-repo my-branch
#!/bin/bash
Repo=$1
Branch=$2
cd $Repo
get_data() {
cat <<EOF
{
"title": "PR title",
"head": $Branch,
"base": "development",
"body": "PR description"
}
EOF
}
echo $(get_data) # <----------------- I can see my value of the variable $Branch here
curl -X POST \
-H "Accept: application/vnd.github.v3+json" \
-d "$(get_data)" \ # <----------------- But here I'm facing "Problems parsing JSON"
-u my_user:my_token \
https://api.github.com/repos/my_user/$Repo/pulls
open https://github.com/my_user/$Repo/pulls
How can I set my variable into the curl correctly?
$Branch needs to be quoted as well:
get_data() {
cat <<EOF
{
"title": "PR title",
"head": "$Branch",
"base": "development",
"body": "PR description"
}
EOF
}
Related
I am trying to run shell script with a curl command as below with --data-raw as body.
curl --location --request POST '<URL>' \
--header 'Content-Type: application/json' \
--data-raw '{
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Help Text",
"emoji": true
}
},
{
"type": "divider"
},
]
}'
Output:
curl: option --data-raw: is unknown
curl: try 'curl --help' or 'curl --manual' for more information
I couldn't find any error with the json validator. Please suggest a solution. TIA.
Here, you have 2 issue.
your JSON is invalid, the , line 14 need to be removed
use --data and a heredoc :
curl --location --request POST '<URL>' \
--header 'Content-Type: application/json' \
--data "#/dev/stdin"<<EOF
{
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Help Text",
"emoji": true
}
},
{
"type": "divider"
}
]
}
EOF
Here documents:
cat <<EOF followed by several lines of text, followed by the literal string EOF on a new line, NOT indented. The portion between the EOFs is passed to the command as standard input. If 'EOF' is 'quoted', substitutions WON'T be done; otherwise they are. See <<- for the indented variety (not recommended, need TABs).
I've been working on creating a script utilizes curl and variables. Doing some searches I found how to place a variable in the data portion of the curl but now I'm getting errors from the curl command.
(Some parts of the code removed to keep passwords out, everything is working except for entering the data into the --data portion of curl)
curlData=$(cat <<EOF
{
"rebootClient": false,
"createPseudoClientRequest": {
"registerClient": true,
"clientInfo": {
"clientType": 0,
}
},
"packages": [
{
"packageId": 702,
"packageName": "File System",
"packageId": 51,
"packageName": "MediaAgent"
}
],
},
"entities": [
{
"clientId": 0,
}
]
}
EOF
)
shopt -u nocasematch #Sets options back to being case sensitive
echo "$csName"
curl -vv --location --request POST "http://$csName:81/SearchSvc/CVWebService.svc/InstallClient" --header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header "Authtoken: $token" \
-d "$curlData"
Doing a bash -x everything looks correct
"rebootClient": false,
"createPseudoClientRequest": {
"registerClient": true,
"clientInfo": {
"clientType": 0,
}
},
"packages": [
{
"packageId": 702,
"packageName": "File System",
"packageId": 51,
"packageName": "MediaAgent"
}
],
"clientAuthForJob": {
},
"entities": [
{
"clientId": 0,
"clientName": "srybrcost",
}
]
}'
But every time I get Request body is empty or format is invalid
This question already has answers here:
Difference between single and double quotes in Bash
(7 answers)
Closed 3 years ago.
This is my script
#!/bin/bash
set -x
USERNAME="someUser"
curl -H "Content-Type: application/json" -X POST -d '{"auth":{ "client": $USERNAME, "password": "somePassword" }, "messages": { "UpdateProduct": {} }}' http://someDomain.com/services/json
it just becomes as below, it did not replace $USERNAME with someUser
curl -H "Content-Type: application/json" -X POST -d '{"auth":{ "client": $USERNAME, "password": "somePassword" }, "messages": { "UpdateProduct": {} }}' http://someDomain.com/services/json
but if i put USERNAME in, it works
curl -H "Content-Type: application/json" -X POST -d '{"auth":{ "client": "someUser", "password": "somePassword" }, "messages": { "UpdateProduct": {} }}' http://someDomain.com/services/json
Single quotes don't expand variables. You can use something like
-d '{"auth":{ "client": '"$USERNAME"', "password"...
but it can still break if the username contains a double quote.
The cleanest way is to use a tool that understands JSON, e.g. jq:
$ USERNAME='"a"' jq '.username|=env.USERNAME' <<< '{"username":"..."}'
{
"username": "\"a\""
}
sorry guys, but i don't know how clone server in zabbix, so please help.
i didn't find the json request with this function in zabbix documentation, so try to create personal script, but when i get items from server and try to add it in new, have this error :
{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid
params.","data":"Item uses host interface from non-parent
host."},"id":1}
thanks
if need of course my code :
create_host() {
a='{ "jsonrpc": "2.0", "method": "host.create", "params": { "host": "'$selected_name'", "interfaces": [ { "type": 1, "main": 1, "useip": 1, "ip": "'$IP'", "dns": "", "port": "10050" } ], "groups": [ { "groupid": "1" } ], "templates": [ { "templateid": "10001" } ], "inventory": { "macaddress_a": "01234", "macaddress_b": "56768" } }, "auth": "'$AUTH_TOKEN'", "id": 1 }'
wget -O- -o /dev/null $API --no-check-certificate --header 'Content-Type: application/json-rpc' --post-data "$a"
}
push_items() {
id_of_host=`echo $3 | tr -d ']' | tr -d '[u' | sed -s "s/'//g"`
echo "name"$1
echo "key"$2
request_push='{
"jsonrpc": "2.0",
"method": "item.create",
"params": {
"name": "'$1'",
"key_": "'$2'",
"hostid": "'$id_of_host'",
"type": 10,
"value_type": 0,
"interfaceid": "2",
"delay": 300
},
"auth": "'$AUTH_TOKEN'",
"id": 1
}'
wget -O- -o /dev/null $API --no-check-certificate --header 'Content-Type: application/json-rpc' --post-data "$request_push"
}
get_items() {
request='{
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": ["name", "key_"],
"host": "'$ETALON_SERVER'",
"sortfield": "name"
},
"auth": "'$AUTH_TOKEN'",
"id": 1
}'
wget -O- -o /dev/null $API --no-check-certificate --header 'Content-Type: application/json-rpc' --post-data "$request"
}
AUTH_TOKEN=$(authenticate)
if [ -z "$AUTH_TOKEN" ]; then
echo "Connection not established"
exit 1
else
echo "everything is ok"
echo $AUTH_TOKEN
fi
check_host=$(check_exist_host)
host_create=$(create_host)
#echo "$host_create"
id_host=`echo "$host_create" | python -c 'import json, sys; print json.load(sys.stdin)["result"]["hostids"]'`
items=$(get_items)
#echo $items
keys=`echo "$items" | python -c 'import json, sys; print ("".join(i["name"]+";"+i["key_"] +"|" for i in json.load(sys.stdin)["result"]))'`
while IFS='[;]' read -r s1 s2; do
name_item=$s1
item_key=$s2
push_items "$s1" "$s2" "$id_host"
done < <(printf "%b" "${keys//|/\\n}")
As old as this question is, it still comes up in the top search results...
The API doesn't allow host.clone() because it's supposed to be performed through host.get() and host.create(), depending on your needs. The following code clones
host name
host visible name
first IP address
groups, adding a new one (static ID)
macros
and changes
templates (statid ID)
The old host is renamed and disabled, in order to maintain data history.
from pyzabbix import ZabbixAPI
ZAPI = ZabbixAPI(api_url)
ZAPI.login(username, password)
batch_list = [
"host1-asdasd",
"host2-asdasd"
]
for hostname in batch_list:
try:
original_host = ZAPI.host.get(
filter={'host': hostname},
selectGroups='extend',
selectInterfaces='extend',
selectMacros='extend'
)[0]
disable = ZAPI.host.update(
hostid=original_host['hostid'],
status=1,
host=original_host['host'] + '-history',
name=original_host['name'] + ' (history)'
)
print(disable)
clone = ZAPI.host.create(
host=original_host['host'],
name=original_host['name'],
proxy_hostid=original_host['proxy_hostid'],
groups=original_host['groups'] + [{'groupid': 802}],
macros=original_host['macros'],
interfaces=[{'main': '1', 'type': '1', 'useip': '1', 'dns': '', 'port': '10050', 'bulk': '1',
'ip': original_host['interfaces'][0]['ip']}],
templates={'templateid': 25708}
)
print(clone)
except:
print('something went wrong with: ' + hostname)
I am trying to build a Bash script that will take arguments from the command line as well as hard-coded arguments and pass them to a function, which in turn will construct a call to curl and perform an HTTP POST. Unfortunately, when I try passing strings with spaces in them, the script mangles the strings and the eventual call to curl fails to pass the arguments in the right order:
#!/bin/bash
API_URL="http://httpbin.org/"
docurl() {
arg1=$1
shift
arg2=$1
shift
args=()
while [ "$1" ]
do
arg_name="$1"
shift
arg_value="$1"
shift
args+=(-d $arg_name="$arg_value")
done
curl_result=$( curl -qSfs "$API_URL/post" -X POST -d arg1=$arg1 -d arg2=$arg2 ${args[#]} ) 2>/dev/null
echo "$curl_result"
}
docurl foo1 foo2 title "$1" body "$2"
The script invocation would be something like this:
test2.sh "Hello" "Body of the message"
The output of the script as it stands is this:
{
"form": {
"body": "Body",
"arg1": "foo1",
"arg2": "foo2",
"title": "Hello"
},
"headers": {
"Host": "httpbin.org",
"Connection": "close",
"Content-Length": "41",
"User-Agent": "curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*"
},
"files": {},
"data": "",
"url": "http://httpbin.org/post",
"args": {},
"origin": "xxx.xxx.xxx.xxx",
"json": null
}
As you can see, in the form element, the fields "body" and "title" have been truncated. Can anybody let me know what on what I'm doing wrong here?
Use a bit more quotes!
args+=(-d "$arg_name"="$arg_value")
And:
curl_result=$( curl -qSfs "$API_URL/post" -X POST -d arg1="$arg1" -d arg2="$arg2" "${args[#]}" ) 2>/dev/null