1Net::Telnet(3)        User Contributed Perl Documentation       Net::Telnet(3)
2
3
4

NAME

6       Net::Telnet - interact with TELNET port or other TCP ports
7

SYNOPSIS

9       "use Net::Telnet ();"
10
11       see METHODS or EXAMPLES sections below
12

DESCRIPTION

14       Net::Telnet allows you to make client connections to a TCP port and do
15       network I/O, especially to a port using the TELNET protocol.  Simple
16       I/O methods such as print, get, and getline are provided.  More
17       sophisticated interactive features are provided because connecting to a
18       TELNET port ultimately means communicating with a program designed for
19       human interaction.  These interactive features include the ability to
20       specify a time-out and to wait for patterns to appear in the input
21       stream, such as the prompt from a shell.  IPv6 support is available
22       when using perl 5.14 or later, see "family()".
23
24       Other reasons to use this module than strictly with a TELNET port are:
25
26       • You're not familiar with sockets and you want a simple way to make
27         client connections to TCP services.
28
29       • You want to be able to specify your own time-out while connecting,
30         reading, or writing.
31
32       • You're communicating with an interactive program at the other end of
33         some socket or pipe and you want to wait for certain patterns to
34         appear.
35
36       Here's an example that prints who's logged-on to a remote host.  In
37       addition to a username and password, you must also know the user's
38       shell prompt, which for this example is "bash$ "
39
40           use Net::Telnet ();
41           $t = new Net::Telnet (Timeout => 10,
42                                 Prompt => '/bash\$ $/');
43           $t->open($host);
44           $t->login($username, $passwd);
45           @lines = $t->cmd("who");
46           print @lines;
47
48       See the EXAMPLES section below for more examples.
49
50       Usage questions should be directed to the perlmonks.org discussion
51       group.  Bugs can be viewed or reported at cpan.org on the Net::Telnet
52       page.
53
54   What To Know Before Using
55       • All output is flushed while all input is buffered.  Each object
56         contains its own input buffer.
57
58       • The output record separator for "print()" and "cmd()" is set to "\n"
59         by default, so that you don't have to append all your commands with a
60         newline.  To avoid printing a trailing "\n" use "put()" or set the
61         output_record_separator to "".
62
63       • The methods "login()" and "cmd()" use the prompt setting in the
64         object to determine when a login or remote command is complete.
65         Those methods will fail with a time-out if you don't set the prompt
66         correctly.
67
68       • Use a combination of "print()" and "waitfor()" as an alternative to
69         "login()" or "cmd()" when they don't do what you want.
70
71       • Errors such as timing-out are handled according to the error mode
72         action.  The default action is to print an error message to standard
73         error and have the program die.  See the "errmode()" method for more
74         information.
75
76       • When constructing the match operator argument for "prompt()" or
77         "waitfor()", always use single quotes instead of double quotes to
78         avoid unexpected backslash interpretation (e.g. '/bash\$ $/').  If
79         you're constructing a DOS like file path, you'll need to use four
80         backslashes to represent one (e.g. '/c:\\\\users\\\\bill>$/i').
81
82         Of course don't forget about regexp metacharacters like ".", "[", or
83         "$".  You'll only need a single backslash to quote them.  The anchor
84         metacharacters "^" and "$" refer to positions in the input buffer.
85         To avoid matching characters read that look like a prompt, it's a
86         good idea to end your prompt pattern with the "$" anchor.  That way
87         the prompt will only match if it's the last thing read.
88
89       • In the input stream, each sequence of carriage return and line feed
90         (i.e. "\015\012" or CR LF) is converted to "\n".  In the output
91         stream, each occurrence of "\n" is converted to a sequence of CR LF.
92         See "binmode()" to change the behavior.  TCP protocols typically use
93         the ASCII sequence, carriage return and line feed to designate a
94         newline.
95
96       • Timing-out while making a connection is disabled for machines that
97         don't support the "alarm()" function.  Most notably these include MS-
98         Windows machines.
99
100       • You'll need to be running at least Perl version 5.002 to use this
101         module.  This module does not require any libraries that don't
102         already come with a standard Perl distribution.
103
104         If you have the IO:: libraries installed (they come standard with
105         perl5.004 and later) then IO::Socket::INET is used as a base class,
106         otherwise FileHandle is used.
107
108   Debugging
109       The typical usage bug causes a time-out error because you've made
110       incorrect assumptions about what the remote side actually sends.  The
111       easiest way to reconcile what the remote side sends with your
112       expectations is to use "input_log()" or "dump_log()".
113
114       "dump_log()" allows you to see the data being sent from the remote side
115       before any translation is done, while "input_log()" shows you the
116       results after translation.  The translation includes converting end of
117       line characters, removing and responding to TELNET protocol commands in
118       the data stream.
119
120   Style of Named Parameters
121       Two different styles of named parameters are supported.  This document
122       only shows the IO:: style:
123
124           Net::Telnet->new(Timeout => 20);
125
126       however the dash-option style is also allowed:
127
128           Net::Telnet->new(-timeout => 20);
129
130   Connecting to a Remote MS-Windows Machine
131       By default MS-Windows doesn't come with a TELNET server.  However third
132       party TELNET servers are available.  Unfortunately many of these
133       servers falsely claim to be a TELNET server.  This is especially true
134       of the so-called "Microsoft Telnet Server" that comes installed with
135       some newer versions MS-Windows.
136
137       When a TELNET server first accepts a connection, it must use the ASCII
138       control characters carriage-return and line-feed to start a new line
139       (see RFC854).  A server like the "Microsoft Telnet Server" that doesn't
140       do this, isn't a TELNET server.  These servers send ANSI terminal
141       escape sequences to position to a column on a subsequent line and to
142       even position while writing characters that are adjacent to each other.
143       Worse, when sending output these servers resend previously sent command
144       output in a misguided attempt to display an entire terminal screen.
145
146       Connecting Net::Telnet to one of these false TELNET servers makes your
147       job of parsing command output very difficult.  It's better to replace a
148       false TELNET server with a real TELNET server.  The better TELNET
149       servers for MS-Windows allow you to avoid the ANSI escapes by turning
150       off something some of them call console mode.
151

METHODS

