Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / lib / site_perl / 5.8.0 / Expect.pod
CommitLineData
86530b38
AT
1=head1 NAME
2
3Expect.pm - Expect for Perl
4
5=head1 VERSION
6
71.15
8
9=head1 SYNOPSIS
10
11 use Expect;
12
13 # create an Expect object by spawning another process
14 my $exp = Expect->spawn($command, @params)
15 or die "Cannot spawn $command: $!\n";
16
17 # or by using an already opened filehandle
18 my $exp = Expect->exp_init(\*FILEHANDLE);
19
20 # if you prefer the OO mindset:
21 my $exp = new Expect;
22 $exp->raw_pty(1);
23 $exp->spawn($command, @parameters)
24 or die "Cannot spawn $command: $!\n";
25
26 # send some string there:
27 $exp->send("string\n");
28
29 # or, for the filehandle mindset:
30 print $exp "string\n";
31
32 # then do some pattern matching with either the simple interface
33 $patidx = $exp->expect($timeout, @match_patterns);
34
35 # or multi-match on several spawned commands with callbacks,
36 # just like the Tcl version
37 $exp->expect($timeout,
38 [ qr/regex1/ => sub { my $exp = shift;
39 $exp->send("response\n");
40 exp_continue; } ],
41 [ "regexp2" , \&callback, @cbparms ],
42 );
43
44 # if no longer needed, do a soft_close to nicely shut down the command
45 $exp->soft_close();
46
47 # or be less patient with
48 $exp->hard_close();
49
50Expect.pm is built to either spawn a process or take an existing filehandle
51and interact with it such that normally interactive tasks can be done
52without operator assistance. This concept makes more sense if you are
53already familiar with the versatile Tcl version of Expect.
54The public functions that make up Expect.pm are:
55
56 Expect->new()
57 Expect::interconnect(@objects_to_be_read_from)
58 Expect::test_handles($timeout, @objects_to_test)
59 Expect::version($version_requested | undef);
60 $object->spawn(@command)
61 $object->clear_accum()
62 $object->set_accum($value)
63 $object->debug($debug_level)
64 $object->exp_internal(0 | 1)
65 $object->notransfer(0 | 1)
66 $object->raw_pty(0 | 1)
67 $object->stty(@stty_modes) # See the IO::Stty docs
68 $object->slave()
69 $object->before();
70 $object->match();
71 $object->after();
72 $object->matchlist();
73 $object->match_number();
74 $object->error();
75 $object->command();
76 $object->exitstatus();
77 $object->pty_handle();
78 $object->do_soft_close();
79 $object->restart_timeout_upon_receive(0 | 1);
80 $object->interact($other_object, $escape_sequence)
81 $object->log_group(0 | 1 | undef)
82 $object->log_user(0 | 1 | undef)
83 $object->log_file("filename" | $filehandle | \&coderef | undef)
84 $object->manual_stty(0 | 1 | undef)
85 $object->match_max($max_buffersize or undef)
86 $object->pid();
87 $object->send_slow($delay, @strings_to_send)
88 $object->set_group(@listen_group_objects | undef)
89 $object->set_seq($sequence,\&function,\@parameters);
90
91There are several configurable package variables that affect the behavior of Expect. They are:
92
93 $Expect::Debug;
94 $Expect::Exp_Internal;
95 $Expect::Log_Group;
96 $Expect::Log_Stdout;
97 $Expect::Manual_Stty;
98 $Expect::Multiline_Matching;
99 $Expect::Do_Soft_Close;
100
101=head1 DESCRIPTION
102
103The Expect module is a successor of Comm.pl and a descendent of Chat.pl. It
104more closely ressembles the Tcl Expect language than its predecessors. It
105does not contain any of the networking code found in Comm.pl. I suspect this
106would be obsolete anyway given the advent of IO::Socket and external tools
107such as netcat.
108
109Expect.pm is an attempt to have more of a switch() & case feeling to make
110decision processing more fluid. Three separate types of debugging have
111been implemented to make code production easier.
112
113It is now possible to interconnect multiple file handles (and processes) much
114like Tcl's Expect. An attempt was made to enable all the features of Tcl's
115Expect without forcing Tcl on the victim programmer :-) .
116
117
118=head1 USAGE
119
120=over 4
121
122=item new Expect ()
123
124Creates a new Expect object, i.e. a pty. You can change parameters on
125it before actually spawning a command. This is important if you want
126to modify the terminal settings for the slave. See slave() below.
127The object returned is actually a reblessed IO::Pty filehandle, so see
128there for additional methods.
129
130
131=item Expect->exp_init(\*FILEHANDLE) I<or>
132
133=item Expect->init(\*FILEHANDLE)
134
135Initializes $new_handle_object for use with other Expect functions. It must
136be passed a B<_reference_> to FILEHANDLE if you want it to work properly.
137IO::File objects are preferable. Returns a reference to the newly created
138object.
139
140
141=item Expect->spawn($command, @parameters) I<or>
142
143=item $object->spawn($command, @parameters) I<or>
144
145=item new Expect ($command, @parameters)
146
147Forks and execs $command. Returns an Expect object upon success or
148C<undef> if the fork was unsuccessful or the command could not be
149found. spawn() passes its parameters unchanged to Perls exec(), so
150look there for detailed semantics.
151
152Note that if spawn cannot exec() the given command, the Expect object
153is still valid and the next expect() will see "Cannot exec", so you
154can use that for error handling.
155
156Also note that you cannot reuse an object with an already spawned
157command, even if that command has exited. Sorry, but you have to
158allocate a new object...
159
160
161=item $object->debug(0 | 1 | 2 | 3 | undef)
162
163Sets debug level for $object. 1 refers to general debugging
164information, 2 refers to verbose debugging and 0 refers to no
165debugging. If you call debug() with no parameters it will return the
166current debugging level. When the object is created the debugging
167level will match that $Expect::Debug, normally 0.
168
169The '3' setting is new with 1.05, and adds the additional
170functionality of having the _full_ accumulated buffer printed every
171time data is read from an Expect object. This was implemented by
172request. I recommend against using this unless you think you need it
173as it can create quite a quantity of output under some circumstances..
174
175
176=item $object->exp_internal(1 | 0)
177
178Sets/unsets 'exp_internal' debugging. This is similar in nature to its Tcl
179counterpart. It is extremely valuable when debugging expect() sequences.
180When the object is created the exp_internal setting will match the value of
181$Expect::Exp_Internal, normally 0. Returns the current setting if called
182without parameters. It is highly recommended that you make use of the
183debugging features lest you have angry code.
184
185
186=item $object->raw_pty(1 | 0)
187
188Set pty to raw mode before spawning. This disables echoing and CR->LF
189translation and gives a more pipe-like behaviour. Note that this must
190be set I<before> spawning the program.
191
192
193=item $object->stty(qw(mode1 mode2...))
194
195Sets the tty mode for $object's associated terminal to the given
196modes. Note that on many systems the master side of the pty is not a
197tty, so you have to modify the slave pty instead, see next item. This
198needs IO::Stty installed, which is no longer required.
199
200
201=item $object->slave()
202
203Returns a filehandle to the slave part of the pty. Very useful in modifying
204the terminal settings:
205
206 $object->slave->stty(qw(raw -echo));
207
208Typical values are 'sane', 'raw', and 'raw -echo'. Note that I
209recommend setting the terminal to 'raw' or 'raw -echo', as this avoids
210a lot of hassle and gives pipe-like (i.e. transparent) behaviour
211(without the buffering issue).
212
213
214=item $object->print(@strings) I<or>
215
216=item $object->send(@strings)
217
218Sends the given strings to the spawned command. Note that the strings
219are not logged in the logfile (see print_log_file) but will probably
220be echoed back by the pty, depending on pty settings (default is echo)
221and thus end up there anyway. This must also be taken into account
222when expect()ing for an answer: the next string will be the command
223just sent. I suggest setting the pty to raw, which disables echo and
224makes the pty transparently act like a bidirectional pipe.
225
226
227=item $object->expect($timeout, @match_patterns)
228
229or, more like Tcl/Expect,
230
231 expect($timeout,
232 '-i', [ $obj1, $obj2, ... ],
233 [ $re_pattern, sub { ...; exp_continue; }, @subparms, ],
234 [ 'eof', sub { ... } ],
235 [ 'timeout', sub { ... }, \$subparm1 ],
236 '-i', [ $objn, ...],
237 '-ex', $exact_pattern, sub { ... },
238 $exact_pattern, sub { ...; exp_continue_timeout; },
239 '-re', $re_pattern, sub { ... },
240 '-i', \@object_list, @pattern_list,
241 ...);
242
243I<Simple interface:>
244
245Given $timeout in seconds Expect will wait for $object's handle to produce
246one of the match_patterns. Due to o/s limitations $timeout should be a round
247number. If $timeout is 0 Expect will check one time to see if $object's
248handle contains any of the match_patterns. If $timeout is undef Expect
249will wait forever for a pattern to match.
250
251If called in a scalar context, expect() will return the position of
252the matched pattern within $match_patterns, or undef if no pattern was
253matched. This is a position starting from 1, so if you want to know
254which of an array of @matched_patterns matched you should subtract one
255from the return value.
256
257If called in an array context expect() will return
258($matched_pattern_position, $error, $successfully_matching_string,
259$before_match, and $after_match).
260
261$matched_pattern_position will contain the value that would have been
262returned if expect() had been called in a scalar context. $error is
263the error that occurred that caused expect() to return. $error will
264contain a number followed by a string equivalent expressing the nature
265of the error. Possible values are undef, indicating no error,
266'1:TIMEOUT' indicating that $timeout seconds had elapsed without a
267match, '2:EOF' indicating an eof was read from $object, '3: spawn
268id($fileno) died' indicating that the process exited before matching
269and '4:$!' indicating whatever error was set in $ERRNO during the last
270read on $object's handle. All handles indicated by set_group plus
271STDOUT will have all data to come out of $object printed to them
272during expect() if log_group and log_stdout are set.
273
274Changed from older versions is the regular expression handling. By
275default now all strings passed to expect() are treated as literals. To
276match a regular expression pass '-re' as a parameter in front of the
277pattern you want to match as a regexp.
278
279Example:
280
281 $object->expect(15, 'match me exactly','-re','match\s+me\s+exactly');
282
283This change makes it possible to match literals and regular expressions
284in the same expect() call.
285
286Also new is multiline matching. ^ will now match the beginning of
287lines. Unfortunately, because perl doesn't use $/ in determining where
288lines break using $ to find the end of a line frequently doesn't work. This
289is because your terminal is returning "\r\n" at the end of every line. One
290way to check for a pattern at the end of a line would be to use \r?$ instead
291of $.
292
293Example: Spawning telnet to a host, you might look for the escape
294character. telnet would return to you "\r\nEscape character is
295'^]'.\r\n". To find this you might use $match='^Escape char.*\.\r?$';
296
297 $telnet->expect(10,'-re',$match);
298
299
300I<New more Tcl/Expect-like interface:>
301
302It's now possible to expect on more than one connection at a time by
303specifying 'C<-i>' and a single Expect object or a ref to an array
304containing Expect objects, e.g.
305
306 expect($timeout,
307 '-i', $exp1, @patterns_1,
308 '-i', [ $exp2, $exp3 ], @patterns_2_3,
309 )
310
311Furthermore, patterns can now be specified as array refs containing
312[$regexp, sub { ...}, @optional_subprams] . When the pattern matches,
313the subroutine is called with parameters ($matched_expect_obj,
314@optional_subparms). The subroutine can return the symbol
315`exp_continue' to continue the expect matching with timeout starting
316anew or return the symbol `exp_continue_timeout' for continuing expect
317without resetting the timeout count.
318
319 $exp->expect($timeout,
320 [ qr/username: /i, sub { my $self = shift;
321 $self->send("$username\n");
322 exp_continue; }],
323 [ qr/password: /i, sub { my $self = shift;
324 $self->send("$password\n");
325 exp_continue; }],
326 $shell_prompt);
327
328
329`expect' is now exported by default.
330
331
332=item $object->exp_before() I<or>
333
334=item $object->before()
335
336before() returns the 'before' part of the last expect() call. If the last
337expect() call didn't match anything, exp_before() will return the entire
338output of the object accumulated before the expect() call finished.
339
340
341=item $object->exp_after() I<or>
342
343=item $object->after()
344
345returns the 'after' part of the last expect() call. If the last
346expect() call didn't match anything, exp_after() will return undef().
347
348
349=item $object->exp_match() I<or>
350
351=item $object->match()
352
353returns the string matched by the last expect() call, undef if
354no string was matched.
355
356
357=item $object->exp_match_number() I<or>
358
359=item $object->match_number()
360
361exp_match_number() returns the number of the pattern matched by the last
362expect() call. Keep in mind that the first pattern in a list of patterns is 1,
363not 0. Returns undef if no pattern was matched.
364
365
366=item $object->exp_matchlist() I<or>
367
368=item $object->matchlist()
369
370exp_matchlist() returns a list of matched substrings from the brackets
371() inside the regexp that last matched. ($object->matchlist)[0]
372thus corresponds to $1, ($object->matchlist)[1] to $2, etc.
373
374
375=item $object->exp_error() I<or>
376
377=item $object->error()
378
379exp_error() returns the error generated by the last expect() call if
380no pattern was matched. It is typically useful to examine the value returned by
381before() to find out what the output of the object was in determining
382why it didn't match any of the patterns.
383
384
385=item $object->clear_accum()
386
387Clear the contents of the accumulator for $object. This gets rid of
388any residual contents of a handle after expect() or send_slow() such
389that the next expect() call will only see new data from $object. The
390contents of the accumulator are returned.
391
392
393=item $object->set_accum($value)
394
395Sets the content of the accumulator for $object to $value. The
396previous content of the accumulator is returned.
397
398
399=item $object->exp_command() I<or>
400
401=item $object->command()
402
403exp_command() returns the string that was used to spawn the command. Helpful
404for debugging and for reused patternmatch subroutines.
405
406
407=item $object->exp_exitstatus() I<or>
408
409=item $object->exitstatus()
410
411Returns the exit status of $object (if it already exited).
412
413
414=item $object->exp_pty_handle() I<or>
415
416=item $object->pty_handle()
417
418Returns a string representation of the attached pty, for example:
419`spawn id(5)' (pty has fileno 5), `handle id(7)' (pty was initialized
420from fileno 7) or `STDIN'. Useful for debugging.
421
422
423=item $object->restart_timeout_upon_receive(0 | 1)
424
425If this is set to 1, the expect timeout is retriggered whenever something
426is received from the spawned command. This allows to perform some
427aliveness testing and still expect for patterns.
428
429 $exp->restart_timeout_upon_receive(1);
430 $exp->expect($timeout,
431 [ timeout => \&report_timeout ],
432 [ qr/pattern/ => \&handle_pattern],
433 );
434
435Now the timeout isn't triggered if the command produces any kind of output,
436i.e. is still alive, but you can act upon patterns in the output.
437
438
439=item $object->notransfer(1 | 0)
440
441Do not truncate the content of the accumulator after a match.
442Normally, the accumulator is set to the remains that come after the
443matched string. Note that this setting is per object and not per
444pattern, so if you want to have normal acting patterns that truncate
445the accumulator, you have to add a
446
447 $exp->set_accum($exp->after);
448
449to their callback, e.g.
450
451 $exp->notransfer(1);
452 $exp->expect($timeout,
453 # accumulator not truncated, pattern1 will match again
454 [ "pattern1" => sub { my $self = shift;
455 ...
456 } ],
457 # accumulator truncated, pattern2 will not match again
458 [ "pattern2" => sub { my $self = shift;
459 ...
460 $self->set_accum($self->after());
461 } ],
462 );
463
464This is only a temporary fix until I can rewrite the pattern matching
465part so it can take that additional -notransfer argument.
466
467
468=item Expect::interconnect(@objects);
469
470Read from @objects and print to their @listen_groups until an escape sequence
471is matched from one of @objects and the associated function returns 0 or undef.
472The special escape sequence 'EOF' is matched when an object's handle returns
473an end of file. Note that it is not necessary to include objects that only
474accept data in @objects since the escape sequence is _read_ from an object.
475Further note that the listen_group for a write-only object is always empty.
476Why would you want to have objects listening to STDOUT (for example)?
477By default every member of @objects _as well as every member of its listen
478group_ will be set to 'raw -echo' for the duration of interconnection.
479Setting $object->manual_stty() will stop this behavior per object.
480The original tty settings will be restored as interconnect exits.
481
482For a generic way to interconnect processes, take a look at L<IPC::Run>.
483
484
485=item Expect::test_handles(@objects)
486
487Given a set of objects determines which objects' handles have data ready
488to be read. B<Returns an array> who's members are positions in @objects that
489have ready handles. Returns undef if there are no such handles ready.
490
491
492=item Expect::version($version_requested or undef);
493
494Returns current version of Expect. As of .99 earlier versions are not
495supported. Too many things were changed to make versioning possible.
496
497
498=item $object->interact( C<\*FILEHANDLE, $escape_sequence>)
499
500interact() is essentially a macro for calling interconnect() for
501connecting 2 processes together. \*FILEHANDLE defaults to \*STDIN and
502$escape_sequence defaults to undef. Interaction ceases when $escape_sequence
503is read from B<FILEHANDLE>, not $object. $object's listen group will
504consist solely of \*FILEHANDLE for the duration of the interaction.
505\*FILEHANDLE will not be echoed on STDOUT.
506
507
508=item $object->log_group(0 | 1 | undef)
509
510Set/unset logging of $object to its 'listen group'. If set all objects
511in the listen group will have output from $object printed to them during
512$object->expect(), $object->send_slow(), and C<Expect::interconnect($object
513, ...)>. Default value is on. During creation of $object the setting will
514match the value of $Expect::Log_Group, normally 1.
515
516
517=item $object->log_user(0 | 1 | undef) I<or>
518
519=item $object->log_stdout(0 | 1 | undef)
520
521Set/unset logging of object's handle to STDOUT. This corresponds to Tcl's
522log_user variable. Returns current setting if called without parameters.
523Default setting is off for initialized handles. When a process object is
524created (not a filehandle initialized with exp_init) the log_stdout setting
525will match the value of $Expect::Log_Stdout variable, normally 1.
526If/when you initialize STDIN it is usually associated with a tty which
527will by default echo to STDOUT anyway, so be careful or you will have
528multiple echoes.
529
530
531=item $object->log_file("filename" | $filehandle | \&coderef | undef)
532
533Log session to a file. All characters send to or received from the
534spawned process are written to the file. Normally appends to the
535logfile, but you can pass an additional mode of "w" to truncate the
536file upon open():
537
538 $object->log_file("filename", "w");
539
540Returns the logfilehandle.
541
542If called with an undef value, stops logging and closes logfile:
543
544 $object->log_file(undef);
545
546If called without argument, returns the logfilehandle:
547
548 $fh = $object->log_file();
549
550Can be set to a code ref, which will be called instead of printing
551to the logfile:
552
553 $object->log_file(\&myloggerfunc);
554
555
556=item $object->print_log_file(@strings)
557
558Prints to logfile (if opened) or calls the logfile hook function.
559This allows the user to add arbitraty text to the logfile. Note that
560this could also be done as $object->log_file->print() but would only
561work for log files, not code hooks.
562
563
564=item $object->set_seq($sequence, \&function, \@function_parameters)
565
566During Expect->interconnect() if $sequence is read from $object &function
567will be executed with parameters @function_parameters. It is B<_highly
568recommended_> that the escape sequence be a single character since the
569likelihood is great that the sequence will be broken into to separate reads
570from the $object's handle, making it impossible to strip $sequence from
571getting printed to $object's listen group. \&function should be something
572like 'main::control_w_function' and @function_parameters should be an
573array defined by the caller, passed by reference to set_seq().
574Your function should return a non-zero value if execution of interconnect()
575is to resume after the function returns, zero or undefined if interconnect()
576should return after your function returns.
577The special sequence 'EOF' matches the end of file being reached by $object.
578See interconnect() for details.
579
580
581=item $object->set_group(@listener_objects)
582
583@listener_objects is the list of objects that should have their handles
584printed to by $object when Expect::interconnect, $object->expect() or
585$object->send_slow() are called. Calling w/out parameters will return
586the current list of the listener objects.
587
588
589=item $object->manual_stty(0 | 1 | undef)
590
591Sets/unsets whether or not Expect should make reasonable guesses as to
592when and how to set tty parameters for $object. Will match
593$Expect::Manual_Stty value (normally 0) when $object is created. If called
594without parameters manual_stty() will return the current manual_stty setting.
595
596
597=item $object->match_max($maximum_buffer_length | undef) I<or>
598
599=item $object->max_accum($maximum_buffer_length | undef)
600
601Set the maximum accumulator size for object. This is useful if you think
602that the accumulator will grow out of hand during expect() calls. Since
603the buffer will be matched by every match_pattern it may get slow if the
604buffer gets too large. Returns current value if called without parameters.
605Not defined by default.
606
607
608=item $object->notransfer(0 | 1)
609
610If set, matched strings will not be deleted from the accumulator.
611Returns current value if called without parameters. False by default.
612
613
614=item $object->exp_pid() I<or>
615
616=item $object->pid()
617
618Return pid of $object, if one exists. Initialized filehandles will not have
619pids (of course).
620
621
622=item $object->send_slow($delay, @strings);
623
624print each character from each string of @strings one at a time with $delay
625seconds before each character. This is handy for devices such as modems
626that can be annoying if you send them data too fast. After each character
627$object will be checked to determine whether or not it has any new data ready
628and if so update the accumulator for future expect() calls and print the
629output to STDOUT and @listen_group if log_stdout and log_group are
630appropriately set.
631
632=back
633
634=head2 Configurable Package Variables:
635
636=item $Expect::Debug
637
638Defaults to 0. Newly created objects have a $object->debug() value
639of $Expect::Debug. See $object->debug();
640
641=item $Expect::Do_Soft_Close
642
643Defaults to 0. When destroying objects, soft_close may take up to half
644a minute to shut everything down. From now on, only hard_close will
645be called, which is less polite but still gives the process a chance
646to terminate properly. Set this to '1' for old behaviour.
647
648=item $Expect::Exp_Internal
649
650Defaults to 0. Newly created objects have a $object->exp_internal()
651value of $Expect::Exp_Internal. See $object->exp_internal().
652
653=item $Expect::Log_Group
654
655Defaults to 1. Newly created objects have a $object->log_group()
656value of $Expect::Log_Group. See $object->log_group().
657
658=item $Expect::Log_Stdout
659
660Defaults to 1 for spawned commands, 0 for file handles
661attached with exp_init(). Newly created objects have a
662$object->log_stdout() value of $Expect::Log_Stdout. See
663$object->log_stdout().
664
665=item $Expect::Manual_Stty
666
667Defaults to 0. Newly created objects have a $object->manual_stty()
668value of $Expect::Manual_Stty. See $object->manual_stty().
669
670=item $Expect::Multiline_Matching
671
672 Defaults to 1. Affects whether or not expect() uses the /m flag for
673doing regular expression matching. If set to 1 /m is used.
674 This makes a difference when you are trying to match ^ and $. If
675you have this on you can match lines in the middle of a page of output
676using ^ and $ instead of it matching the beginning and end of the entire
677expression. I think this is handy.
678
679
680=head1 CONTRIBUTIONS
681
682Lee Eakin <leakin@japh.itg.ti.com> has ported the kibitz script
683from Tcl/Expect to Perl/Expect. You can find it in the examples/
684subdir. Thanks Lee!
685
686Historical notes:
687
688There are still a few lines of code dating back to the inspirational
689Comm.pl and Chat.pl modules without which this would not have been possible.
690Kudos to Eric Arnold <Eric.Arnold@Sun.com> and Randal 'Nuke your NT box with
691one line of perl code' Schwartz<merlyn@stonehenge.com> for making these
692available to the perl public.
693
694As of .98 I think all the old code is toast. No way could this have been done
695without it though. Special thanks to Graham Barr for helping make sense of
696the IO::Handle stuff as well as providing the highly recommended IO::Tty
697module.
698
699
700=head1 REFERENCES
701
702Mark Rogaski <rogaski@att.com> wrote:
703
704"I figured that you'd like to know that Expect.pm has been very
705useful to AT&T Labs over the past couple of years (since I first talked to
706Austin about design decisions). We use Expect.pm for managing
707the switches in our network via the telnet interface, and such automation
708has significantly increased our reliability. So, you can honestly say that
709one of the largest digital networks in existence (AT&T Frame Relay) uses
710Expect.pm quite extensively."
711
712
713=head1 FAQ - Frequently Asked Questions
714
715This is a growing collection of things that might help.
716Please send you questions that are not answered here to
717RGiersig@cpan.org
718
719
720=head2 What systems does Expect run on?
721
722Expect itself doesn't have real system dependencies, but the underlying
723IO::Tty needs pseudoterminals. IO::Stty uses POSIX.pm and Fcntl.pm.
724
725I have used it on Solaris, Linux and AIX, others report *BSD and OSF
726as working. Generally, any modern POSIX Unix should do, but there
727are exceptions to every rule. Feedback is appreciated.
728
729See L<IO::Tty> for a list of verified systems.
730
731
732=head2 Can I use this module with ActivePerl on Windows?
733
734Up to now, the answer was 'No', but this has changed.
735
736You still cannot use ActivePerl, but if you use the Cygwin environment
737(http://sources.redhat.com), which brings its own perl, and have
738the latest IO::Tty (v0.05 or later) installed, it should work (feedback
739appreciated).
740
741
742=head2 The examples in the tutorial don't work!
743
744The tutorial is hopelessly out of date and needs a serious overhaul.
745I appologize for this, I have concentrated my efforts mainly on the
746functionality. Volunteers welcomed.
747
748
749=head2 How can I find out what Expect is doing?
750
751If you set
752
753 $Expect::Exp_Internal = 1;
754
755Expect will tell you very verbosely what it is receiving and sending,
756what matching it is trying and what it found. You can do this on a
757per-command base with
758
759 $exp->exp_internal(1);
760
761You can also set
762
763 $Expect::Debug = 1; # or 2, 3 for more verbose output
764
765or
766
767 $exp->debug(1);
768
769which gives you even more output.
770
771
772=head2 I am seeing the output of the command I spawned. Can I turn that off?
773
774Yes, just set
775
776 $Expect::Log_Stdout = 0;
777
778to globally disable it or
779
780 $exp->log_stdout(0);
781
782for just that command. 'log_user' is provided as an alias so
783Tcl/Expect user get a DWIM experience... :-)
784
785
786=head2 No, I mean that when I send some text to the spawned process, it gets echoed back and I have to deal with it in the next expect.
787
788This is caused by the pty, which has probably 'echo' enabled. A
789solution would be to set the pty to raw mode, which in general is
790cleaner for communication between two programs (no more unexpected
791character translations). Unfortunately this would break a lot of old
792code that sends "\r" to the program instead of "\n" (translating this
793is also handled by the pty), so I won't add this to Expect just like that.
794But feel free to experiment with C<$exp-E<gt>raw_pty(1)>.
795
796
797=head2 How do I send control characters to a process?
798
799A: You can send any characters to a process with the print command. To
800represent a control character in Perl, use \c followed by the letter. For
801example, control-G can be represented with "\cG" . Note that this will not
802work if you single-quote your string. So, to send control-C to a process in
803$exp, do:
804
805 print $exp "\cC";
806
807Or, if you prefer:
808
809 $exp->send("\cC");
810
811The ability to include control characters in a string like this is provided
812by Perl, not by Expect.pm . Trying to learn Expect.pm without a thorough
813grounding in Perl can be very daunting. We suggest you look into some of
814the excellent Perl learning material, such as the books _Programming Perl_
815and _Learning Perl_ by O'Reilly, as well as the extensive online Perl
816documentation available through the perldoc command.
817
818
819=head2 My script fails from time to time without any obvious reason. It seems that I am sometimes loosing output from the spawned program.
820
821You could be exiting too fast without giving the spawned program
822enough time to finish. Try adding $exp->soft_close() to terminate the
823program gracefully or do an expect() for 'eof'.
824
825Alternatively, try adding a 'sleep 1' after you spawn() the program.
826It could be that pty creation on your system is just slow (but this is
827rather improbable if you are using the latest IO-Tty).
828
829
830=head2 I want to automate password entry for su/ssh/scp/rsh/...
831
832You shouldn't use Expect for this. Putting passwords, especially
833root passwords, into scripts in clear text can mean severe security
834problems. I strongly recommend using other means. For 'su', consider
835switching to 'sudo', which gives you root access on a per-command and
836per-user basis without the need to enter passwords. 'ssh'/'scp' can be
837set up with RSA authentication without passwords. 'rsh' can use
838the .rhost mechanism, but I'd strongly suggest to switch to 'ssh'; to
839mention 'rsh' and 'security' in the same sentence makes an oxymoron.
840
841It will work for 'telnet', though, and there are valid uses for it,
842but you still might want to consider using 'ssh', as keeping cleartext
843passwords around is very insecure.
844
845
846=head2 I want to use Expect to automate [anything with a buzzword]...
847
848Are you sure there is no other, easier way? As a rule of thumb,
849Expect is useful for automating things that expect to talk to a human,
850where no formal standard applies. For other tasks that do follow a
851well-defined protocol, there are often better-suited modules that
852already can handle those protocols. Don't try to do HTTP requests by
853spawning telnet to port 80, use LWP instead. To automate FTP, take a
854look at L<Net::FTP> or C<ncftp> (http://www.ncftp.org). You don't use
855a screwdriver to hammer in your nails either, or do you?
856
857
858=head2 I want to log the whole session to a file.
859
860Use
861
862 $exp->log_file("filename");
863
864or
865
866 $exp->log_file($filehandle);
867
868or even
869
870 $exp->log_file(\&log_procedure);
871
872for maximum flexibility.
873
874Note that the logfile is appended to by default, but you can
875specify an optional mode "w" to truncate the logfile:
876
877 $exp->log_file("filename", "w");
878
879To stop logging, just call it with a false argument:
880
881 $exp->log_file(undef);
882
883
884=head2 How can I turn off multi-line matching for my regexps?
885
886To globally unset multi-line matching for all regexps:
887
888 $Expect::Multiline_Matching = 0;
889
890You can do that on a per-regexp basis by stating C<(?-m)> inside the regexp
891(you need perl5.00503 or later for that).
892
893
894=head2 How can I expect on multiple spawned commands?
895
896You can use the B<-i> parameter to specify a single object or a list
897of Expect objects. All following patterns will be evaluated against
898that list.
899
900You can specify B<-i> multiple times to create groups of objects
901and patterns to match against within the same expect statement.
902
903This works just like in Tcl/Expect.
904
905See the source example below.
906
907
908=head2 I seem to have problems with ptys!
909
910Well, pty handling is really a black magic, as it is extremely system
911dependend. I have extensively revised IO-Tty, so these problems
912should be gone.
913
914If your system is listed in the "verified" list of IO::Tty, you
915probably have some non-standard setup, e.g. you compiled your
916Linux-kernel yourself and disabled ptys. Please ask your friendly
917sysadmin for help.
918
919If your system is not listed, unpack the latest version of IO::Tty,
920do a 'perl Makefile.PL; make; make test; uname C<-a>' and send me the
921results and I'll see what I can deduce from that.
922
923
924=head2 I just want to read the output of a process without expect()ing anything. How can I do this?
925
926[ Are you sure you need Expect for this? How about qx() or open("prog|")? ]
927
928By using expect without any patterns to match.
929
930 $process->expect(undef); # Forever until EOF
931 $process->expect($timeout); # For a few seconds
932 $process->expect(0); # Is there anything ready on the handle now?
933
934
935=head2 Ok, so now how do I get what was read on the handle?
936
937 $read = $process->before();
938
939
940=head2 Where's IO::Pty?
941
942Find it on CPAN as IO-Tty, which provides both.
943
944
945=head2 How come when I automate the passwd program to change passwords for me passwd dies before changing the password sometimes/every time?
946
947What's happening is you are closing the handle before passwd exits.
948When you close the handle to a process, it is sent a signal (SIGPIPE?)
949telling it that STDOUT has gone away. The default behavior for
950processes is to die in this circumstance. Two ways you can make this
951not happen are:
952
953 $process->soft_close();
954
955This will wait 15 seconds for a process to come up with an EOF by
956itself before killing it.
957
958 $process->expect(undef);
959
960This will wait forever for the process to match an empty set of
961patterns. It will return when the process hits an EOF.
962
963As a rule, you should always expect() the result of your transaction
964before you continue with processing.
965
966
967=head2 How come when I try to make a logfile with log_file() or set_group() it doesn't print anything after the last time I run expect()?
968
969Output is only printed to the logfile/group when Expect reads from the
970process, during expect(), send_slow() and interconnect().
971One way you can force this is to make use of
972
973 $process->expect(undef);
974
975and
976
977 $process->expect(0);
978
979which will make expect() run with an empty pattern set forever or just
980for an instant to capture the output of $process. The output is
981available in the accumulator, so you can grab it using
982$process->before().
983
984
985=head2 I seem to have problems with terminal settings, double echoing, etc.
986
987Tty settings are a major pain to keep track of. If you find unexpected
988behavior such as double-echoing or a frozen session, doublecheck the
989documentation for default settings. When in doubt, handle them
990yourself using $exp->stty() and manual_stty() functions. As of .98
991you shouldn't have to worry about stty settings getting fouled unless
992you use interconnect or intentionally change them (like doing -echo to
993get a password).
994
995If you foul up your terminal's tty settings, kill any hung processes
996and enter 'stty sane' at a shell prompt. This should make your
997terminal manageable again.
998
999Note that IO::Tty returns ptys with your systems default setting
1000regarding echoing, CRLF translation etc. and Expect does not change
1001them. I have considered setting the ptys to 'raw' without any
1002translation whatsoever, but this would break a lot of existing things,
1003as '\r' translation would not work anymore. On the other hand, a raw
1004pty works much like a pipe and is more WYGIWYE (what you get is what
1005you expect), so I suggest you set it to 'raw' by yourself:
1006
1007 $exp = new Expect;
1008 $exp->raw_pty(1);
1009 $exp->spawn(...);
1010
1011To disable echo:
1012
1013 $exp->slave->stty(qw(-echo));
1014
1015
1016=head2 I'm spawning a telnet/ssh session and then let the user interact with it. But screen-oriented applications on the other side don't work properly.
1017
1018You have to set the terminal screen size for that. Luckily, IO::Pty
1019already has a method for that, so modify your code to look like this:
1020
1021 my $exp = new Expect;
1022 $exp->slave->clone_winsize_from(\*STDIN);
1023 $exp->spawn("telnet somehost);
1024
1025Also, some applications need the TERM shell variable set so they know
1026how to move the cursor across the screen. When logging in, the remote
1027shell sends a query (Ctrl-Z I think) and expects the terminal to
1028answer with a string, e.g. 'xterm'. If you really want to go that way
1029(be aware, madness lies at its end), you can handle that and send back
1030the value in $ENV{TERM}. This is only a hand-waving explanation,
1031please figure out the details by yourself.
1032
1033
1034=head2 I set the terminal size as explained above, but if I resize the window, the application does not notice this.
1035
1036You have to catch the signal WINCH ("window size changed"), change the
1037terminal size and propagate the signal to the spawned application:
1038
1039 my $exp = new Expect;
1040 $exp->slave->clone_winsize_from(\*STDIN);
1041 $exp->spawn("ssh somehost);
1042 $SIG{WINCH} = \&winch;
1043
1044 sub winch {
1045 $exp->slave->clone_winsize_from(\*STDIN);
1046 kill WINCH => $exp->pid if $exp->pid;
1047 $SIG{WINCH} = \&winch;
1048 }
1049
1050 $exp->interact();
1051
1052
1053=head2 I noticed that the test uses a string that resembles, but not exactly matches, a well-known sentence that contains every character. What does that mean?
1054
1055That means you are anal-retentive. :-) [Gotcha there!]
1056
1057
1058=head2 I get a "Could not assign a pty" error when running as a non-root user on an IRIX box?
1059
1060The OS may not be configured to grant additional pty's (pseudo terminals)
1061to non-root users. /usr/sbin/mkpts should be 4755, not 700 for this
1062to work. I don't know about security implications if you do this.
1063
1064
1065=head2 How come I don't notice when the spawned process closes its stdin/out/err??
1066
1067You are probably on one of the systems where the master doesn't get an
1068EOF when the slave closes stdin/out/err.
1069
1070One possible solution is when you spawn a process, follow it with a
1071unique string that would indicate the process is finished.
1072
1073 $process = Expect->spawn('telnet somehost; echo ____END____');
1074
1075And then $process->expect($timeout,'____END____','other','patterns');
1076
1077
1078=head1 Source Examples
1079
1080
1081=head2 How to automate login
1082
1083 my $exp = Expect->spawn("telnet localhost")
1084 or die "Cannot spawn telnet: $!\n";;
1085 my $spawn_ok;
1086 $exp->expect($timeout,
1087 [
1088 qr'login: $',
1089 sub {
1090 $spawn_ok = 1;
1091 my $fh = shift;
1092 $fh->send("$username\n");
1093 exp_continue;
1094 }
1095 ],
1096 [
1097 'Password: $',
1098 sub {
1099 my $fh = shift;
1100 print $fh "$password\n";
1101 exp_continue;
1102 }
1103 ],
1104 [
1105 eof =>
1106 sub {
1107 if ($spawn_ok) {
1108 die "ERROR: premature EOF in login.\n";
1109 } else {
1110 die "ERROR: could not spawn telnet.\n";
1111 }
1112 }
1113 ],
1114 [
1115 timeout =>
1116 sub {
1117 die "No login.\n";
1118 }
1119 ],
1120 '-re', qr'[#>:] $', #' wait for shell prompt, then exit expect
1121 );
1122
1123
1124=head2 How to expect on multiple spawned commands
1125
1126 foreach my $cmd (@list_of_commands) {
1127 push @commands, Expect->spawn($cmd);
1128 }
1129
1130 expect($timeout,
1131 '-i', \@commands,
1132 [
1133 qr"pattern", # find this pattern in output of all commands
1134 sub {
1135 my $obj = shift; # object that matched
1136 print $obj "something\n";
1137 exp_continue; # we don't want to terminate the expect call
1138 }
1139 ],
1140 '-i', $some_other_command,
1141 [
1142 "some other pattern",
1143 sub {
1144 my ($obj, $parmref) = @_;
1145 # ...
1146
1147 # now we exit the expect command
1148 },
1149 \$parm
1150 ],
1151 );
1152
1153
1154=head2 How to propagate terminal sizes
1155
1156 my $exp = new Expect;
1157 $exp->slave->clone_winsize_from(\*STDIN);
1158 $exp->spawn("ssh somehost);
1159 $SIG{WINCH} = \&winch;
1160
1161 sub winch {
1162 $exp->slave->clone_winsize_from(\*STDIN);
1163 kill WINCH => $exp->pid if $exp->pid;
1164 $SIG{WINCH} = \&winch;
1165 }
1166
1167 $exp->interact();
1168
1169
1170
1171=head1 HOMEPAGE
1172
1173http://sourceforge.net/projects/expectperl/
1174
1175
1176=head1 MAILING LISTS
1177
1178There are two mailing lists available, expectperl-announce and
1179expectperl-discuss, at
1180
1181 http://lists.sourceforge.net/lists/listinfo/expectperl-announce
1182
1183and
1184
1185 http://lists.sourceforge.net/lists/listinfo/expectperl-discuss
1186
1187
1188=head1 AUTHORS
1189
1190(c) 1997 Austin Schutz E<lt>F<ASchutz@users.sourceforge.net>E<gt> (retired)
1191
1192expect() interface & functionality enhancements (c) 1999-2002 Roland Giersig.
1193
1194This module is now maintained by Roland Giersig E<lt>F<RGiersig@cpan.org>E<gt>
1195
1196
1197=head1 LICENSE
1198
1199This module can be used under the same terms as Perl.
1200
1201
1202=head1 DISCLAIMER
1203
1204THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
1205WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
1206MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1207IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
1208INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
1209BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
1210OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
1211ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
1212TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
1213USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
1214DAMAGE.
1215
1216In other words: Use at your own risk. Provided as is. Your mileage
1217may vary. Read the source, Luke!
1218
1219And finally, just to be sure:
1220
1221Any Use of This Product, in Any Manner Whatsoever, Will Increase the
1222Amount of Disorder in the Universe. Although No Liability Is Implied
1223Herein, the Consumer Is Warned That This Process Will Ultimately Lead
1224to the Heat Death of the Universe.
1225
1226=cut