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" by
59         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 object to
64         determine when a login or remote command is complete.  Those methods
65         will fail with a time-out if you don't set the prompt correctly.
66
67       • Use a combination of print() and waitfor() as an alternative to
68         login() or cmd() when they don't do what you want.
69
70       • Errors such as timing-out are handled according to the error mode
71         action.  The default action is to print an error message to standard
72         error and have the program die.  See the errmode() method for more
73         information.
74
75       • When constructing the match operator argument for prompt() or
76         waitfor(), always use single quotes instead of double quotes to avoid
77         unexpected backslash interpretation (e.g. '/bash\$ $/').  If you're
78         constructing a DOS like file path, you'll need to use four
79         backslashes to represent one (e.g. '/c:\\\\users\\\\bill>$/i').
80
81         Of course don't forget about regexp metacharacters like ".", "[", or
82         "$".  You'll only need a single backslash to quote them.  The anchor
83         metacharacters "^" and "$" refer to positions in the input buffer.
84         To avoid matching characters read that look like a prompt, it's a
85         good idea to end your prompt pattern with the "$" anchor.  That way
86         the prompt will only match if it's the last thing read.
87
88       • In the input stream, each sequence of carriage return and line feed
89         (i.e. "\015\012" or CR LF) is converted to "\n".  In the output
90         stream, each occurrence of "\n" is converted to a sequence of CR LF.
91         See binmode() to change the behavior.  TCP protocols typically use
92         the ASCII sequence, carriage return and line feed to designate a
93         newline.
94
95       • Timing-out while making a connection is disabled for machines that
96         don't support the alarm() function.  Most notably these include MS-
97         Windows machines.
98
99       • You'll need to be running at least Perl version 5.002 to use this
100         module.  This module does not require any libraries that don't
101         already come with a standard Perl distribution.
102
103         If you have the IO:: libraries installed (they come standard with
104         perl5.004 and later) then IO::Socket::INET is used as a base class,
105         otherwise FileHandle is used.
106
107   Debugging
108       The typical usage bug causes a time-out error because you've made
109       incorrect assumptions about what the remote side actually sends.  The
110       easiest way to reconcile what the remote side sends with your
111       expectations is to use input_log() or dump_log().
112
113       dump_log() allows you to see the data being sent from the remote side
114       before any translation is done, while input_log() shows you the results
115       after translation.  The translation includes converting end of line
116       characters, removing and responding to TELNET protocol commands in the
117       data stream.
118
119   Style of Named Parameters
120       Two different styles of named parameters are supported.  This document
121       only shows the IO:: style:
122
123           Net::Telnet->new(Timeout => 20);
124
125       however the dash-option style is also allowed:
126
127           Net::Telnet->new(-timeout => 20);
128
129   Connecting to a Remote MS-Windows Machine
130       By default MS-Windows doesn't come with a TELNET server.  However third
131       party TELNET servers are available.  Unfortunately many of these
132       servers falsely claim to be a TELNET server.  This is especially true
133       of the so-called "Microsoft Telnet Server" that comes installed with
134       some newer versions MS-Windows.
135
136       When a TELNET server first accepts a connection, it must use the ASCII
137       control characters carriage-return and line-feed to start a new line
138       (see RFC854).  A server like the "Microsoft Telnet Server" that doesn't
139       do this, isn't a TELNET server.  These servers send ANSI terminal
140       escape sequences to position to a column on a subsequent line and to
141       even position while writing characters that are adjacent to each other.
142       Worse, when sending output these servers resend previously sent command
143       output in a misguided attempt to display an entire terminal screen.
144
145       Connecting Net::Telnet to one of these false TELNET servers makes your
146       job of parsing command output very difficult.  It's better to replace a
147       false TELNET server with a real TELNET server.  The better TELNET
148       servers for MS-Windows allow you to avoid the ANSI escapes by turning
149       off something some of them call console mode.
150

METHODS

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

SEE ALSO

1323       RFC 854
1324         TELNET Protocol Specification
1325
1326         http://tools.ietf.org/html/rfc854
1327
1328       RFC 1143
1329         Q Method of Implementing TELNET Option Negotiation
1330
1331         http://tools.ietf.org/html/rfc1143
1332
1333       TELNET Option Assignments
1334         http://www.iana.org/assignments/telnet-options
1335

EXAMPLES

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

AUTHOR

1632       Jay Rogers <jay@rgrs.com>
1633

CREDITS

1635       Dave Martin, Dave Cardosi
1636
1638       Copyright 1997, 2000, 2002, 2013, 2021 by Jay Rogers.  All rights
1639       reserved.  This program is free software; you can redistribute it
1640       and/or modify it under the same terms as Perl itself.
1641
1642
1643
1644perl v5.36.0                      2023-01-20                    Net::Telnet(3)
Impressum