Skip to content

Instantly share code, notes, and snippets.

@gilangvperdana
Created May 15, 2023 04:53
Show Gist options
  • Save gilangvperdana/0f9ccb51ba61dcddb807654c5640faec to your computer and use it in GitHub Desktop.
Save gilangvperdana/0f9ccb51ba61dcddb807654c5640faec to your computer and use it in GitHub Desktop.
Notify New/Deleted DNS Record to Telegram on Cloudflare with Cloudflare API
#!/bin/bash
# Token bot Telegram dan chat ID penerima notifikasi
TOKEN="YOUR_BOT_TOKEN"
CHAT_ID="YOUR_TELEGRAM_CHAT_ID"
# Fungsi untuk mengirim notifikasi ke Telegram
function send_telegram_notification {
MESSAGE="$1"
curl -s -X POST "https://api.telegram.org/bot$TOKEN/sendMessage" \
-d chat_id="$CHAT_ID" \
-d text="$MESSAGE" \
-d parse_mode=HTML \
> /dev/null
}
# Mengambil DNS record dari API Cloudflare dan menyimpannya ke file temporary
EMAIL="YOUR_CLOUDFLARE_EMAIL"; \
KEY="YOUR_CLOUDFLARE_APITOKEN"; \
ZONE_ID="YOUR_CLOUDFLARE_ZONEID"; \
curl -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
-H "X-Auth-Email: $EMAIL" \
-H "Authorization: Bearer $KEY" \
-H "Content-Type: application/json" \
| python -c "import sys, json; print('\n'.join([r['name']+' '+r['content']+' '+r['type'] for r in json.load(sys.stdin)['result']]))" > dnsrec_temp.txt
# Jika file dnsrec.txt belum ada, buat file tersebut dan kirim notifikasi ke Telegram
if [ ! -f dnsrec.txt ]; then
mv dnsrec_temp.txt dnsrec.txt
MESSAGE="Berikut adalah DNS record yang tersimpan saat ini:\n$(cat dnsrec.txt)"
send_telegram_notification "$MESSAGE"
# Jika file dnsrec.txt sudah ada, bandingkan dengan file temporary untuk mencari perubahan
else
diff_output=$(diff -u dnsrec.txt dnsrec_temp.txt)
if [ -n "$diff_output" ]; then
# Ada perubahan pada file DNS record
# Periksa apakah ada record baru atau record yang dihapus
added_records=$(echo "$diff_output" | grep '^+\w'| awk '{print $3,$2.$1}')
deleted_records=$(echo "$diff_output" | grep '^\-\w'| awk -F '[[:space:]]+|-' '{print $3," ",$2$1}' | sed 's/^-//g')
if [ -n "$added_records" ]; then
# Ada record baru
message="Terdapat record <b>DNS Baru</b> yaitu <b>$added_records</b>"
send_telegram_notification "$message"
fi
if [ -n "$deleted_records" ]; then
# Ada record yang dihapus
message="Terdapat record <b>DNS yang diHapus</b> yaitu <b>$deleted_records</b>"
send_telegram_notification "$message"
fi
# Update file dnsrec.txt dengan file temporary
mv dnsrec_temp.txt dnsrec.txt
else
# Tidak ada perubahan pada file DNS record
rm dnsrec_temp.txt
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment