Linux script telnet HEAD request [duplicate]

2019-06-05 13:22发布

This question already has an answer here:

So basically I'm trying to do something fairly easy; I'm trying to make a script to telnet to the microsoft server and requesting the HEAD of the page. But as expected, it doesn't work. If I just enter it manually into the console it works, but when executing the script doesn't work at all.

This is the script I made:

echo "telnet $1 $2"
sleep 10
echo "HEAD $3 HTTP/1.0"
echo
echo
sleep 2

Typing this in the console:

./gethost microsoft.com 80 /

Give this as a result:

telnet microsoft.com 80
HEAD / HTTP/1.0


And then just returns to the console after the last two empty echos, I honestly don't get it, I even increased the sleeps (for possible network delays).

2条回答
Bombasti
2楼-- · 2019-06-05 13:30

Your script just prints some stuff to stdout. It doesn't actually execute the telnet command. Try something like this:

telnet $1 $2 <<< $'HEAD $3 HTTP/1.0\r\n\r\n'

This will run telnet instead of just printing the command out. It also feeds in the HEAD command on stdin. It's important to send \r\n line endings rather than UNIX's default \n line endings, since \r\n is what the HTTP protocol requires.

See man bash for a description of the <<< operator.

查看更多
We Are One
3楼-- · 2019-06-05 13:40

You aren't actually running the telnet command anywhere. You just echo it to the screen.

Drop the echo from that line.

That being said that won't work either because you don't get an interactive telnet session in a script that way.

You might be able to pipe input to telnet to give it strings to send to the remove host but I'm not sure.

You can use something like netcat/nc instead of telnet for this (which is likely a good idea anyway) as they definitely can take input via a pipe.

You could also just use a tool built for this like curl (curl -I).

查看更多
登录 后发表回答