简体   繁体   English

使用netcat在bash中发出http get请求

[英]Using netcat to issue a http get request in bash

I have written the following script (it does not support index yet). 我已经编写了以下脚本(尚不支持索引)。 The issue I am having is regarding using netcat to load the page. 我遇到的问题是关于使用netcat加载页面。 I can do this manually using the command line but when I try to have my script issue the exact same commands I can it does nothing without error. 我可以使用命令行手动执行此操作,但是当我尝试让脚本发出完全相同的命令时,我可以执行任何操作而不会出现错误。 The only possible thing I can think is that my output is going somewhere else? 我唯一能想到的是我的输出将输出到其他地方吗?

#!/bin/bash
PORT=80

while [ true ]
do
    echo "Type the address you wish to visit then, followed by [ENTER]:"
    read address
    path=${address#*/}
    domain=${address%%/*}
    nc $domain $PORT
    printf "GET /$path HTTP/1.1\n" 
    printf "Host: $domain\n" 
    printf "\n" 
    printf "\n" 
done

You need to pass the request header to the standard input of nc . 您需要将请求标头传递到nc的标准输入。

One way to do that is input redirection: 一种方法是输入重定向:

while true
do
    echo "Type the address you wish to visit then, followed by [ENTER]:"
    read address
    path=${address#*/}
    domain=${address%%/*}
    nc $domain $PORT <<EOF
GET /$path
Host: $domain

EOF
done

nc works by copying standard input to the given address:port, and copying whatever it reads from there to standard output. nc工作方式是将标准输入复制到给定的address:port,然后将从那里读取的所有内容复制到标准输出。

{
  printf "GET /%s HTTP/1.1\r\n" "$path"
  printf "Host: %s\r\n" "$domain"
  printf "\r\n" 
  printf "\r\n"
} | nc "$domain" "$port"
  • HTTP requires \\r\\n at the end of each line. HTTP在每行的末尾要求\\r\\n Some servers accept just \\n but some stick to the letter of the law and accept only \\r\\n as specified. 某些服务器仅接受\\n但某些服务器遵守法律规定,仅接受指定的\\r\\n

  • You need to send these lines to the standard input of nc . 您需要将这些行发送到nc的标准输入。

  • It is better to use printf "Get %s HTTP/1.1\\r\\n" "$path" because $path may contain % signs and that would confuse printf`. 最好使用printf "Get %s HTTP/1.1\\r\\n" "$path" because $ path may containsigns and that would confuse printf`。

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

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