purge_cdn_cache.sh 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. token=""
  2. service="cdn"
  3. host="cdn.tencentcloudapi.com"
  4. region=""
  5. action="PurgeUrlsCache"
  6. version="2018-06-06"
  7. algorithm="TC3-HMAC-SHA256"
  8. timestamp=$(date +%s)
  9. date=$(date -u -d @$timestamp +"%Y-%m-%d")
  10. payload="{\"Urls\":$purge_urls}"
  11. # ************* 步骤 1:拼接规范请求串 *************
  12. http_request_method="POST"
  13. canonical_uri="/"
  14. canonical_querystring=""
  15. canonical_headers="content-type:application/json; charset=utf-8\nhost:$host\nx-tc-action:$(echo $action | awk '{print tolower($0)}')\n"
  16. signed_headers="content-type;host;x-tc-action"
  17. hashed_request_payload=$(echo -n "$payload" | openssl sha256 -hex | awk '{print $2}')
  18. canonical_request="$http_request_method\n$canonical_uri\n$canonical_querystring\n$canonical_headers\n$signed_headers\n$hashed_request_payload"
  19. # ************* 步骤 2:拼接待签名字符串 *************
  20. credential_scope="$date/$service/tc3_request"
  21. hashed_canonical_request=$(printf "$canonical_request" | openssl sha256 -hex | awk '{print $2}')
  22. string_to_sign="$algorithm\n$timestamp\n$credential_scope\n$hashed_canonical_request"
  23. # ************* 步骤 3:计算签名 *************
  24. secret_date=$(printf "$date" | openssl sha256 -hmac "TC3$secret_key" | awk '{print $2}')
  25. secret_service=$(printf $service | openssl dgst -sha256 -mac hmac -macopt hexkey:"$secret_date" | awk '{print $2}')
  26. secret_signing=$(printf "tc3_request" | openssl dgst -sha256 -mac hmac -macopt hexkey:"$secret_service" | awk '{print $2}')
  27. signature=$(printf "$string_to_sign" | openssl dgst -sha256 -mac hmac -macopt hexkey:"$secret_signing" | awk '{print $2}')
  28. # ************* 步骤 4:拼接 Authorization *************
  29. authorization="$algorithm Credential=$secret_id/$credential_scope, SignedHeaders=$signed_headers, Signature=$signature"
  30. # ************* 步骤 5:构造并发起请求 *************
  31. curl -XPOST "https://$host" -d "$payload" -H "Authorization: $authorization" -H "Content-Type: application/json; charset=utf-8" -H "Host: $host" -H "X-TC-Action: $action" -H "X-TC-Timestamp: $timestamp" -H "X-TC-Version: $version" -H "X-TC-Region: $region" -H "X-TC-Token: $token"