Created
August 27, 2021 03:19
-
-
Save sempr/0e8b37c3f4fe571b699aee8ee8fe91cd to your computer and use it in GitHub Desktop.
Send DingTalk with shell and sign
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 | |
DING_SEC="<Your SEC Here>" | |
DING_URL="<Your Webhook Here>" | |
function hash_hmac { | |
# hash_hmac sha256 data sec -binary | |
old_lc_collate=$LC_COLLATE | |
LC_COLLATE=C | |
digest="$1" | |
data="$2" | |
key="$3" | |
shift 3 | |
echo -n "$data" | openssl dgst "-$digest" -hmac "$key" "$@" | |
LC_COLLATE=$old_lc_collate | |
} | |
urlencode() { | |
# urlencode <string> | |
old_lc_collate=$LC_COLLATE | |
LC_COLLATE=C | |
local length="${#1}" | |
for ((i = 0; i < length; i++)); do | |
local c="${1:$i:1}" | |
case $c in | |
[a-zA-Z0-9.~_-]) printf '%s' "$c" ;; | |
*) printf '%%%02X' "'$c" ;; | |
esac | |
done | |
LC_COLLATE=$old_lc_collate | |
} | |
escape_json_string() { | |
JSON_TOPIC_RAW=$1 | |
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//\\/\\\\} \ | |
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//\//\\\/} # \ | |
# / | |
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//\'/\\\'} # ' (not strictly needed ?) | |
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//\"/\\\"} # " | |
JSON_TOPIC_RAW=${JSON_TOPIC_RAW// /\\t} # \t (tab) | |
JSON_TOPIC_RAW=${JSON_TOPIC_RAW// | |
/\\\n} # \n (newline) | |
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//^M/\\\r} # \r (carriage return) | |
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//^L/\\\f} # \f (form feed) | |
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//^H/\\\b} # \b (backspace) | |
echo $JSON_TOPIC_RAW | |
} | |
send() { | |
# send msg | |
msg=$(escape_json_string "$1") | |
DT=$(echo $(date +%s%N) / 1000000 | bc) | |
data=$(echo -e "$DT\n$DING_SEC") | |
SIGN=$(urlencode $(hash_hmac sha256 "$data" $DING_SEC -binary | base64)) | |
url="$DING_URL&sign=$SIGN×tamp=$DT" | |
POST_DATA=$(echo '{"msgtype": "text", "text": {"content": "' "$msg"'"}}') | |
curl $url \ | |
-H 'Content-Type: application/json' -d "$POST_DATA" | |
} | |
send "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment