bash/shell 스크립트에서 http 응답 코드를 평가하는 방법
것을 있는 것 느낌이 들지만, 하지 못했습니다.man [curl|wget]또는 구글('blad'는 매우 나쁜 검색어를 만듭니다).자주 장애가 발생하여 오류 메시지와 함께 상태 코드 500을 반환하는 웹 서버 중 하나에 대한 빠르고 더러운 수정을 찾고 있습니다.이 경우는, 재기동할 필요가 있습니다.
근본 원인을 찾는 것은 어려울 것 같기 때문에, 정말로 해결할 수 있을 때까지의 시간을 메우는 것으로 충분할 것으로 기대하면서, 신속한 해결을 목표로 하고 있습니다(서비스는 고가용성이 필요 없습니다).
권장되는 솔루션은 5분마다 실행되는 cron 작업을 생성하여 http://localhost:8080/을 확인하는 것입니다.상태 코드 500이 반환되면 웹 서버가 재시작됩니다.서버는 1분 이내에 재시작되므로 재시작이 이미 실행 중인지 확인할 필요가 없습니다.
문제의 서버는 ubuntu 8.04 최소 설치로 현재 필요한 것을 실행하기에 충분한 패키지만 설치되어 있습니다.bash에서 작업을 하기 위한 어려운 요건은 없지만, 더 이상 인터프리터를 설치하지 않고 최소한의 환경에서 작업을 수행했으면 합니다.
(http 상태 코드를 환경변수에 할당하는 명령/옵션으로 충분할 정도로 스크립팅에 익숙합니다.이것이 제가 찾았지만 찾을 수 없었습니다.)
500 코드로 테스트한 적은 없지만 200, 302, 404와 같은 다른 코드에서는 동작합니다.
response=$(curl --write-out '%{http_code}' --silent --output /dev/null servername)
로 묶어야 write-out은 따옴표로 묶어야 . @ibai를 합니다.--headHEAD head head ★★★★★★★★★★★★★★★★★★★.이렇게 하면 페이지 내용이 전송되지 않으므로 검색에 성공했을 때 시간이 절약됩니다.
오늘 빨리 데모를 해야 돼서 이걸 생각해 냈어요.작전본부의 요청과 비슷한 것이 필요하면 여기에 놓아두려고 합니다.
#!/bin/bash
status_code=$(curl --write-out %{http_code} --silent --output /dev/null www.bbc.co.uk/news)
if [[ "$status_code" -ne 200 ]] ; then
echo "Site status changed to $status_code" | mail -s "SITE STATUS CHECKER" "my_email@email.com" -r "STATUS_CHECKER"
else
exit 0
fi
그러면 200에서 모든 상태 변경에 대해 이메일 경고가 전송되므로 어리석고 잠재적으로 탐욕스러울 수 있습니다.이를 개선하기 위해 여러 상태 코드를 루프하여 결과에 따라 다른 작업을 수행하는 방법을 검토하겠습니다.
curl --write-out "%{http_code}\n" --silent --output /dev/null "$URL"
동작하지 않는 경우는, 리턴 키를 눌러 코드 자체를 표시할 필요가 있습니다.
받아들여진 응답은 좋은 답변이지만 장애 시나리오는 간과됩니다. curl000요청에 오류가 있거나 연결 장애가 있는 경우.
url='http://localhost:8080/'
status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == 500 ]] || [[ $status == 000 ]] && echo restarting ${url} # do start/restart logic
한 것을 합니다.500 curl할 수 ( 반환됩니다).000를 참조해 주세요.
여기서 함수를 만듭니다.
failureCode() {
local url=${1:-http://localhost:8080}
local code=${2:-500}
local status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == ${code} ]] || [[ $status == 000 ]]
}
" " " " " " 를 얻는 500:
failureCode http://httpbin.org/status/500 && echo need to restart
/접속 에러 테스트 「」/「」)000
failureCode http://localhost:77777 && echo need to start
a a " " " " A " " " "500:
failureCode http://httpbin.org/status/400 || echo not a failure
다음은 이전 답변보다 좀 더 상세하게 설명한 구현입니다.
curl https://somewhere.com/somepath \
--silent \
--insecure \
--request POST \
--header "your-curl-may-want-a-header" \
--data @my.input.file \
--output site.output \
--write-out %{http_code} \
> http.response.code 2> error.messages
errorLevel=$?
httpResponse=$(cat http.response.code)
jq --raw-output 'keys | @csv' site.output | sed 's/"//g' > return.keys
hasErrors=`grep --quiet --invert errors return.keys;echo $?`
if [[ $errorLevel -gt 0 ]] || [[ $hasErrors -gt 0 ]] || [[ "$httpResponse" != "200" ]]; then
echo -e "Error POSTing https://somewhere.com/somepath with input my.input (errorLevel $errorLevel, http response code $httpResponse)" >> error.messages
send_exit_message # external function to send error.messages to whoever.
fi
netcat 및 awk를 사용하면 서버 응답을 수동으로 처리할 수 있습니다.
if netcat 127.0.0.1 8080 <<EOF | awk 'NR==1{if ($2 == "500") exit 0; exit 1;}'; then
GET / HTTP/1.1
Host: www.example.com
EOF
apache2ctl restart;
fi
모든 요청에 대해 3XX 방향 수정 및 응답 코드를 인쇄하려면 다음 절차를 따릅니다.
HTTP_STATUS="$(curl -IL --silent example.com | grep HTTP )";
echo "${HTTP_STATUS}";
데이터와 상태가 뒤섞인 답변이 마음에 들지 않았어요이것을 발견: -f 플래그를 추가하여 컬이 실패하도록 하고 표준 상태 변수에서 오류 상태 코드를 선택합니다: $?
https://unix.stackexchange.com/questions/204762/return-code-for-curl-used-in-a-command-substitution
모든 시나리오에 적합한지는 모르겠지만 제 요구에 맞는 것 같고 작업도 훨씬 편하다고 생각합니다.
이것은 http 상태를 평가하는 데 도움이 됩니다.
var=`curl -I http://www.example.org 2>/dev/null | head -n 1 | awk -F" " '{print $2}'`
echo http:$var
또 다른 변형:
status=$(curl -sS -I https://www.healthdata.gov/user/login 2> /dev/null | head -n 1 | cut -d' ' -f2)
status_w_desc=$(curl -sS -I https://www.healthdata.gov/user/login 2> /dev/null | head -n 1 | cut -d' ' -f2-)
여기에 제시된 대로 응답 헤더만 요구하고 IFS를 사용하지 않는 netherobot 솔루션에서 영감을 얻어 장황하면서도 이해하기 쉬운 스크립트가 등장합니다.> = 400이라는 응답이 있을 때 바운스 메시지를 출력합니다.이 에코를 바운스 스크립트로 대체할 수 있습니다.
# set the url to probe
url='http://localhost:8080'
# use curl to request headers (return sensitive default on timeout: "timeout 500"). Parse the result into an array (avoid settings IFS, instead use read)
read -ra result <<< $(curl -Is --connect-timeout 5 "${url}" || echo "timeout 500")
# status code is second element of array "result"
status=${result[1]}
# if status code is greater than or equal to 400, then output a bounce message (replace this with any bounce script you like)
[ $status -ge 400 ] && echo "bounce at $url with status $status"
위의 @DennisWilliamson 코멘트에 추가하려면:
@VaibhavBajpai:response=$(response --write-output \n%{response_code} --response --output - servername) - 결과의 마지막 줄이 응답 코드가 됩니다.
다음으로 다음과 같은 것을 사용하여 응답에서 응답 코드를 해석할 수 있습니다.여기서 X는 응답의 끝을 나타내는 정규식을 나타냅니다(여기에서는 json 예를 사용합니다).
X='*\}'
code=$(echo ${response##$X})
서브스트링의 삭제」를 참조해 주세요.
- 응용 프로그램에 Stop and Start 스크립트를 이미 구현했다고 가정합니다.응용 프로그램 URL의 http 상태를 확인하고 502의 경우 재시작하는 스크립트를 다음과 같이 만듭니다.
httpStatusCode=$(curl - s - o / dev / w % { deb / w % { { your _ url } / ) [ $ httpStatusCode = 502 ]의 경우 sh / { path _ to _ folder } / stopscript 。sh /{path_to_folder}/startscript.sh fi
- cron 작업을 구현하여 5분마다 이 스크립트를 호출합니다.위의 스크립트의 이름이 checkBootAndRestart.sh인 경우.그럼 네 크론탭은...
*/5 * * * * /{path_to_folder}/checkBootAndRestart.sh
언급URL : https://stackoverflow.com/questions/2220301/how-to-evaluate-http-response-codes-from-bash-shell-script
'programing' 카테고리의 다른 글
| C# - Excel 워크시트를 프로그래밍 방식으로 추가하는 방법 - Office XP / 2003 (0) | 2023.04.19 |
|---|---|
| 프레임워크가 있는 iOS 앱이 장치에서 크래시됨, dyld: 라이브러리가 로드되지 않음, Xcode 6 베타 (0) | 2023.04.19 |
| UITableView셀을 선택한 색상? (0) | 2023.04.19 |
| Dockerfile에서 도커 컨테이너의 Bash 별칭을 설정하려면 어떻게 해야 합니까? (0) | 2023.04.19 |
| Git 브랜치를 로컬 및 원격으로 삭제하려면 어떻게 해야 합니까? (0) | 2023.04.19 |