Skip to content

Instantly share code, notes, and snippets.

@cipulan
Created March 6, 2024 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cipulan/a35e75989d5678976f61871a71843abf to your computer and use it in GitHub Desktop.
Save cipulan/a35e75989d5678976f61871a71843abf to your computer and use it in GitHub Desktop.
Run Script Before Reboot, Poweroff, or Terminated
[Unit]
Description=Send Telegram Notif
Requires=network-online.target
After=network.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStop=/usr/bin/bash /opt/script/down.sh
[Install]
WantedBy=network.target
#!/bin/bash
# Get Instance Info
response=$(/usr/bin/curl -s ipinfo.io)
# Extract values of "ip" "region" and "org" using jq
ip=$(echo "$response" | jq -r '.ip')
region=$(echo "$response" | jq -r '.region')
org=$(echo "$response" | jq -r '.org')
# Get Instance Hostname
hostname=$(hostname)
name=$(echo "$hostname" | cut -d'.' -f1 | tr '[:lower:]' '[:upper:]')
# Telegram Notification
chat_id=-100xxxxxx
bot_id=67xxxx:xxxxxxxxxxxxxmCo
# Post to telegram Group
/usr/bin/curl -X POST \
-H "Content-Type: application/json" \
-d '{
"chat_id": '"$chat_id"',
"text": "*[ Server : '"$name"' | Status : DOWN ]*\nHostname : *'"$hostname"'* \nIP : *'"$ip"'*\nRegion : *'"$region"'*\nProvider : '"$org"' \n*<-- Please Check -->*",
"parse_mode": "Markdown"
}' \
https://api.telegram.org/bot$bot_id/sendMessage
@cipulan
Copy link
Author

cipulan commented Mar 6, 2024

Run Script Before Reboot, Poweroff, or Terminated

Run script before Reboot, Poweroff, or Terminated. Additionally, it integrates with Telegram to send notifications about these events.

Usage :

  • Install jq for parse JSON
    sudo apt install jq or dnf install jq
  • Create directory /opt/script
    sudo mkdir /opt/script
  • Create file /opt/script/down.sh with script above
    sudo vi /opt/script/down.sh
  • Edit file /opt/script/down.sh and adjust your telegram chat_id & bot_id
  • Change permission with command
    sudo chown +x /opt/script/down.sh
  • Create Service file aa-run-before-shutdown.service under directory /etc/systemd/system/
    sudo vi /etc/systemd/system/aa-run-before-shutdown.service
  • Reload daemon
    sudo systemctl daemon-reload
  • Enable and Start service
    sudo systemctl enable --now aa-run-before-shutdown.service
  • Test it with run script or reboot the machine
    sh /opt/script/down.sh
  • Result
    photo_down

Supported OS :

  • Debian Family
  • RedHat Family

To automated this step using ansible

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment