Feeding contents of a text file as command to telnet

With the command telnet docs.python.org 80, I can do a manual HTTP request to http://docs.python.org/2/license.html, by typing the actual request.

Now, instead of typing it in live, I'd like to feed the request from a text file.

I tried this:

cat request.txt|telnet docs.python.org 80


request.txt:

GET /2/license.html HTTP/1.1 
Host: docs.python.org

(You have to finish the file with a blank line or you'll get a bad request!)


But the connection to the server is closed immediately.

How should I properly pipe request.txt to telnet docs.python.org 80?


edit:

It's good to know; if you use HEAD instead of GET, you will get the same response as if you did a GET request, except for the message body.
So, use HEAD if you just want to examine the HTTP headers. (i.e. So that the contents of the response doesn't clutter your shell output.)


Solution 1:

Use netcat (nc command) rather then "telnet", so

cat request.txt | nc docs.python.org 80

Telnet is a quick and easy hack, but netcat is, apparently, the correct tool for the job.

Solution 2:

I don't really have any experience with telnet but it does take input from file redirection:

telnet < abc.txt

I can get it to connect to the server correctly as follows:

$ cat abc.txt
open docs.python.org 80
$ telnet < abc.txt
telnet> Trying 82.94.164.162...
Connected to dinsdale.python.org.
Escape character is '^]'.
Connection closed by foreign host.

Perhaps you can figure out how to get it to accept the GET command but I couldn't. An alternative is to use an expect script:

#!/usr/bin/expect

spawn telnet docs.python.org 80
expect "Escape character is '^]'." { 
     send "GET /2/license.html HTTP/1.1\nHost: docs.python.org\n\n" 
}
interact

You can then save the script as telnet.exp,make it executable and run it:

./telnet.exp > output.html