gpt4 book ai didi

bash - 如何使用 Curl 检索真正的重定向位置 header ?不使用 {redirect_url}

转载 作者:行者123 更新时间:2023-11-29 09:25:10 29 4
gpt4 key购买 nike

我意识到 Curl {redirect_url} 并不总是显示相同的重定向 URL。例如,如果 URL header 是 Location: https:/\example.com 这将重定向到 https:/\example.com 但 curl {redirect_url} 显示 redirect_url: https://host-domain.com/https:/\example.com 并且它不会显示响应真实位置 header 。 (我喜欢看到真正的 location: 结果。)

这是我正在使用的 BASH:

#!/bin/bash
# Usage: urls-checker.sh domains.txt
FILE="$1"
while read -r LINE; do
# read the response to a variable
response=$(curl -H 'Cache-Control: no-cache' -s -k --max-time 2 --write-out '%{http_code} %{size_header} %{redirect_url} ' "$LINE")
# get the title
title=$(sed -n 's/.*<title>\(.*\)<\/title>.*/\1/ip;T;q'<<<"$response")
# read the write-out from the last line
read -r http_code size_header redirect_url < <(tail -n 1 <<<"$response")
printf "***Url: %s\n\n" "$LINE"
printf "Status: %s\n\n" "$http_code"
printf "Size: %s\n\n" "$size_header"
printf "Redirect-url: %s\n\n" "$redirect_url"
printf "Title: %s\n\n" "$title"
# -c 20 only shows the 20 first chars from response
printf "Body: %s\n\n" "$(head -c 100 <<<"$response")"
done < "${FILE}"

如何printf "Redirect-url: 原始请求的 location: header 而不必使用 redirect_url

最佳答案

要读取服务器返回的确切 Location header 字段值,您可以使用 -i/--include选项,结合 grep

例如:

$ curl 'http://httpbin.org/redirect-to?url=http:/\example.com' -si | grep -oP 'Location: \K.*'
http:/\example.com

或者,如果您想读取所有headerscontent--write-out 变量行(根据您的脚本):

response=$(curl -H 'Cache-Control: no-cache' -s -i -k --max-time 2 --write-out '%{http_code} %{size_header} %{redirect_url} ' "$url")

# break the response in parts
headers=$(sed -n '1,/^\r$/p' <<<"$response")
content=$(sed -e '1,/^\r$/d' -e '$d' <<<"$response")
read -r http_code size_header redirect_url < <(tail -n1 <<<"$response")

# get the real Location
location=$(grep -oP 'Location: \K.*' <<<"$headers")

完全集成到您的脚本中,如下所示:

#!/bin/bash
# Usage: urls-checker.sh domains.txt
file="$1"
while read -r url; do
# read the response to a variable
response=$(curl -H 'Cache-Control: no-cache' -s -i -k --max-time 2 --write-out '%{http_code} %{size_header} %{redirect_url} ' "$url")

# break the response in parts
headers=$(sed -n '1,/^\r$/p' <<<"$response")
content=$(sed -e '1,/^\r$/d' -e '$d' <<<"$response")
read -r http_code size_header redirect_url < <(tail -n1 <<<"$response")

# get the real Location
location=$(grep -oP 'Location: \K.*' <<<"$headers")

# get the title
title=$(sed -n 's/.*<title>\(.*\)<\/title>.*/\1/ip;T;q'<<<"$content")

printf "***Url: %s\n\n" "$url"
printf "Status: %s\n\n" "$http_code"
printf "Size: %s\n\n" "$size_header"
printf "Redirect-url: %s\n\n" "$location"
printf "Title: %s\n\n" "$title"
printf "Body: %s\n\n" "$(head -c 100 <<<"$content")"
done < "$file"

关于bash - 如何使用 Curl 检索真正的重定向位置 header ?不使用 {redirect_url},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46507336/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com