Automating telnet session using bash scripts
While I'd suggest using expect
, too, for non-interactive use the normal shell commands might suffice. telnet
accepts its command on stdin, so you just need to pipe or write the commands into it through heredoc:
telnet 10.1.1.1 <<EOFremotecommand 1remotecommand 2EOF
(Edit: Judging from the comments, the remote command needs some time to process the inputs or the early SIGHUP is not taken gracefully by telnet
. In these cases, you might try a short sleep on the input:)
{ echo "remotecommand 1"; echo "remotecommand 2"; sleep 1; } | telnet 10.1.1.1
In any case, if it's getting interactive or anything, use expect
.
Write an expect
script.
Here is an example:
#!/usr/bin/expect#If it all goes pear shaped the script will timeout after 20 seconds.set timeout 20#First argument is assigned to the variable nameset name [lindex $argv 0]#Second argument is assigned to the variable userset user [lindex $argv 1]#Third argument is assigned to the variable passwordset password [lindex $argv 2]#This spawns the telnet program and connects it to the variable namespawn telnet $name #The script expects loginexpect "login:" #The script sends the user variablesend "$user "#The script expects Passwordexpect "Password:"#The script sends the password variablesend "$password "#This hands control of the keyboard over to you (Nice expect feature!)interact
To run:
./myscript.expect name user password
Telnet is often used when you learn HTTP protocol. I used to use that script as a part of my web-scraper:
echo "open www.example.com 80" sleep 2 echo "GET /index.html HTTP/1.1" echo "Host: www.example.com" echo echo sleep 2
let's say the name of the script is get-page.sh then:
get-page.sh | telnet
will give you a html document.
Hope it will be helpful to someone ;)