简体   繁体   English

如何通过 bash 脚本使用 netcat 获取 http 状态代码

[英]how to get http status code with netcat via bash script

I have to write a bash script that has to include these conditions.我必须编写一个必须包含这些条件的 bash 脚本。 I am newbee can you give me an advise please?我是新手,请给我一个建议好吗?

This script runs with "command and [parameter]".此脚本使用“命令和 [参数]”运行。 I give it to domain as a variable and script has to get this variable's status code with "nc" (I have not use cURL).我将它作为变量提供给域,脚本必须使用“nc”获取此变量的状态代码(我没有使用 cURL)。 If the status code is 200 (only), bash script print OK, otherwise script should exit with status code 7 without any prints words on screen.如果状态码为 200(仅),则 bash 脚本打印正常,否则脚本应以状态码 7 退出,屏幕上没有任何打印字样。

I wrote this but when I use variables I am not able to get any result.我写了这个,但是当我使用变量时,我无法得到任何结果。

1-) this works (this is without variable, I know google responses 301 so I wrote grep 301) 1-)这个工作(这是没有变量,我知道谷歌响应301所以我写了grep 301)

#!/bin/bash

        STATUS=`printf 'GET / HTTP/1.1\r\nHost: google.com\r\n\r\n' | nc google.com 80 | awk '{print $2}' | grep '301'`
                if [ "$STATUS" -eq 301  ]; then
                echo "OK"
                else
                exit 7
                fi

2-) this is not work - please help me improve this script. 2-) 这不起作用 - 请帮我改进这个脚本。 I have to write with nc command to get response code and compare with 200.我必须用 nc 命令编写以获取响应代码并与 200 进行比较。

#!/bin/bash

DOMAIN=google.com

        STATUS=`printf 'GET / HTTP/1.1\r\nHost: "$DOMAIN"\r\n\r\n' | nc "$DOMAIN" 80 | awk '{print $2}' | grep '301'`
                if [ "$STATUS" ]; then
                        echo "OK"
                else
                        exit 7
                fi

If have put together a small script.如果已经整理了一个小脚本。 Hope that helps.希望有帮助。 PLEASE test before your production use:)请在生产使用前进行测试:)

STATUS=$(printf "HEAD / HTTP/1.1\r\nUser-Agent: nc/0.0.1\r\nHost: $1\r\nAccept: */*\r\n\r\n" | nc $1 80 | sed -n 's/HTTP.* \(.*\) .*/\1/p' |grep $2)

if [ $? -eq 0 ]; then
  echo OK
else
  exit 7
fi

Your print command will work likewise:您的print命令将同样工作:

STATUS=$(printf "HEAD / HTTP/1.1\r\nUser-Agent: nc/0.0.1\r\nHost: $1\r\nAccept: */*\r\n\r\n" | nc $1 80 | awk '{print $2}' |grep $2)

The grep in the way you are using it will print 200. That means we have to check in the if block against an actual value.您使用的 grep 将打印 200。这意味着我们必须根据实际值检查 if 块。

I am checking the last exit code.我正在检查最后一个退出代码。 If the grep command was successful - means it has found 200 in the HTTP response code - the exit code will be 0.如果 grep 命令成功 - 意味着它在 HTTP 响应代码中找到了 200 - 退出代码将为 0。

I am issuing the script like ./demo.sh nginx.org 200我正在发布类似./demo.sh nginx.org 200的脚本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM