Last active
November 13, 2024 12:22
-
-
Save LaurenceJJones/94bee85fc7e2a058ae24890dacfbc303 to your computer and use it in GitHub Desktop.
Bash script to detect if crowdsec agent hasnt sent a heartbeat over 2 mins
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
current="$(/usr/bin/date '+%s')" | |
cscli=$(which cscli) | |
machinesJson=$($cscli -ojson machines list) | |
echo $machinesJson | /usr/bin/jq -r '.[]| select(.last_heartbeat != null) | [.last_heartbeat, .machineId] | @tsv' | | |
while IFS=$'\t' read -r hb mid; do | |
last_hb="$(/usr/bin/date -u -d "$hb" '+%s')" | |
diff=$((current - last_hb)) | |
if [ "$diff" -gt "180" ]; then | |
echo "$mid has not contacted LAPI for more than 2 minutes" | |
# Do notifying here for machine that has not contacted LAPI for more than 2 minutes | |
fi | |
done | |
echo $machinesJson | /usr/bin/jq -r '.[]| select(.last_heartbeat == null) | .machineId' | | |
while read -r mid; do | |
# Do notifying here for machine that never contacted LAPI | |
echo "$mid has never contacted LAPI" | |
done | |
Looks like line 4 is getting unexpected inputs format : /usr/bin/date: invalid date ‘2022-12-31T03:42:45.167902982Z\machineId
I suggest the below :
- Changing the parsing of $hb, as it is in UTC time it seems, we need to add -u
- diff, doesn't require "" around the variables
With the below, it seems to work for me.
thanks for the help
current="$(/usr/bin/date '+%s')"
/usr/bin/cscli -ojson machines list | /usr/bin/jq -r '.[]| [.last_heartbeat, .machineId] | @tsv' |
while IFS=$'\Z' read -r hb mid; do
last_hb="$(/usr/bin/date -u -d "$hb" '+%s')"
diff=$(($current - $last_hb))
if [ "$diff" -gt "180" ]; then
echo "$mid hasn't sent heartbeat in over 2 minutes"
fi
done
I suggest the below :
* Changing the parsing of $hb, as it is in UTC time it seems, we need to add -u * diff, doesn't require "" around the variables
With the below, it seems to work for me.
thanks for the help
current="$(/usr/bin/date '+%s')" /usr/bin/cscli -ojson machines list | /usr/bin/jq -r '.[]| [.last_heartbeat, .machineId] | @tsv' | while IFS=$'\Z' read -r hb mid; do last_hb="$(/usr/bin/date -u -d "$hb" '+%s')" diff=$(($current - $last_hb)) if [ "$diff" -gt "180" ]; then echo "$mid hasn't sent heartbeat in over 2 minutes" fi done
The issue you changed IFS=$'\t'
this is used to break on the tab characters. Cause | @tsv'
changes the array to tab seperated values. I checked and Z in date works fine for me.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replace echo statement with the notification
$mid
is either the random ID crowdsec generates or machine name if custom name is supplied when registering to lapi.