For循环和配置,包括Curl命令



我试图写一个脚本,我通过检查HTTP响应长度枚举用户。当响应不等于23时,我想得到输出"好",但是我现在得到这些错误:

for ((i=113;i<=115;i++)); do
  if [[curl -i -s -k  -X 'GET' "http://myurl/some.asp?q=$i" |
       grep Content-Length | cut -d' ' -f2 != 23]]
  then
       echo "good"
  fi
done
输出:

bash: [[curl: command not found
cut: !=: No such file or directory
cut: 23]]: No such file or directory
cut: !=: No such file or directory
cut: 23]]: No such file or directory
bash: [[curl: command not found
cut: !=: No such file or directory
cut: 23]]: No such file or directory
bash: [[curl: command not found

如果我简单地制作一个没有If条件的脚本,那么它工作得很好:

for ((i=113;i<=115;i++)); do
    curl -i -s -k  -X 'GET' "http://myurl/some.asp?q=$i" |
    grep Content-Length
done

我检查了很多例子,但似乎不能找出我做错了什么。

在更新你的初始错误之后,你可能会有这样的语法(建议:在格式上花些精力,这样更清楚你有什么,什么可能是错的):

for ((i=113;i<=115;i++))
do
    if [[ curl -i -s -k  -X 'GET' "http://myurl/some.asp?q=$i" | grep Content-Length | cut -d' ' -f2 != 23 ]]
    then
        echo "good"
    fi
done

返回错误:

bash:有条件的二进制操作符我' '

这很正常,因为你基本上是在说:

if [[ command ]]; then ...

其中command为多管道命令的集合。然而,在[[中,您只能在"$var" -eq 23"$(command)" -ne 23的形式上添加表达式。

所以使用$( )来执行命令:if [[ "$(command)" -ne 23 ]]:

if [[ "$(curl -i -s -k  -X 'GET' "http://myurl/some.asp?q=$i" | grep Content-Length | cut -d' ' -f2)" -ne 23 ]]

注意,我使用-ne来执行一个整数比较,意思是"不等于"。

最后,注意awk单独可以完成grepcut分两步完成的任务:

... | grep "Content-Length" | cut -d' ' -f2

这意味着:检查包含"Content-Length"的行并打印它的第二个字段。awk简单地说:

... | awk '/Content-Length/ {print $2}'

最后,但并非最不重要的是,表达式for ((i=113;i<=115;i++))也可以使用大括号展开写成for i in {113..115}

如果要测试命令执行的结果,应该将其放入$()中。因此生成的脚本应该如下所示:

for i in {113..115}; do if [[ $(curl -i -s -k  -X 'GET' "http://myurl/some.asp?q=$i" | grep Content-Length | cut -d' ' -f2) != 23 ]]; then echo "good" ; fi; done

我也改变了你迭代值的方式。{一个. .bash中的B}提供了一个从'a'到' B '的序列。

最新更新