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