Book HomePerl CookbookSearch this book

18.6. 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 prompts. If the prompt on the remote machine doesn't match the default pattern, you have to specify your own. Remember to include the slashes.

Timeout lets you control how long (in seconds) network operations wait before they give up. The default is 10 seconds.

If an error or timeout occurs in the Net::Telnet module, the default behavior is to raise an exception, which, if uncaught, prints a message to STDERR and exits. To change this, pass a subroutine reference to new in the Errmode argument. If instead of a code subroutine, you specify the string "return" as the Errmode, methods return undef (in scalar context) or an empty list (in list context) on error, with the error message available via the errmsg method:

$telnet = Net::Telnet->new( Errmode => sub { main::log(@_) }, ... );

The login method is used to send a username and password to the remote machine. It uses the Prompt to decide when the login is complete and times out if the machine doesn't reply with a prompt:

$telnet->login($username, $password)
    or die "Login failed: @{[ $telnet->errmsg() ]}\n";

To run a program and gather its output, use the cmd method. Pass it the string to send, and it returns the output of the command. In list context, it returns one line per list element. In scalar context, it returns one long line. It waits for the Prompt before returning.

You can separate the sending of the command from the reception of its output with the print and waitfor methods, as we do in the Solution. The waitfor method takes either a single string containing a Perl regular expression match operator:

$telnet->waitfor('/--more--/')

or named arguments. Timeout lets you specify a timeout to override the default, Match is a string containing a match operator as above, and String is a literal string to find:

$telnet->waitfor(String => 'greasy smoke', Timeout => 30)

In scalar context, waitfor returns true if the pattern or string was found. If it is not found, the Errmode action is performed. In list context, it returns two strings: all the text before the match, and the text that matched.

See Also

The documentation for the Net::Telnet module from CPAN; RFCs 854-856, as amended by later RFCs


Previous: 18.5. Reading Mail with POP3Perl CookbookNext: 18.7. Pinging a Machine
18.5. Reading Mail with POP3Book Index18.7. Pinging a Machine

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.