Simulating Telnet from a Program


You want to simulate a telnet connection from your program by logging into a remote machine, issuing commands, and reacting to what is sent. This has many applications, from automating tasks on machines you can telnet to but which don’t support scripting or rsh, to simply testing whether a machine’s telnet daemon is still running.


Use the CPAN module Net::Telnet:

use Net::Telnet;

$t = Net::Telnet->new( Timeout => 10,
                       Prompt  => '/%/',
                       Host    => $hostname );

$t->login($username, $password);
@files = $t->cmd("ls");
(undef, $process_string) = $t->waitfor('/\d+ processes/');


Net::Telnet provides an object-oriented interface to the telnet protocol. Create a connection with Net::Telnet->new, and then interact with the remote machine using method calls on the resulting object.

Give the new method named parameters, passed in hash-like form. We’ll only cover only a few of many possible parameters. The most important is Host, the machine you’re telnetting to. The default host is localhost. If you want to telnet to a port other than one telnet normally uses, specify this in the Port option. Error handling is done through the function whose reference is specified in the Errmode parameter.

Another important option is Prompt. When you log in or run a command, Net::Telnet uses the Prompt pattern to determine when the login or command has completed. The default Prompt is:

/[\$%#>] $/

which matches the common shell ...

Get Perl Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.