Speedtest_logger/Linux/speedtest-cli/speedtest.sh

124 lines
3.0 KiB
Bash
Executable File

#!/bin/bash
# Set WAN Number
WAN="WAN NUMBER"
# Do you want the script to log to a CSV file? Set log variable to 1 for yes, 0 for no
log=SET_NUMBER
# Set the path to the log file
LOG_FILE="PATH TO CSV"
# Do you want the script to output to a Discord webhook? Set discord variable to 1 for yes, 0 for no
discord=SET_NUMBER
# Set your Discord webhook URL
WEBHOOK_URL="DISCORD WEBHOOK URL"
# Get IP info
INFO=$(curl -s https://ipv4.am.i.mullvad.net/json | python -m json.tool)
# Reported IP
IP=$(echo "$INFO" | grep -oE '"ip":\s*"[^"]+"' | grep -oE '[0-9.]+')
# Reported ISP
ORG=$(echo "$INFO" | grep -oE '"organization":\s*"[^"]+"' | grep -oE '"[^"]+"' | tr -d '"')
<<<<<<< HEAD
=======
# Set WAN Number
WAN="NUMBER"
>>>>>>> e74072aff15ddfef5a49aa6a3c1a5d270925c90c
# Run the speedtest and parse the output
SPEEDTEST=$(speedtest-cli --csv)
# Check if the output is empty or contains errors
if [ -z "$SPEEDTEST" ] || [[ "$SPEEDTEST" == *"ERROR"* ]]; then
echo "Speedtest failed: $SPEEDTEST"
exit 1
fi
PING=$(echo "$SPEEDTEST" | awk -F',' '{print $6}')
DOWNLOAD=$(echo "$SPEEDTEST" | awk -F',' '{print $7}')
UPLOAD=$(echo "$SPEEDTEST" | awk -F',' '{print $8}')
# Check if the required fields are missing or invalid
if [ -z "$PING" ] || [ -z "$DOWNLOAD" ] || [ -z "$UPLOAD" ]; then
echo "Missing or invalid speedtest fields: PING=$PING, DOWNLOAD=$DOWNLOAD, UPLOAD=$UPLOAD"
exit 1
fi
# Convert the download and upload speeds to Mbps
DOWNLOAD_Mbps=$(awk "BEGIN { printf \"%.1f\", $DOWNLOAD / (1024*1024) }")
UPLOAD_Mbps=$(awk "BEGIN { printf \"%.1f\", $UPLOAD / (1024*1024) }")
if [ "$log" -eq 1 ]; then
echo "Variable is set to 1. Running command A."
# Append the result to the log file
echo "$(date +"%Y-%m-%d %H:%M:%S"),$ORG,$IP,$PING,$DOWNLOAD_Mbps Mbps,$UPLOAD_Mbps Mbps" >> "$LOG_FILE"
# Check if the variable is set to 0
elif [ "$log" -eq 0 ]; then
echo "Skipping log to file"
# Variable is not set to 1 or 0
else
echo "Variable is not set to a valid value."
fi
if [ "$discord" -eq 1 ]; then
echo "Variable is set to 1."
# Prepare the payload for the Discord webhook
curl -H "Content-Type: application/json" -X POST --data @- "$WEBHOOK_URL" <<EOF
{
"content": null,
"embeds": [
{
"title": "Speedtest Result - WAN $WAN",
"color": 5814783,
"fields": [
{
"name": "Time:",
"value": "$(date +'%Y-%m-%d %H:%M:%S')"
},
{
"name": "ISP:",
"value": "$ORG"
},
{
"name": "IP:",
"value": "$IP"
},
{
"name": "Ping:",
"value": "$PING ms"
},
{
"name": "Download:",
"value": "$DOWNLOAD_Mbps mbps"
},
{
"name": "Upload:",
"value": "$UPLOAD_Mbps mbps"
}
]
}
],
"attachments": []
}
EOF
# Check if the variable is set to 0
elif [ "$discord" -eq 0 ]; then
echo "Skipping send to Discord"
# Variable is not set to 1 or 0
else
echo "Variable is not set to a valid value."
fi