Simulating Telnet from a Program

Problem

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.

Solution

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");
$t->print("top");
(undef, $process_string) = $t->waitfor('/\d+ processes/');
$t->close;

Discussion

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.