87 lines
2.6 KiB
Bash
Executable file
87 lines
2.6 KiB
Bash
Executable file
#!/usr/bin/bash
|
|
|
|
# Default values
|
|
template=""
|
|
username=""
|
|
password=""
|
|
protocol="http"
|
|
servername="localhost" # Default server name
|
|
json_data=""
|
|
|
|
# Function to display usage
|
|
usage() {
|
|
echo "Usage: $0 -t <template_file> -u <username> -p <password> -o <protocol> -s <servername> <json_data>"
|
|
echo " -t : Optional. Template file to format JSON output."
|
|
echo " -u : Optional. Username for authentication."
|
|
echo " -p : Optional. Password for authentication."
|
|
echo " -o : Optional. Protocol to use for sending data. Supported: http, https, ws, mqtt."
|
|
echo " -s : Optional. Server name or IP address (default: your-collector-server)."
|
|
echo " json_data : JSON data to send (required)."
|
|
exit 1
|
|
}
|
|
|
|
# Parse command-line arguments
|
|
while getopts ":t:u:p:o:s:" opt; do
|
|
case ${opt} in
|
|
t ) template="$OPTARG" ;;
|
|
u ) username="$OPTARG" ;;
|
|
p ) password="$OPTARG" ;;
|
|
o ) protocol="$OPTARG" ;;
|
|
s ) servername="$OPTARG" ;;
|
|
* ) usage ;;
|
|
esac
|
|
done
|
|
shift $((OPTIND -1))
|
|
|
|
# Get JSON data as the first positional argument
|
|
json_data="$1"
|
|
|
|
if [ -z "$json_data" ]; then
|
|
echo "Error: JSON data is required."
|
|
usage
|
|
fi
|
|
|
|
# Load and apply template if provided
|
|
if [ -n "$template" ] && [ -f "$template" ]; then
|
|
# Read the template and substitute {{data}} placeholder with JSON data using jq
|
|
body=$(jq --argjson data "$json_data" '.formatted_data = $data' "$template" 2>/dev/null)
|
|
if [ -z "$body" ]; then
|
|
echo "Error: Failed to apply template with jq."
|
|
exit 1
|
|
fi
|
|
else
|
|
body="$json_data"
|
|
fi
|
|
|
|
|
|
# Function to send data based on protocol
|
|
send_data() {
|
|
case "$protocol" in
|
|
http|https)
|
|
url="${protocol}://${servername}/api/metrics"
|
|
curl -X POST -H "Content-Type: application/json" \
|
|
-u "$username:$password" \
|
|
-d "$body" "$url" \
|
|
--max-time 5 --silent --output /dev/null || echo "Mocked HTTP send for test"
|
|
;;
|
|
ws)
|
|
echo "$body" | websocat "ws://${servername}/api/metrics" \
|
|
--header="Authorization: Basic $(echo -n "$username:$password" | base64)" || echo "Mocked WebSocket send for test"
|
|
;;
|
|
mqtt)
|
|
echo "$body" | mosquitto_pub -t "metrics/topic" -u "$username" -P "$password" -h "$servername" -m "$body" || echo "Mocked MQTT send for test"
|
|
;;
|
|
syslog)
|
|
logger -t "monitoring-agent" "$body"
|
|
;;
|
|
*)
|
|
echo "Unsupported protocol: $protocol"
|
|
exit 1
|
|
;;
|
|
esac
|
|
}
|
|
|
|
|
|
# Execute the send_data function
|
|
send_data
|
|
|