Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
In this short tutorial, we’ll discuss different ways to automate telnet sessions using the expect command.
The expect program provides a means of automating interactive programs. It’s able to call one or more programs, emulating a user operating them through a standard terminal.
expect also provides a special language, allowing us to script the dialogue with the controlled programs. In general, programs will be centered around the idea of sending inputs and waiting for specific outputs to/from the controlled programs.
Next, we’ll discuss examples of how to use expect to automate telnet sessions.
telnet has been largely superseded by the more secure ssh as the preferred protocol for remote host connections.
However, telnet presents some advantages. For instance, it’s a lightweight protocol suitable for low-powered devices. Moreover, within secured networks, the gains provided by more secure protocols may be marginal.
In the script below, expect calls telnet to log into a host automatically:
#!/usr/bin/expect
set timeout 5
set host [lindex $argv 0]
set port [lindex $argv 1]
set login [lindex $argv 2]
set password [lindex $argv 3]
spawn telnet $host $port
expect "login: "
send "$login\r"
expect "password: "
send "$password\r"
interact
Now, let’s analyze the above script:
Here’s how we can invoke the script:
$ ./automate-telnet.sh localhost 23 myusername mypassword
When connecting to ports other than 23, telnet assumes it isn’t connecting with a telnet server. Then, it won’t attempt to perform the regular protocol negotiations. This allows us to use telnet as a general-purpose TCP/IP client to interact with servers using arbitrary protocols.
In the example below, expect invokes a telnet process to establish an HTTP connection to the www.example.com host:
#!/usr/bin/expect
set timeout 5
spawn telnet www.example.com 80
expect "Connected"
send "GET /index.html HTTP/1.1\r"
send "Host: www.example.com\r\r"
expect "</html>"
Firstly, the expect script will wait for the “Connected” string (a sign that telnet could establish a connection). Then, it transmits a simple GET request and waits for the string “</html>”, signaling the end of the HTML output.
In this short article, we’ve discussed possibilities for automating telnet sessions using expect scripts.