[SOLVED] Exec commandLine/bash script (Unifi) via rule

Okay, thanks for all your help!
Problem was the following:
the “§site” variable wasn’t set first and second the " ’ " in front and behind had to be deleted. i got this by starting the script with “bash -xv …/unifi_wlan_guest.sh” and then with “sudo -u openhab …/unifi_wlan_guest.sh”.
also: the cookie had to be deleted, because there were old/inconsistent data there. therefore the script gets a “rm $cookie” at the last line.
now everything works as intended.
here is the current working script:

#!/bin/bash

unifi_username=user
unifi_password='pass'
unifi_controller=https://192.168.x.xx:xxxx
wifi_id=dsa4fsda6g46fdsg984
cookie=/tmp/cookie

#site_id=""             // deprecated

curl_cmd="curl -s -S --cookie ${cookie} --cookie-jar ${cookie} --insecure "

unifi_login() {
 # authenticate against unifi controller
 # Mute response by adding > /dev/null
 ${curl_cmd} -H "Content-Type: application/json" -X POST -d "{\"password\":\"$unifi_password\",\"username\":\"$unifi_username\"}" $unifi_controller/api/login #> /dev/null
}

unifi_logout() {
 # logout
 ${curl_cmd} $unifi_controller/logout
}

enable_wifi() {
 # enables guest wifi network
 # Mute response by adding > /dev/null
 ${curl_cmd} "$unifi_controller"'/api/s/default/rest/wlanconf/'"$wifi_id" -X PUT --data-binary '{"_id":"'$site_id'","enabled":true}' --compressed #> /dev/null
}

disable_wifi() {
 # enables guest wifi network
 # Mute response by adding > /dev/null
 ${curl_cmd} "$unifi_controller"'/api/s/default/rest/wlanconf/'"$wifi_id" -X PUT --data-binary '{"_id":"'$site_id'","enabled":false}' --compressed #> /dev/null
}

check_status() {
 # checks wifi network status
 # Mute response by adding > /dev/null
 response=$(${curl_cmd} "$unifi_controller"'/api/s/default/rest/wlanconf/'"$wifi_id" --compressed)
 status=$(echo $response | jq ".data[0].enabled")
 if [ "$status" == "true" ]; then
 exit 0
 elif [ "$status" == "false" ]; then
 exit 1
 else
 echo exit -1
 fi
}

unifi_login
if [ "$1" == "enable" ]; then
 echo "Enabling WiFi."
 enable_wifi
elif [ "$1" == "disable" ]; then
 echo "Disabling WiFi."
 disable_wifi
elif [ "$1" == "status" ]; then
 check_status
else
 echo "Must include command line parameter [enable|disable|status]."
fi
unifi_logout
rm $cookie

1 Like