18.6. Simulating Telnet from a ProgramProblemYou 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. SolutionUse 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
Give the
Another important option 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.
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 $telnet = Net::Telnet->new( Errmode => sub { main::log(@_) }, ... );
The $telnet->login($username, $password) or die "Login failed: @{[ $telnet->errmsg() ]}\n";
To run a program and gather its output, use the
You can separate the sending of the command from the reception of its output with the $telnet->waitfor('/--more--/')
or named arguments. $telnet->waitfor(String => 'greasy smoke', Timeout => 30)
In scalar context, See AlsoThe documentation for the Net::Telnet module from CPAN; RFCs 854-856, as amended by later RFCs |
|