alert_mqtt.sh 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/bin/bash
  2. # LinuxGSM alert_mqtt.sh module
  3. # Author: Daniel Gibbs
  4. # Contributors: https://linuxgsm.com/contrib
  5. # Website: https://linuxgsm.com
  6. # Description: Sends MQTT alert.
  7. moduleselfname="$(basename "$(readlink -f "${BASH_SOURCE[0]}")")"
  8. if [ -z "$(command -v mosquitto_pub 2> /dev/null)" ]; then
  9. fn_print_fail_nl "mosquitto_pub is not installed. MQTT alerts are not available"
  10. fn_script_log_fail "mosquitto_pub is not installed. MQTT alerts are not available"
  11. return
  12. fi
  13. json=$(
  14. jq -cn \
  15. --arg title "${alerttitle}" \
  16. --arg message "${alertmessage}" \
  17. --arg server "${servername}" \
  18. --arg game "${gamename}" \
  19. --arg host "${HOSTNAME}" \
  20. --arg ip "${alertip}:${port}" \
  21. --arg url "${alerturl}" \
  22. --arg time "$(date)" \
  23. '{title: $title, message: $message, server: $server, game: $game, hostname: $host, ip: $ip, url: $url, time: $time}'
  24. )
  25. cmd=(mosquitto_pub -h "${mqtthost}" -p "${mqttport}" -t "${mqtttopic}" -s)
  26. if [ -n "${mqttuser}" ]; then
  27. cmd+=(-u "${mqttuser}")
  28. fi
  29. if [ -n "${mqttpassword}" ]; then
  30. cmd+=(-P "${mqttpassword}")
  31. fi
  32. if [ "${mqtttls}" == "on" ]; then
  33. cmd+=(--capath /etc/ssl/certs)
  34. fi
  35. fn_print_dots "Sending MQTT alert"
  36. mqttsend=$(echo -n "${json}" | timeout 15 "${cmd[@]}" 2>&1)
  37. exitcode=$?
  38. if [ "${exitcode}" -eq 0 ]; then
  39. fn_print_ok_nl "Sending MQTT alert"
  40. fn_script_log_pass "Sending MQTT alert"
  41. else
  42. fn_print_fail_nl "Sending MQTT alert: ${mqttsend}"
  43. fn_script_log_fail "Sending MQTT alert: ${mqttsend}"
  44. fi