Last active
December 26, 2023 10:18
-
-
Save admk/455df89d1034c3b8ce5b4ad53029ef1b to your computer and use it in GitHub Desktop.
Check if SSH connection is working, useful for crontab
This file contains 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
#!/bin/bash | |
HOST="$1" | |
PORT="$2" | |
BARK_KEY="$3" | |
USER="$(whoami)" | |
IP="$(dig +short $HOST)" | |
KEY_PATH="$HOME/.ssh/id_ed25519" | |
LOG_FILE="$HOME/logs/connection_check.log" | |
mkdir -p $HOME/logs | |
encode() { | |
python3 -c "import urllib.parse; print(urllib.parse.quote('''$1'''))" | |
} | |
send_msg() { | |
title="$USER@$HOST:$PORT" | |
message="[hostname=$(hostname) ip=$IP] $1" | |
message="$(encode "$title")/$(encode "$message")" | |
curl -w "\n" "https://api.day.app/$BARK_KEY/$message" | |
if [ $? -ne 0 ]; then | |
echo "$(date): Failed to send message '$1'" | |
fi | |
} | |
{ | |
if ssh -i "$KEY_PATH" "$USER"@"$HOST" -p "$PORT" true; then | |
if echo `tail -n 1 $LOG_FILE` | grep -q "failed"; then | |
send_msg "back online" | |
echo "$(date) [$IP]: SSH connection back online" | |
fi | |
echo "$(date) [$IP]: SSH connection successful" | |
else | |
send_msg "offline" | |
echo "$(date) [$IP]: SSH connection failed" | |
fi | |
} 2>&1 | tee -a $LOG_FILE |
This file contains 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
0 * * * * /home/USER/connection_check.sh HOST PORT BARK_KEY |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment