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