153       In the calling sequences below, square brackets [] represent optional
154       parameters.
155
156       new - create a new Net::Telnet object
157               $obj = new Net::Telnet ([$host]);
158
159               $obj = new Net::Telnet ([Binmode    => $mode,]
160                                       [Cmd_remove_mode => $mode,]
161                                       [Dump_Log   => $filename,]
162                                       [Errmode    => $errmode,]
163                                       [Family     => $family,]
164                                       [Fhopen     => $filehandle,]
165                                       [Host       => $host,]
166                                       [Input_log  => $file,]
167                                       [Input_record_separator => $chars,]
168                                       [Localfamily => $family,]
169                                       [Localhost   => $host,]
170                                       [Max_buffer_length => $len,]
171                                       [Ofs        => $chars,]
172                                       [Option_log => $file,]
173                                       [Ors        => $chars,]
174                                       [Output_field_separator => $chars,]
175                                       [Output_log => $file,]
176                                       [Output_record_separator => $chars,]
177                                       [Port       => $port,]
178                                       [Prompt     => $matchop,]
179                                       [Rs         => $chars,]
180                                       [Telnetmode => $mode,]
181                                       [Timeout    => $secs,]);
182
183           This is the constructor for Net::Telnet objects.  A new object is
184           returned on success, the error mode action is performed on failure
185           - see "errmode()".  The optional arguments are short-cuts to
186           methods of the same name.
187
188           If the $host argument is given then the object is opened by
189           connecting to TCP $port on $host.  Also see "open()".  The new
190           object returned is given the following defaults in the absence of
191           corresponding named parameters:
192
193           •   The default Host is "localhost"
194
195           •   The default Port is 23
196
197           •   The default Family is "ipv4"
198
199           •   The default Prompt is '/[\$%#>] $/'
200
201           •   The default Timeout is 10
202
203           •   The default Errmode is "die"
204
205           •   The default Output_record_separator is "\n".  Note that Ors is
206               synonymous with Output_record_separator.
207
208           •   The default Input_record_separator is "\n".  Note that Rs is
209               synonymous with Input_record_separator.
210
211           •   The default Binmode is 0, which means do newline translation.
212
213           •   The default Telnetmode is 1, which means respond to TELNET
214               commands in the data stream.
215
216           •   The default Cmd_remove_mode is "auto"
217
218           •   The defaults for Dump_log, Input_log, Option_log, and
219               Output_log are "", which means that logging is turned-off.
220
221           •   The default Max_buffer_length is 1048576 bytes, i.e. 1 MiB.
222
223           •   The default Output_field_separator is "".  Note that Ofs is
224               synonymous with Output_field_separator.
225
226           •   The default Localhost is ""
227
228           •   The default Localfamily is "ipv4"
229
230       binmode - toggle newline translation
231               $mode = $obj->binmode;
232
233               $prev = $obj->binmode($mode);
234
235           This method controls whether or not sequences of carriage returns
236           and line feeds (CR LF or more specifically "\015\012") are
237           translated.  By default they are translated (i.e. binmode is 0).
238
239           If no argument is given, the current mode is returned.
240
241           If $mode is 1 then binmode is on and newline translation is not
242           done.
243
244           If $mode is 0 then binmode is off and newline translation is done.
245           In the input stream, each sequence of CR LF is converted to "\n"
246           and in the output stream, each occurrence of "\n" is converted to a
247           sequence of CR LF.
248
249           Note that input is always buffered.  Changing binmode doesn't
250           effect what's already been read into the buffer.  Output is not
251           buffered and changing binmode will have an immediate effect.
252
253       break - send TELNET break character
254               $ok = $obj->break;
255
256           This method sends the TELNET break character.  This character is
257           provided because it's a signal outside the ASCII character set
258           which is currently given local meaning within many systems.  It's
259           intended to indicate that the Break Key or the Attention Key was
260           hit.
261
262           This method returns 1 on success, or performs the error mode action
263           on failure.
264
265       buffer - scalar reference to object's input buffer
266               $ref = $obj->buffer;
267
268           This method returns a scalar reference to the input buffer for
269           $obj.  Data in the input buffer is data that has been read from the
270           remote side but has yet to be read by the user.  Modifications to
271           the input buffer are returned by a subsequent read.
272
273       buffer_empty - discard all data in object's input buffer
274               $obj->buffer_empty;
275
276           This method removes all data in the input buffer for $obj.
277
278       close - close object
279               $ok = $obj->close;
280
281           This method closes the socket, file, or pipe associated with the
282           object.  It always returns a value of 1.
283
284       cmd - issue command and retrieve output
285               $ok = $obj->cmd($string);
286               $ok = $obj->cmd(String   => $string,
287                               [Output  => $ref,]
288                               [Cmd_remove_mode => $mode,]
289                               [Errmode => $mode,]
290                               [Input_record_separator => $chars,]
291                               [Ors     => $chars,]
292                               [Output_record_separator => $chars,]
293                               [Prompt  => $match,]
294                               [Rs      => $chars,]
295                               [Timeout => $secs,]);
296
297               @output = $obj->cmd($string);
298               @output = $obj->cmd(String   => $string,
299                                   [Output  => $ref,]
300                                   [Cmd_remove_mode => $mode,]
301                                   [Errmode => $mode,]
302                                   [Input_record_separator => $chars,]
303                                   [Ors     => $chars,]
304                                   [Output_record_separator => $chars,]
305                                   [Prompt  => $match,]
306                                   [Rs      => $chars,]
307                                   [Timeout => $secs,]);
308
309           This method sends the command $string, and reads the characters
310           sent back by the command up until and including the matching
311           prompt.  It's assumed that the program to which you're sending is
312           some kind of command prompting interpreter such as a shell.
313
314           The command $string is automatically appended with the
315           output_record_separator, by default it is "\n".  This is similar to
316           someone typing a command and hitting the return key.  Set the
317           output_record_separator to change this behavior.
318
319           In a scalar context, the characters read from the remote side are
320           discarded and 1 is returned on success.  On time-out, eof, or other
321           failures, the error mode action is performed.  See "errmode()".
322
323           In a list context, just the output generated by the command is
324           returned, one line per element.  In other words, all the characters
325           in between the echoed back command string and the prompt are
326           returned.  If the command happens to return no output, a list
327           containing one element, the empty string is returned.  This is so
328           the list will indicate true in a boolean context.  On time-out,
329           eof, or other failures, the error mode action is performed.  See
330           "errmode()".
331
332           The characters that matched the prompt may be retrieved using
333           "last_prompt()".
334
335           Many command interpreters echo back the command sent.  In most
336           situations, this method removes the first line returned from the
337           remote side (i.e. the echoed back command).  See
338           "cmd_remove_mode()" for more control over this feature.
339
340           Use "dump_log()" to debug when this method keeps timing-out and you
341           don't think it should.
342
343           Consider using a combination of "print()" and "waitfor()" as an
344           alternative to this method when it doesn't do what you want, e.g.
345           the command you send prompts for input.
346
347           The Output named parameter provides an alternative method of
348           receiving command output.  If you pass a scalar reference, all the
349           output (even if it contains multiple lines) is returned in the
350           referenced scalar.  If you pass an array or hash reference, the
351           lines of output are returned in the referenced array or hash.  You
352           can use "input_record_separator()" to change the notion of what
353           separates a line.
354
355           Optional named parameters are provided to override the current
356           settings of cmd_remove_mode, errmode, input_record_separator, ors,
357           output_record_separator, prompt, rs, and timeout.  Rs is synonymous
358           with input_record_separator and ors is synonymous with
359           output_record_separator.
360
361       cmd_remove_mode - toggle removal of echoed commands
362               $mode = $obj->cmd_remove_mode;
363
364               $prev = $obj->cmd_remove_mode($mode);
365
366           This method controls how to deal with echoed back commands in the
367           output returned by cmd().  Typically, when you send a command to
368           the remote side, the first line of output returned is the command
369           echoed back.  Use this mode to remove the first line of output
370           normally returned by cmd().
371
372           If no argument is given, the current mode is returned.
373
374           If $mode is 0 then the command output returned from cmd() has no
375           lines removed.  If $mode is a positive integer, then the first
376           $mode lines of command output are stripped.
377
378           By default, $mode is set to "auto".  Auto means that whether or not
379           the first line of command output is stripped, depends on whether or
380           not the remote side offered to echo.  By default, Net::Telnet
381           always accepts an offer to echo by the remote side.  You can change
382           the default to reject such an offer using "option_accept()".
383
384           A warning is printed to STDERR when attempting to set this
385           attribute to something that is not "auto" or a non-negative
386           integer.
387
388       dump_log - log all I/O in dump format
389               $fh = $obj->dump_log;
390
391               $fh = $obj->dump_log($fh);
392
393               $fh = $obj->dump_log($tiefh);
394
395               $fh = $obj->dump_log($filename);
396
397           This method starts or stops dump format logging of all the object's
398           input and output.  The dump format shows the blocks read and
399           written in a hexadecimal and printable character format.  This
400           method is useful when debugging, however you might want to first
401           try "input_log()" as it's more readable.
402
403           If no argument is given, the log filehandle is returned.  A
404           returned empty string indicates logging is off.
405
406           To stop logging, use an empty string as an argument.  The stopped
407           filehandle is not closed.
408
409           If an open filehandle is given, it is used for logging and
410           returned.  Otherwise, the argument is assumed to be the name of a
411           file, the filename is opened for logging and a filehandle to it is
412           returned.  If the filehandle is not already opened or the filename
413           can't be opened for writing, the error mode action is performed.
414           The filehandle can be a tied filehandle.
415
416       eof - end of file indicator
417               $eof = $obj->eof;
418
419           This method returns 1 if end of file has been read, otherwise it
420           returns an empty string.  Because the input is buffered this isn't
421           the same thing as $obj has closed.  In other words $obj can be
422           closed but there still can be stuff in the buffer to be read.
423           Under this condition you can still read but you won't be able to
424           write.
425
426       errmode - define action to be performed on error
427               $mode = $obj->errmode;
428
429               $prev = $obj->errmode($mode);
430
431           This method gets or sets the action used when errors are
432           encountered using the object.  The first calling sequence returns
433           the current error mode.  The second calling sequence sets it to
434           $mode and returns the previous mode.  Valid values for $mode are
435           "die" (the default), "return", a coderef, or an arrayref.
436
437           When mode is "die" and an error is encountered using the object,
438           then an error message is printed to standard error and the program
439           dies.
440
441           When mode is "return" then the method generating the error places
442           an error message in the object and returns an undefined value in a
443           scalar context and an empty list in list context.  The error
444           message may be obtained using "errmsg()".
445
446           When mode is a coderef, then when an error is encountered coderef
447           is called with the error message as its first argument.  Using this
448           mode you may have your own subroutine handle errors.  If coderef
449           itself returns then the method generating the error returns
450           undefined or an empty list depending on context.
451
452           When mode is an arrayref, the first element of the array must be a
453           coderef.  Any elements that follow are the arguments to coderef.
454           When an error is encountered, the coderef is called with its
455           arguments.  Using this mode you may have your own subroutine handle
456           errors.  If the coderef itself returns then the method generating
457           the error returns undefined or an empty list depending on context.
458
459           A warning is printed to STDERR when attempting to set this
460           attribute to something that is not "die", "return", a coderef, or
461           an arrayref whose first element isn't a coderef.
462
463       errmsg - most recent error message
464               $msg = $obj->errmsg;
465
466               $prev = $obj->errmsg(@msgs);
467
468           The first calling sequence returns the error message associated
469           with the object.  The empty string is returned if no error has been
470           encountered yet.  The second calling sequence sets the error
471           message for the object to the concatenation of @msgs and returns
472           the previous error message.  Normally, error messages are set
473           internally by a method when an error is encountered.
474
475       error - perform the error mode action
476               $obj->error(@msgs);
477
478           This method concatenates @msgs into a string and places it in the
479           object as the error message.  Also see "errmsg()".  It then
480           performs the error mode action.  Also see "errmode()".
481
482           If the error mode doesn't cause the program to die, then an
483           undefined value or an empty list is returned depending on the
484           context.
485
486           This method is primarily used by this class or a sub-class to
487           perform the user requested action when an error is encountered.
488
489       family - IP address family for remote host
490               $family = $obj->family;
491
492               $prev   = $obj->family($family);
493
494           This method designates which IP address family "host()" refers to,
495           i.e. IPv4 or IPv6.  IPv6 support is available when using perl 5.14
496           or later.  With no argument it returns the current value set in the
497           object.  With an argument it sets the current address family to
498           $family and returns the previous address family.  Valid values are
499           "ipv4", "ipv6", or "any".  When "any", the "host()" can be a
500           hostname or IP address for either IPv4 or IPv6.  After connecting,
501           you can use "sockfamily()" to determine which IP address family was
502           used.
503
504           The default value is "ipv4".
505
506           The error mode action is performed when attempting to set this
507           attribute to something that isn't "ipv4", "ipv6", or "any".  It is
508           also performed when attempting to set it to "ipv6" when the Socket
509           module is less than version 1.94 or IPv6 is not supported in the OS
510           as indicated by Socket::AF_INET6 not being defined.
511
512       fhopen - use already open filehandle for I/O
513               $ok = $obj->fhopen($fh);
514
515           This method associates the open filehandle $fh with $obj for
516           further I/O.  Filehandle $fh must already be opened.
517
518           Suppose you want to use the features of this module to do I/O to
519           something other than a TCP port, for example STDIN or a filehandle
520           opened to read from a process.  Instead of opening the object for
521           I/O to a TCP port by using "open()" or "new()", call this method
522           instead.
523
524           The value 1 is returned success, the error mode action is performed
525           on failure.
526
527       get - read block of data
528               $data = $obj->get([Binmode    => $mode,]
529                                 [Errmode    => $errmode,]
530                                 [Telnetmode => $mode,]
531                                 [Timeout    => $secs,]);
532
533           This method reads a block of data from the object and returns it
534           along with any buffered data.  If no buffered data is available to
535           return, it will wait for data to read using the timeout specified
536           in the object.  You can override that timeout using $secs.  Also
537           see "timeout()".  If buffered data is available to return, it also
538           checks for a block of data that can be immediately read.
539
540           On eof an undefined value is returned.  On time-out or other
541           failures, the error mode action is performed.  To distinguish
542           between eof or an error occurring when the error mode is not set to
543           "die", use "eof()".
544
545           Optional named parameters are provided to override the current
546           settings of binmode, errmode, telnetmode, and timeout.
547
548       getline - read next line
549               $line = $obj->getline([Binmode    => $mode,]
550                                     [Errmode    => $errmode,]
551                                     [Input_record_separator => $chars,]
552                                     [Rs         => $chars,]
553                                     [Telnetmode => $mode,]
554                                     [Timeout    => $secs,]);
555
556           This method reads and returns the next line of data from the
557           object.  You can use "input_record_separator()" to change the
558           notion of what separates a line.  The default is "\n".  If a line
559           isn't immediately available, this method blocks waiting for a line
560           or a time-out.
561
562           On eof an undefined value is returned.  On time-out or other
563           failures, the error mode action is performed.  To distinguish
564           between eof or an error occurring when the error mode is not set to
565           "die", use "eof()".
566
567           Optional named parameters are provided to override the current
568           settings of binmode, errmode, input_record_separator, rs,
569           telnetmode, and timeout.  Rs is synonymous with
570           input_record_separator.
571
572       getlines - read next lines
573               @lines = $obj->getlines([Binmode    => $mode,]
574                                       [Errmode    => $errmode,]
575                                       [Input_record_separator => $chars,]
576                                       [Rs         => $chars,]
577                                       [Telnetmode => $mode,]
578                                       [Timeout    => $secs,]
579                                       [All        => $boolean,]);
580
581           This method reads and returns all the lines of data from the object
582           until end of file is read.  You can use "input_record_separator()"
583           to change the notion of what separates a line.  The default is
584           "\n".  A time-out error occurs if all the lines can't be read
585           within the time-out interval.  See "timeout()".
586
587           The behavior of this method was changed in version 3.03.  Prior to
588           version 3.03 this method returned just the lines available from the
589           next read.  To get that old behavior, use the optional named
590           parameter All and set $boolean to "" or 0.
591
592           If only eof is read then an empty list is returned.  On time-out or
593           other failures, the error mode action is performed.  Use "eof()" to
594           distinguish between reading only eof or an error occurring when the
595           error mode is not set to "die".
596
597           Optional named parameters are provided to override the current
598           settings of binmode, errmode, input_record_separator, rs,
599           telnetmode, and timeout.  Rs is synonymous with
600           input_record_separator.
601
602       host - name or IP address of remote host
603               $host = $obj->host;
604
605               $prev = $obj->host($host);
606
607           This method designates the remote host for "open()".  It is either
608           a hostname or an IP address.  With no argument it returns the
609           current value set in the object.  With an argument it sets the
610           current host name to $host and returns the previous value.  Use
611           "family()" to control which IP address family, IPv4 or IPv6, host
612           refers to.
613
614           The default value is "localhost".  It may also be set by "open()"
615           or "new()".
616
617       input_log - log all input
618               $fh = $obj->input_log;
619
620               $fh = $obj->input_log($fh);
621
622               $fh = $obj->input_log($tiefh);
623
624               $fh = $obj->input_log($filename);
625
626           This method starts or stops logging of input.  This is useful when
627           debugging.  Also see "dump_log()".  Because most command
628           interpreters echo back commands received, it's likely all your
629           output will also be in this log.  Note that input logging occurs
630           after newline translation.  See "binmode()" for details on newline
631           translation.
632
633           If no argument is given, the log filehandle is returned.  A
634           returned empty string indicates logging is off.
635
636           To stop logging, use an empty string as an argument.  The stopped
637           filehandle is not closed.
638
639           If an open filehandle is given, it is used for logging and
640           returned.  Otherwise, the argument is assumed to be the name of a
641           file, the filename is opened for logging and a filehandle to it is
642           returned.  If the filehandle is not already opened or the filename
643           can't be opened for writing, the error mode action is performed.
644           The filehandle can be a tied filehandle.
645
646       input_record_separator - input line delimiter
647               $chars = $obj->input_record_separator;
648
649               $prev = $obj->input_record_separator($chars);
650
651           This method designates the line delimiter for input.  It's used
652           with "getline()", "getlines()", and "cmd()" to determine lines in
653           the input.
654
655           With no argument this method returns the current input record
656           separator set in the object.  With an argument it sets the input
657           record separator to $chars and returns the previous value.  Note
658           that $chars must have length.
659
660           A warning is printed to STDERR when attempting to set this
661           attribute to a string with no length.
662
663       last_prompt - last prompt read
664               $string = $obj->last_prompt;
665
666               $prev = $obj->last_prompt($string);
667
668           With no argument this method returns the last prompt read by cmd()
669           or login().  See "prompt()".  With an argument it sets the last
670           prompt read to $string and returns the previous value.  Normally,
671           only internal methods set the last prompt.
672
673       lastline - last line read
674               $line = $obj->lastline;
675
676               $prev = $obj->lastline($line);
677
678           This method retrieves the last line read from the object.  This may
679           be a useful error message when the remote side abnormally closes
680           the connection.  Typically the remote side will print an error
681           message before closing.
682
683           With no argument this method returns the last line read from the
684           object.  With an argument it sets the last line read to $line and
685           returns the previous value.  Normally, only internal methods set
686           the last line.
687
688       localfamily - IP address family for local host
689               $localfamily = $obj->localfamily;
690
691               $prev   = $obj->localfamily($family);
692
693           This method designates which IP address family "localhost()" refers
694           to, i.e. IPv4 or IPv6.  IPv6 support is available when using perl
695           5.14 or later.  With no argument it returns the current value set
696           in the object.  With an argument it sets the current local address
697           family to $family and returns the previous address family.  Valid
698           values are "ipv4", "ipv6", or "any".  When "any", the "localhost()"
699           can be a hostname or IP address for either IPv4 or IPv6.
700
701           The default value is "ipv4".
702
703           The error mode action is performed when attempting to set this
704           attribute to something that isn't "ipv4", "ipv6", or "any".  It is
705           also performed when attempting to set it to "ipv6" when the Socket
706           module is less than version 1.94 or IPv6 is not supported in the OS
707           as indicated by Socket::AF_INET6 not being defined.
708
709       localhost - bind local socket to a specific network interface
710               $localhost = $obj->localhost;
711
712               $prev = $obj->localhost($host);
713
714           This method designates the local socket IP address for "open()".
715           It is either a hostname, an IP address, or a null string (i.e. "").
716           A null string disables this feature.
717
718           Normally the OS picks which local network interface to use.  This
719           method is useful when the local machine has more than one network
720           interface and you want to bind to a specific one.  With no argument
721           it returns the current value set in the object.  With an argument
722           it sets the current local host name to $host and returns the
723           previous value.  Use "localfamily()" to control which IP address
724           family, IPv4 or IPv6, local host refers to.
725
726           The default value is "".
727
728       login - perform standard login
729               $ok = $obj->login($username, $password);
730
731               $ok = $obj->login(Name     => $username,
732                                 Password => $password,
733                                 [Errmode => $mode,]
734                                 [Prompt  => $match,]
735                                 [Timeout => $secs,]);
736
737           This method performs a standard login by waiting for a login prompt
738           and responding with $username, then waiting for the password prompt
739           and responding with $password, and then waiting for the command
740           interpreter prompt.  If any of those prompts sent by the remote
741           side don't match what's expected, this method will time-out, unless
742           timeout is turned off.
743
744           Login prompt must match either of these case insensitive patterns:
745
746               /login[: ]*$/i
747               /username[: ]*$/i
748
749           Password prompt must match this case insensitive pattern:
750
751               /password[: ]*$/i
752
753           The command interpreter prompt must match the current setting of
754           prompt.  See "prompt()".
755
756           Use "dump_log()" to debug when this method keeps timing-out and you
757           don't think it should.
758
759           Consider using a combination of "print()" and "waitfor()" as an
760           alternative to this method when it doesn't do what you want, e.g.
761           the remote host doesn't prompt for a username.
762
763           On success, 1 is returned.  On time out, eof, or other failures,
764           the error mode action is performed.  See "errmode()".
765
766           Optional named parameters are provided to override the current
767           settings of errmode, prompt, and timeout.
768
769       max_buffer_length - maximum size of input buffer
770               $len = $obj->max_buffer_length;
771
772               $prev = $obj->max_buffer_length($len);
773
774           This method designates the maximum size of the input buffer.  An
775           error is generated when a read causes the buffer to exceed this
776           limit.  The default value is 1,048,576 bytes (1 MiB).  The input
777           buffer can grow much larger than the block size when you
778           continuously read using "getline()" or "waitfor()" and the data
779           stream contains no newlines or matching waitfor patterns.
780
781           With no argument, this method returns the current maximum buffer
782           length set in the object.  With an argument it sets the maximum
783           buffer length to $len and returns the previous value.  Values of
784           $len smaller than 512 will be adjusted to 512.
785
786           A warning is printed to STDERR when attempting to set this
787           attribute to something that isn't a positive integer.
788
789       ofs - field separator for print
790               $chars = $obj->ofs
791
792               $prev = $obj->ofs($chars);
793
794           This method is synonymous with "output_field_separator()".
795
796       open - connect to port on remote host
797               $ok = $obj->open($host);
798
799               $ok = $obj->open([Host        => $host,]
800                                [Port        => $port,]
801                                [Family      => $family,]
802                                [Errmode     => $mode,]
803                                [Timeout     => $secs,]
804                                [Localhost   => $host,]
805                                [Localfamily => $family,]);
806
807           This method opens a TCP connection to $port on $host for the IP
808           address $family.  If any of those arguments are missing then the
809           current attribute value for the object is used.  Specifying Host
810           sets that attribute for the object.  Specifying any of the other
811           optional named parameters overrides the current setting.
812
813           The default IP address family is "ipv4".  $family may be set to
814           "ipv4", "ipv6", or "any".  See "family()" for more details.
815
816           Localhost is used to bind to a specific local network interface.
817
818           If the object is already open, it is closed before attempting a
819           connection.
820
821           On success 1 is returned.  On time-out or other connection
822           failures, the error mode action is performed.  See "errmode()".
823
824           Time-outs don't work for this method on machines that don't
825           implement SIGALRM - most notably MS-Windows machines.  For those
826           machines, an error is returned when the system reaches its own
827           time-out while trying to connect.
828
829           A side effect of this method is to reset the alarm interval
830           associated with SIGALRM.
831
832       option_accept - indicate willingness to accept a TELNET option
833               $fh = $obj->option_accept([Do   => $telopt,]
834                                         [Dont => $telopt,]
835                                         [Will => $telopt,]
836                                         [Wont => $telopt,]);
837
838           This method is used to indicate whether to accept or reject an
839           offer to enable a TELNET option made by the remote side.  If you're
840           using Do or Will to indicate a willingness to enable, then a
841           notification callback must have already been defined by a prior
842           call to "option_callback()".  See "option_callback()" for details
843           on receiving enable/disable notification of a TELNET option.
844
845           You can give multiple Do, Dont, Will, or Wont arguments for
846           different TELNET options in the same call to this method.
847
848           The following example describes the meaning of the named
849           parameters.  A TELNET option, such as "TELOPT_ECHO" used below, is
850           an integer constant that you can import from Net::Telnet.  See the
851           source in file Telnet.pm for the complete list.
852
853Do => "TELOPT_ECHO"
854
855               •   we'll accept an offer to enable the echo option on the
856                   local side
857
858Dont => "TELOPT_ECHO"
859
860               •   we'll reject an offer to enable the echo option on the
861                   local side
862
863Will => "TELOPT_ECHO"
864
865               •   we'll accept an offer to enable the echo option on the
866                   remote side
867
868Wont => "TELOPT_ECHO"
869
870               •   we'll reject an offer to enable the echo option on the
871                   remote side
872
873           •   Use "option_send()" to send a request to the remote side to
874               enable or disable a particular TELNET option.
875
876       option_callback - define the option negotiation callback
877               $coderef = $obj->option_callback;
878
879               $prev = $obj->option_callback($coderef);
880
881           This method defines the callback subroutine that is called when a
882           TELNET option is enabled or disabled.  Once defined, the
883           option_callback may not be undefined.  However, calling this method
884           with a different $coderef changes it.
885
886           A warning is printed to STDERR when attempting to set this
887           attribute to something that isn't a coderef.
888
889           Here are the circumstances that invoke $coderef:
890
891           •   An option becomes enabled because the remote side requested an
892               enable and "option_accept()" had been used to arrange that it
893               be accepted.
894
895           •   The remote side arbitrarily decides to disable an option that
896               is currently enabled.  Note that Net::Telnet always accepts a
897               request to disable from the remote side.
898
899           •   "option_send()" was used to send a request to enable or disable
900               an option and the response from the remote side has just been
901               received.  Note, that if a request to enable is rejected then
902               $coderef is still invoked even though the option didn't change.
903
904           •   Here are the arguments passed to &$coderef:
905
906                   &$coderef($obj, $option, $is_remote,
907                             $is_enabled, $was_enabled, $buf_position);
908
909           •   1.  $obj is the Net::Telnet object
910
911           •   2.  $option is the TELNET option.  Net::Telnet exports
912               constants for the various TELNET options which just equate to
913               an integer.
914
915           •   3.  $is_remote is a boolean indicating for which side the
916               option applies.
917
918           •   4.  $is_enabled is a boolean indicating the option is enabled
919               or disabled
920
921           •   5.  $was_enabled is a boolean indicating the option was
922               previously enabled or disabled
923
924           •   6.  $buf_position is an integer indicating the position in the
925               object's input buffer where the option takes effect.  See
926               "buffer()" to access the object's input buffer.
927
928       option_log - log all TELNET options sent or received
929               $fh = $obj->option_log;
930
931               $fh = $obj->option_log($fh);
932
933               $fh = $obj->option_log($tiefh);
934
935               $fh = $obj->option_log($filename);
936
937           This method starts or stops logging of all TELNET options being
938           sent or received.  This is useful for debugging when you send
939           options via "option_send()" or you arrange to accept option
940           requests from the remote side via "option_accept()".  Also see
941           "dump_log()".
942
943           If no argument is given, the log filehandle is returned.  An empty
944           string indicates logging is off.
945
946           To stop logging, use an empty string as an argument.  The stopped
947           filehandle is not closed.
948
949           If an open filehandle is given, it is used for logging and
950           returned.  Otherwise, the argument is assumed to be the name of a
951           file, the filename is opened for logging and a filehandle to it is
952           returned.  If the filehandle is not already opened or the filename
953           can't be opened for writing, the error mode action is performed.
954           The filehandle can be a tied filehandle.
955
956       option_send - send TELNET option negotiation request
957               $ok = $obj->option_send([Do    => $telopt,]
958                                       [Dont  => $telopt,]
959                                       [Will  => $telopt,]
960                                       [Wont  => $telopt,]
961                                       [Async => $boolean,]);
962
963           This method is not yet implemented.  Look for it in a future
964           version.
965
966       option_state - get current state of a TELNET option
967               $hashref = $obj->option_state($telopt);
968
969           This method returns a hashref containing a copy of the current
970           state of TELNET option $telopt.
971
972           Here are the values returned in the hash:
973
974$hashref->{remote_enabled}
975
976               •   boolean that indicates if the option is enabled on the
977                   remote side.
978
979$hashref->{remote_enable_ok}
980
981               •   boolean that indicates if it's ok to accept an offer to
982                   enable this option on the remote side.
983
984$hashref->{remote_state}
985
986               •   string used to hold the internal state of option
987                   negotiation for this option on the remote side.
988
989$hashref->{local_enabled}
990
991               •   boolean that indicates if the option is enabled on the
992                   local side.
993
994$hashref->{local_enable_ok}
995
996               •   boolean that indicates if it's ok to accept an offer to
997                   enable this option on the local side.
998
999$hashref->{local_state}
1000
1001               •   string used to hold the internal state of option
1002                   negotiation for this option on the local side.
1003
1004       ors - output line delimiter
1005               $chars = $obj->ors;
1006
1007               $prev = $obj->ors($chars);
1008
1009           This method is synonymous with "output_record_separator()".
1010
1011       output_field_separator - field separator for print
1012               $chars = $obj->output_field_separator;
1013
1014               $prev = $obj->output_field_separator($chars);
1015
1016           This method designates the output field separator for "print()".
1017           Ordinarily the print method simply prints out the comma separated
1018           fields you specify.  Set this to specify what's printed between
1019           fields.
1020
1021           With no argument this method returns the current output field
1022           separator set in the object.  With an argument it sets the output
1023           field separator to $chars and returns the previous value.
1024
1025           By default it's set to an empty string.
1026
1027       output_log - log all output
1028               $fh = $obj->output_log;
1029
1030               $fh = $obj->output_log($fh);
1031
1032               $fh = $obj->output_log($tiefh);
1033
1034               $fh = $obj->output_log($filename);
1035
1036           This method starts or stops logging of output.  This is useful when
1037           debugging.  Also see "dump_log()".  Because most command
1038           interpreters echo back commands received, it's likely all your
1039           output would also be in an input log.  See "input_log()".  Note
1040           that output logging occurs before newline translation.  See
1041           "binmode()" for details on newline translation.
1042
1043           If no argument is given, the log filehandle is returned.  A
1044           returned empty string indicates logging is off.
1045
1046           To stop logging, use an empty string as an argument.  The stopped
1047           filehandle is not closed.
1048
1049           If an open filehandle is given, it is used for logging and
1050           returned.  Otherwise, the argument is assumed to be the name of a
1051           file, the filename is opened for logging and a filehandle to it is
1052           returned.  If the filehandle is not already opened or the filename
1053           can't be opened for writing, the error mode action is performed.
1054           The filehandle can be a tied filehandle.
1055
1056       output_record_separator - output line delimiter
1057               $chars = $obj->output_record_separator;
1058
1059               $prev = $obj->output_record_separator($chars);
1060
1061           This method designates the output line delimiter for "print()" and
1062           "cmd()".  Set this to specify what's printed at the end of
1063           "print()" and "cmd()".
1064
1065           The output record separator is set to "\n" by default, so there's
1066           no need to append all your commands with a newline.  To avoid
1067           printing the output_record_separator use "put()" or set the
1068           output_record_separator to an empty string.
1069
1070           With no argument this method returns the current output record
1071           separator set in the object.  With an argument it sets the output
1072           record separator to $chars and returns the previous value.
1073
1074       peerhost - IP address of the other end of the socket connection
1075               $ipaddr = $obj->peerhost;
1076
1077           This method returns a string which is the IPv4 or IPv6 address the
1078           remote socket is bound to (i.e. it is the IP address of "host()").
1079           It returns "" when not connected.
1080
1081       peerport - TCP port of the other end of the socket connection
1082               $port = $obj->peerport;
1083
1084           This method returns the port number which the remote socket is
1085           bound to.  It is the same as the "port()" number when connected.
1086           It returns "" when not connected.
1087
1088       port - remote port
1089               $port = $obj->port;
1090
1091               $prev = $obj->port($port);
1092
1093           This method designates the remote TCP port for "open()".  With no
1094           argument this method returns the current port number.  With an
1095           argument it sets the current port number to $port and returns the
1096           previous port.  If $port is a TCP service name, then it's first
1097           converted to a port number using the perl function
1098           "getservbyname()".
1099
1100           The default value is 23.
1101
1102           The error mode action is performed when attempting to set this
1103           attribute to something that is not a positive integer or a valid
1104           TCP service name.
1105
1106       print - write to object
1107               $ok = $obj->print(@list);
1108
1109           This method writes @list followed by the output_record_separator to
1110           the open object and returns 1 if all data was successfully written.
1111           On time-out or other failures, the error mode action is performed.
1112           See "errmode()".
1113
1114           By default, the "output_record_separator()" is set to "\n" so all
1115           your commands automatically end with a newline.  In most cases your
1116           output is being read by a command interpreter which won't accept a
1117           command until newline is read.  This is similar to someone typing a
1118           command and hitting the return key.  To avoid printing a trailing
1119           "\n" use "put()" instead or set the output_record_separator to an
1120           empty string.
1121
1122           On failure, it's possible that some data was written.  If you
1123           choose to try and recover from a print timing-out, use
1124           "print_length()" to determine how much was written before the error
1125           occurred.
1126
1127           You may also use the output field separator to print a string
1128           between the list elements.  See "output_field_separator()".
1129
1130       print_length - number of bytes written by print
1131               $num = $obj->print_length;
1132
1133           This returns the number of bytes successfully written by the most
1134           recent "print()" or "put()".
1135
1136       prompt - pattern to match a prompt
1137               $matchop = $obj->prompt;
1138
1139               $prev = $obj->prompt($matchop);
1140
1141           This method sets the pattern used to find a prompt in the input
1142           stream.  It must be a string representing a valid perl pattern
1143           match operator.  The methods "login()" and "cmd()" try to read
1144           until matching the prompt.  They will fail with a time-out error if
1145           the pattern you've chosen doesn't match what the remote side sends.
1146
1147           With no argument this method returns the prompt set in the object.
1148           With an argument it sets the prompt to $matchop and returns the
1149           previous value.
1150
1151           The default prompt is '/[\$%#>] $/'
1152
1153           Always use single quotes, instead of double quotes, to construct
1154           $matchop (e.g. '/bash\$ $/').  If you're constructing a DOS like
1155           file path, you'll need to use four backslashes to represent one
1156           (e.g. '/c:\\\\users\\\\bill>$/i').
1157
1158           Of course don't forget about regexp metacharacters like ".", "[",
1159           or "$".  You'll only need a single backslash to quote them.  The
1160           anchor metacharacters "^" and "$" refer to positions in the input
1161           buffer.
1162
1163           The error mode action is performed when attempting to set this
1164           attribute with a match operator missing its opening delimiter.
1165
1166       put - write to object
1167               $ok = $obj->put($string);
1168
1169               $ok = $obj->put(String      => $string,
1170                               [Binmode    => $mode,]
1171                               [Errmode    => $errmode,]
1172                               [Telnetmode => $mode,]
1173                               [Timeout    => $secs,]);
1174
1175           This method writes $string to the opened object and returns 1 if
1176           all data was successfully written.  This method is like "print()"
1177           except that it doesn't write the trailing output_record_separator
1178           ("\n" by default).  On time-out or other failures, the error mode
1179           action is performed.  See "errmode()".
1180
1181           On failure, it's possible that some data was written.  If you
1182           choose to try and recover from a put timing-out, use
1183           "print_length()" to determine how much was written before the error
1184           occurred.
1185
1186           Optional named parameters are provided to override the current
1187           settings of binmode, errmode, telnetmode, and timeout.
1188
1189       rs - input line delimiter
1190               $chars = $obj->rs;
1191
1192               $prev = $obj->rs($chars);
1193
1194           This method is synonymous with "input_record_separator()".
1195
1196       sockfamily - IP address family of connected local socket
1197               $sockfamily = $obj->sockfamily;
1198
1199           This method returns which IP address family "open()" used to
1200           successfully connect.  It is most useful when the requested address
1201           "family()" for "open()" was "any".  Values returned may be "ipv4",
1202           "ipv6", or "" (when not connected).
1203
1204       sockhost - IP address of this end of the socket connection
1205               $ipaddr = $obj->sockhost;
1206
1207           This method returns a string which is the IPv4 or IPv6 address the
1208           local socket is bound to.  It returns "" when not connected.
1209
1210       sockport - TCP port of this end of the socket connection
1211               $port = $obj->sockport;
1212
1213           This method returns the port number which the local socket is bound
1214           to.  It returns "" when not connected.
1215
1216       telnetmode - turn off/on telnet command interpretation
1217               $mode = $obj->telnetmode;
1218
1219               $prev = $obj->telnetmode($mode);
1220
1221           This method controls whether or not TELNET commands in the data
1222           stream are recognized and handled.  The TELNET protocol uses
1223           certain character sequences sent in the data stream to control the
1224           session.  If the port you're connecting to isn't using the TELNET
1225           protocol, then you should turn this mode off.  The default is on.
1226
1227           If no argument is given, the current mode is returned.
1228
1229           If $mode is 0 then telnet mode is off.  If $mode is 1 then telnet
1230           mode is on.
1231
1232       timed_out - time-out indicator
1233               $boolean = $obj->timed_out;
1234
1235               $prev = $obj->timed_out($boolean);
1236
1237           This method indicates if a previous read, write, or open method
1238           timed-out.  Remember that timing-out is itself an error.  To be
1239           able to invoke "timed_out()" after a time-out error, you'd have to
1240           change the default error mode to something other than "die".  See
1241           "errmode()".
1242
1243           With no argument this method returns 1 if the previous method
1244           timed-out.  With an argument it sets the indicator.  Normally, only
1245           internal methods set this indicator.
1246
1247       timeout - I/O time-out interval
1248               $secs = $obj->timeout;
1249
1250               $prev = $obj->timeout($secs);
1251
1252           This method sets the timeout interval used when performing I/O or
1253           connecting to a port.  When a method doesn't complete within the
1254           timeout interval then it's an error and the error mode action is
1255           performed.
1256
1257           A timeout may be expressed as a relative or absolute value.  If
1258           $secs is greater than or equal to the time the program started, as
1259           determined by $^T, then it's an absolute time value for when time-
1260           out occurs.  The perl function "time()" may be used to obtain an
1261           absolute time value.  For a relative time-out value less than $^T,
1262           time-out happens $secs from when the method begins.
1263
1264           If $secs is 0 then time-out occurs if the data cannot be
1265           immediately read or written.  Use the undefined value to turn off
1266           timing-out completely.
1267
1268           With no argument this method returns the timeout set in the object.
1269           With an argument it sets the timeout to $secs and returns the
1270           previous value.  The default timeout value is 10 seconds.
1271
1272           A warning is printed to STDERR when attempting to set this
1273           attribute to something that is not an "undef" or a non-negative
1274           integer.
1275
1276       waitfor - wait for pattern in the input
1277               $ok = $obj->waitfor($matchop);
1278               $ok = $obj->waitfor([Match      => $matchop,]
1279                                   [String     => $string,]
1280                                   [Binmode    => $mode,]
1281                                   [Errmode    => $errmode,]
1282                                   [Telnetmode => $mode,]
1283                                   [Timeout    => $secs,]);
1284
1285               ($prematch, $match) = $obj->waitfor($matchop);
1286               ($prematch, $match) = $obj->waitfor([Match      => $matchop,]
1287                                                   [String     => $string,]
1288                                                   [Binmode    => $mode,]
1289                                                   [Errmode    => $errmode,]
1290                                                   [Telnetmode => $mode,]
1291                                                   [Timeout    => $secs,]);
1292
1293           This method reads until a pattern match or string is found in the
1294           input stream.  All the characters before and including the match
1295           are removed from the input stream.
1296
1297           In a list context the characters before the match and the matched
1298           characters are returned in $prematch and $match.  In a scalar
1299           context, the matched characters and all characters before it are
1300           discarded and 1 is returned on success.  On time-out, eof, or other
1301           failures, for both list and scalar context, the error mode action
1302           is performed.  See "errmode()".
1303
1304           You can specify more than one pattern or string by simply providing
1305           multiple Match and/or String named parameters.  A $matchop must be
1306           a string representing a valid Perl pattern match operator.  The
1307           $string is just a substring to find in the input stream.
1308
1309           Use "dump_log()" to debug when this method keeps timing-out and you
1310           don't think it should.
1311
1312           An optional named parameter is provided to override the current
1313           setting of timeout.
1314
1315           To avoid unexpected backslash interpretation, always use single
1316           quotes instead of double quotes to construct a match operator
1317           argument for "prompt()" and "waitfor()" (e.g. '/bash\$ $/').  If
1318           you're constructing a DOS like file path, you'll need to use four
1319           backslashes to represent one (e.g. '/c:\\\\users\\\\bill>$/i').
1320
1321           Of course don't forget about regexp metacharacters like ".", "[",
1322           or "$".  You'll only need a single backslash to quote them.  The
1323           anchor metacharacters "^" and "$" refer to positions in the input
1324           buffer.
1325
1326           Optional named parameters are provided to override the current
1327           settings of binmode, errmode, telnetmode, and timeout.
1328

