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

SEE ALSO

1318       RFC 854
1319         TELNET Protocol Specification
1320
1321         http://tools.ietf.org/html/rfc854
1322
1323       RFC 1143
1324         Q Method of Implementing TELNET Option Negotiation
1325
1326         http://tools.ietf.org/html/rfc1143
1327
1328       TELNET Option Assignments
1329         http://www.iana.org/assignments/telnet-options
1330

EXAMPLES

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

AUTHOR

1627       Jay Rogers <jay@rgrs.com>
1628

CREDITS

1630       Dave Martin, Dave Cardosi
1631
1633       Copyright 1997, 2000, 2002, 2013 by Jay Rogers.  All rights reserved.
1634       This program is free software; you can redistribute it and/or modify it
1635       under the same terms as Perl itself.
1636

POD ERRORS

1638       Hey! The above document had some coding errors, which are explained
1639       below:
1640
1641       Around line 5169:
1642           Expected text after =item, not a bullet
1643
1644       Around line 5217:
1645           Expected text after =item, not a bullet
1646
1647
1648
1649perl v5.30.0                      2019-07-26                    Net::Telnet(3)
Impressum