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