SEE ALSO

1330       RFC 854
1331         TELNET Protocol Specification
1332
1333         http://tools.ietf.org/html/rfc854
1334
1335       RFC 1143
1336         Q Method of Implementing TELNET Option Negotiation
1337
1338         http://tools.ietf.org/html/rfc1143
1339
1340       TELNET Option Assignments
1341         http://www.iana.org/assignments/telnet-options
1342

EXAMPLES

1344       Setting "prompt()" to match a user's shell prompt can be tricky.  This
1345       example logs in without knowing the shell prompt and then sets it to
1346       match "prompt()".  It requires /usr/bin/env and /bin/sh on the remote
1347       host.
1348
1349           my $host = 'your_destination_host_here';
1350           my $user = 'your_username_here';
1351           my $passwd = 'your_password_here';
1352           my ($t, @output);
1353
1354           ## Create a Net::Telnet object.
1355           use Net::Telnet ();
1356           $t = new Net::Telnet (Timeout  => 10);
1357
1358           ## Connect and login.
1359           $t->open($host);
1360
1361           $t->waitfor('/login: ?$/i');
1362           $t->print($user);
1363
1364           $t->waitfor('/password: ?$/i');
1365           $t->print($passwd);
1366
1367           ## Switch to a known shell, using a known prompt.
1368           $t->prompt('/<xPROMPTx> $/');
1369           $t->errmode("return");
1370
1371           $t->cmd("exec /usr/bin/env 'PS1=<xPROMPTx> ' /bin/sh -i")
1372               or die "login failed to remote host $host";
1373
1374           $t->errmode("die");
1375
1376           ## Now you can do cmd() to your heart's content.
1377           @output = $t->cmd("uname -a");
1378           print @output;
1379
1380           exit;
1381
1382       Usually you want the remote TERM environment variable to be set to
1383       something like "dumb" so you don't read escape sequences meant to be
1384       interpreted by a display terminal.  It is best to set it via "cmd()",
1385       or via "waitfor()" and "print()".  It is also possible to negotiate the
1386       terminal type via telnet.  Here is how to do that.
1387
1388           ## Module import.
1389           use Net::Telnet qw(TELNET_IAC TELNET_SB TELNET_SE TELOPT_TTYPE);
1390
1391           ## Global variables.
1392           my $Term;
1393
1394           ## Main program.
1395           {
1396               my $host = "your_destination_host_here";
1397               my $user = "your_username_here";
1398               my $passwd = "your_password_here";
1399               my $prompt = '/bash\$ $/';  # your regexp for shell prompt here
1400               my $t;
1401
1402               $t = new Net::Telnet (Prompt => $prompt);
1403
1404               ## Set up callbacks to negotiate terminal type.
1405               $t->option_callback(sub {});
1406               $t->suboption_callback(\&subopt_callback);
1407               $t->option_accept(Do => TELOPT_TTYPE);
1408
1409               ## Login and print value of TERM.
1410               $Term = "dumb";
1411               $t->open($host);
1412               $t->login($user, $passwd);
1413               print $t->cmd('hostname');
1414               print "TERM=", $t->cmd('echo $TERM');
1415               $t->close;
1416
1417               exit;
1418           } # end main program
1419
1420           sub subopt_callback {
1421               my ($t, $option, $parameters) = @_;
1422               my $telcmd;
1423
1424               if ($option == TELOPT_TTYPE) {
1425                   $telcmd = pack("C4 A* C2", TELNET_IAC, TELNET_SB, TELOPT_TTYPE, 0,
1426                                  $Term, TELNET_IAC, TELNET_SE);
1427                   $t->put(String => $telcmd,
1428                           Telnetmode => 0);
1429               }
1430
1431               1;
1432           } # end sub subopt_callback
1433
1434       You can also use Net::Telnet to interact with local programs.  This
1435       example changes a user's login password.  It introduces the "spawn()"
1436       subroutine to start a program and associate a filehandle with its
1437       standard I/O.  Because the passwd program always prompts for passwords
1438       on its controlling terminal, the IO::Pty module is used to create a new
1439       pseudo terminal for use by passwd.  The Net::Telnet object reads and
1440       writes to that pseudo terminal.  To use the code below, substitute
1441       "changeme" with the actual old and new passwords.
1442
1443       ## Main program.  {
1444           my ($pty, $passwd);
1445           my $oldpw = "changeme";
1446           my $newpw = "changeme";
1447
1448           ## Start passwd program.
1449           $pty = spawn("passwd");
1450
1451           ## Create a Net::Telnet object to perform I/O on passwd's tty.
1452           use Net::Telnet;
1453           $passwd = new Net::Telnet (-fhopen => $pty,
1454                                      -timeout => 2,
1455                                      -output_record_separator => "\r",
1456                                      -telnetmode => 0,
1457                                      -cmd_remove_mode => 1);
1458           $passwd->errmode("return");
1459
1460           ## Send existing password.
1461           $passwd->waitfor('/password: ?$/i')
1462               or die "no old password prompt: ", $passwd->lastline;
1463           $passwd->print($oldpw);
1464
1465           ## Send new password.
1466           $passwd->waitfor('/new (\w+\s)?password: ?$/i')
1467               or die "bad old password: ", $passwd->lastline;
1468           $passwd->print($newpw);
1469
1470           ## Send new password verification.
1471           $passwd->waitfor('/new (\w+\s)?password: ?$/i')
1472               or die "bad new password: ", $passwd->lastline;
1473           $passwd->print($newpw);
1474
1475           ## Display success or failure.
1476           $passwd->waitfor('/(changed|updated)/')
1477               or die "bad new password: ", $passwd->lastline;
1478           print $passwd->lastline;
1479
1480           $passwd->close;
1481           exit;
1482       } # end main program
1483
1484       sub spawn {
1485           my (@cmd) = @_;
1486           my ($pid, $pty, $tty, $tty_fd);
1487
1488           ## Create a new pseudo terminal.
1489           use IO::Pty ();
1490           $pty = new IO::Pty
1491               or die $!;
1492
1493           ## Execute the program in another process.
1494           unless ($pid = fork) {  # child process
1495               die "problem spawning program: $!\n" unless defined $pid;
1496
1497               ## Disassociate process from its controlling terminal.
1498               use POSIX ();
1499               POSIX::setsid()
1500                   or die "setsid failed: $!";
1501
1502               ## Associate process with a new controlling terminal.
1503               $pty->make_slave_controlling_terminal;
1504               $tty = $pty->slave;
1505               $tty_fd = $tty->fileno;
1506               close $pty;
1507
1508               ## Make standard I/O use the new controlling terminal.
1509               open STDIN, "<&$tty_fd" or die $!;
1510               open STDOUT, ">&$tty_fd" or die $!;
1511               open STDERR, ">&STDOUT" or die $!;
1512               close $tty;
1513
1514               ## Execute requested program.
1515               exec @cmd
1516                   or die "problem executing $cmd[0]\n";
1517           } # end child process
1518
1519           $pty;
1520       } # end sub spawn
1521
1522       Here is an example that uses the openssh program to connect to a remote
1523       host.  It uses the "spawn()" subroutine, from the password changing
1524       example above, to start the ssh program and then read and write to it
1525       via a Net::Telnet object.  This example turns off ssh host key
1526       checking, which reduces your ability to know when someone on the
1527       network is impersonating the remote host.  To use the code below,
1528       substitute "changeme" with the actual host, user, password, and command
1529       prompt.
1530
1531           ## Main program.
1532           {
1533               my $host = "changeme";
1534               my $user = "changeme";
1535               my $passwd = "changeme";
1536               my $prompt = '/changeme\$ $/';
1537               my ($buf, $match, $pty, $ssh, @lines);
1538
1539               ## Start ssh program.
1540               $pty = spawn("ssh",
1541                            "-l", $user,
1542                            "-e", "none",
1543                            "-F", "/dev/null",
1544                            "-o", "PreferredAuthentications=password",
1545                            "-o", "NumberOfPasswordPrompts=1",
1546                            "-o", "StrictHostKeyChecking=no",
1547                            "-o", "UserKnownHostsFile=/dev/null",
1548                            $host);
1549
1550               ## Create a Net::Telnet object to perform I/O on ssh's tty.
1551               use Net::Telnet;
1552               $ssh = new Net::Telnet (-fhopen => $pty,
1553                                       -prompt => $prompt,
1554                                       -telnetmode => 0,
1555                                       -output_record_separator => "\r",
1556                                       -cmd_remove_mode => 1);
1557
1558               ## Wait for the password prompt and send password.
1559               $ssh->waitfor(-match => '/password: ?$/i',
1560                             -errmode => "return")
1561                   or die "problem connecting to \"$host\": ", $ssh->lastline;
1562               $ssh->print($passwd);
1563
1564               ## Wait for the shell prompt.
1565               (undef, $match) = $ssh->waitfor(-match => $ssh->prompt,
1566                                               -match => '/^Permission denied/m',
1567                                               -errmode => "return")
1568                   or return $ssh->error("login failed: expected shell prompt ",
1569                                         "doesn't match actual\n");
1570               return $ssh->error("login failed: bad login-name or password\n")
1571                   if $match =~ /^Permission denied/m;
1572
1573               ## Run commands on remote host.
1574               print $ssh->cmd("hostname");
1575               print $ssh->cmd("uptime");
1576
1577               $ssh->close;
1578               exit;
1579           } # end main program
1580
1581       Some shells have a rather restrictive 255 character line limit.  If you
1582       run into this problem, here is an example for sending lines longer than
1583       254 as a sequence of shorter lines.
1584
1585           ## Main program.
1586           {
1587               my $host = "changeme";
1588               my $user = "changeme";
1589               my $passwd = "changeme";
1590               my $prompt = '/changeme\$ $/';
1591               my $cmd = join("", "echo ",
1592                              "11111111112222222222333333333344444444445555555555",
1593                              "66666666667777777777888888888899999999990000000000",
1594                              "11111111112222222222333333333344444444445555555555",
1595                              "66666666667777777777888888888899999999990000000000",
1596                              "11111111112222222222333333333344444444445555555555",
1597                              "66666666667777777777888888888899999999990000000000");
1598
1599               use Net::Telnet ();
1600               my $t = new Net::Telnet (-prompt => $prompt);
1601               $t->open($host);
1602               $t->login($user, $passwd);
1603
1604               my @output = cmd_unixlong($t, $cmd);
1605               print @output;
1606
1607               exit;
1608           } # end main program
1609
1610           sub cmd_unixlong {
1611               my ($obj, $cmd) = @_;
1612               my ($line, $pos);
1613               my $max_tty_line = 254;
1614
1615               ## Start a Bourne shell.
1616               $obj->cmd(-string => "/usr/bin/env " .
1617                         "'PS1=<xPROMPTx> ' 'PS2=<xPROMPTx> ' /bin/sh -i",
1618                         -prompt => '/<xPROMPTx> $/')
1619                   or return;
1620
1621               ## Break-up the one large command line and send as shorter lines.
1622               $pos = 0;
1623               while (1) {
1624                   $line = substr $cmd, $pos, $max_tty_line;
1625                   $pos += length $line;
1626                   last unless $pos < length $cmd;
1627
1628                   ## Send the line with continuation char.
1629                   $obj->cmd(-string => "$line\\",
1630                             -prompt => '/<xPROMPTx> $/')
1631                       or return;
1632               }
1633
1634               ## Send the last line and return the output.
1635               $obj->cmd("$line ; exit");
1636           } # end sub cmd_unixlong
1637

AUTHOR

1639       Jay Rogers <jay@rgrs.com>
1640

CREDITS

1642       Dave Martin, Dave Cardosi
1643
1645       Copyright 1997, 2000, 2002, 2013, 2021 by Jay Rogers.  All rights
1646       reserved.  This program is free software; you can redistribute it
1647       and/or modify it under the same terms as Perl itself.
1648
1649
1650
1651perl v5.36.0                      2022-07-22                    Net::Telnet(3)
Impressum