?? expect.pod
字號:
=head1 NAMEExpect.pm - Expect for Perl=head1 VERSION1.21=head1 SYNOPSIS use Expect; # create an Expect object by spawning another process my $exp = Expect->spawn($command, @params) or die "Cannot spawn $command: $!\n"; # or by using an already opened filehandle (e.g. from Net::Telnet) my $exp = Expect->exp_init(\*FILEHANDLE); # if you prefer the OO mindset: my $exp = new Expect; $exp->raw_pty(1); $exp->spawn($command, @parameters) or die "Cannot spawn $command: $!\n"; # send some string there: $exp->send("string\n"); # or, for the filehandle mindset: print $exp "string\n"; # then do some pattern matching with either the simple interface $patidx = $exp->expect($timeout, @match_patterns); # or multi-match on several spawned commands with callbacks, # just like the Tcl version $exp->expect($timeout, [ qr/regex1/ => sub { my $exp = shift; $exp->send("response\n"); exp_continue; } ], [ "regexp2" , \&callback, @cbparms ], ); # if no longer needed, do a soft_close to nicely shut down the command $exp->soft_close(); # or be less patient with $exp->hard_close();Expect.pm is built to either spawn a process or take an existing filehandleand interact with it such that normally interactive tasks can be donewithout operator assistance. This concept makes more sense if you are already familiar with the versatile Tcl version of Expect.The public functions that make up Expect.pm are: Expect->new() Expect::interconnect(@objects_to_be_read_from) Expect::test_handles($timeout, @objects_to_test) Expect::version($version_requested | undef); $object->spawn(@command) $object->clear_accum() $object->set_accum($value) $object->debug($debug_level) $object->exp_internal(0 | 1) $object->notransfer(0 | 1) $object->raw_pty(0 | 1) $object->stty(@stty_modes) # See the IO::Stty docs $object->slave() $object->before(); $object->match(); $object->after(); $object->matchlist(); $object->match_number(); $object->error(); $object->command(); $object->exitstatus(); $object->pty_handle(); $object->do_soft_close(); $object->restart_timeout_upon_receive(0 | 1); $object->interact($other_object, $escape_sequence) $object->log_group(0 | 1 | undef) $object->log_user(0 | 1 | undef) $object->log_file("filename" | $filehandle | \&coderef | undef) $object->manual_stty(0 | 1 | undef) $object->match_max($max_buffersize or undef) $object->pid(); $object->send_slow($delay, @strings_to_send) $object->set_group(@listen_group_objects | undef) $object->set_seq($sequence,\&function,\@parameters);There are several configurable package variables that affect the behavior of Expect. They are: $Expect::Debug; $Expect::Exp_Internal; $Expect::IgnoreEintr; $Expect::Log_Group; $Expect::Log_Stdout; $Expect::Manual_Stty; $Expect::Multiline_Matching; $Expect::Do_Soft_Close;=head1 DESCRIPTION The Expect module is a successor of Comm.pl and a descendent of Chat.pl. Itmore closely ressembles the Tcl Expect language than its predecessors. Itdoes not contain any of the networking code found in Comm.pl. I suspect thiswould be obsolete anyway given the advent of IO::Socket and external toolssuch as netcat.Expect.pm is an attempt to have more of a switch() & case feeling to make decision processing more fluid. Three separate types of debugging have been implemented to make code production easier.It is possible to interconnect multiple file handles (and processes) muchlike Tcl's Expect. An attempt was made to enable all the features of Tcl'sExpect without forcing Tcl on the victim programmer :-) .Please, before you consider using Expect, read the FAQs aboutL</"I want to automate password entry for su/ssh/scp/rsh/..."> andL</"I want to use Expect to automate [anything with a buzzword]...">=head1 USAGE=over 4=item new Expect ()Creates a new Expect object, i.e. a pty. You can change parameters onit before actually spawning a command. This is important if you wantto modify the terminal settings for the slave. See slave() below.The object returned is actually a reblessed IO::Pty filehandle, so seethere for additional methods.=item Expect->exp_init(\*FILEHANDLE) I<or>=item Expect->init(\*FILEHANDLE)Initializes $new_handle_object for use with other Expect functions. It mustbe passed a B<_reference_> to FILEHANDLE if you want it to work properly. IO::File objects are preferable. Returns a reference to the newly createdobject.You can use only real filehandles, certain tied filehandles(e.g. Net::SSH2) that lack a fileno() will not work. Net::Telnetobjects can be used but have been reported to work only for certainhosts. YMMV.=item Expect->spawn($command, @parameters) I<or>=item $object->spawn($command, @parameters) I<or>=item new Expect ($command, @parameters)Forks and execs $command. Returns an Expect object upon success orC<undef> if the fork was unsuccessful or the command could not befound. spawn() passes its parameters unchanged to Perls exec(), solook there for detailed semantics.Note that if spawn cannot exec() the given command, the Expect objectis still valid and the next expect() will see "Cannot exec", so youcan use that for error handling.Also note that you cannot reuse an object with an already spawnedcommand, even if that command has exited. Sorry, but you have toallocate a new object... =item $object->debug(0 | 1 | 2 | 3 | undef)Sets debug level for $object. 1 refers to general debugginginformation, 2 refers to verbose debugging and 0 refers to nodebugging. If you call debug() with no parameters it will return thecurrent debugging level. When the object is created the debugginglevel will match that $Expect::Debug, normally 0.The '3' setting is new with 1.05, and adds the additionalfunctionality of having the _full_ accumulated buffer printed everytime data is read from an Expect object. This was implemented byrequest. I recommend against using this unless you think you need itas it can create quite a quantity of output under some circumstances..=item $object->exp_internal(1 | 0)Sets/unsets 'exp_internal' debugging. This is similar in nature to its Tclcounterpart. It is extremely valuable when debugging expect() sequences.When the object is created the exp_internal setting will match the value of$Expect::Exp_Internal, normally 0. Returns the current setting if calledwithout parameters. It is highly recommended that you make use of thedebugging features lest you have angry code.=item $object->raw_pty(1 | 0)Set pty to raw mode before spawning. This disables echoing, CR->LFtranslation and an ugly hack for broken Solaris TTYs (which send<space><backspace> to slow things down) and thus gives a morepipe-like behaviour (which is important if you want to transfer binarycontent). Note that this must be set I<before> spawning the program.=item $object->stty(qw(mode1 mode2...))Sets the tty mode for $object's associated terminal to the givenmodes. Note that on many systems the master side of the pty is not atty, so you have to modify the slave pty instead, see next item. Thisneeds IO::Stty installed, which is no longer required.=item $object->slave()Returns a filehandle to the slave part of the pty. Very useful in modifyingthe terminal settings: $object->slave->stty(qw(raw -echo));Typical values are 'sane', 'raw', and 'raw -echo'. Note that Irecommend setting the terminal to 'raw' or 'raw -echo', as this avoidsa lot of hassle and gives pipe-like (i.e. transparent) behaviour(without the buffering issue).=item $object->print(@strings) I<or>=item $object->send(@strings)Sends the given strings to the spawned command. Note that the stringsare not logged in the logfile (see print_log_file) but will probablybe echoed back by the pty, depending on pty settings (default is echo)and thus end up there anyway. This must also be taken into accountwhen expect()ing for an answer: the next string will be the commandjust sent. I suggest setting the pty to raw, which disables echo andmakes the pty transparently act like a bidirectional pipe.=item $object->expect($timeout, @match_patterns)or, more like Tcl/Expect, expect($timeout, '-i', [ $obj1, $obj2, ... ], [ $re_pattern, sub { ...; exp_continue; }, @subparms, ], [ 'eof', sub { ... } ], [ 'timeout', sub { ... }, \$subparm1 ], '-i', [ $objn, ...], '-ex', $exact_pattern, sub { ... }, $exact_pattern, sub { ...; exp_continue_timeout; }, '-re', $re_pattern, sub { ... }, '-i', \@object_list, @pattern_list, ...);I<Simple interface:>Given $timeout in seconds Expect will wait for $object's handle to produceone of the match_patterns, which are matched exactly by default. If you want a regexp match, prefix the pattern with '-re'. Due to o/s limitations $timeout should be a round number. If $timeout is 0 Expect will check one time to see if $object's handle contains any of the match_patterns. If $timeout is undef Expectwill wait forever for a pattern to match. If called in a scalar context, expect() will return the position ofthe matched pattern within $match_patterns, or undef if no pattern wasmatched. This is a position starting from 1, so if you want to knowwhich of an array of @matched_patterns matched you should subtract onefrom the return value.If called in an array context expect() will return($matched_pattern_position, $error, $successfully_matching_string,$before_match, and $after_match).$matched_pattern_position will contain the value that would have beenreturned if expect() had been called in a scalar context. $error isthe error that occurred that caused expect() to return. $error willcontain a number followed by a string equivalent expressing the natureof the error. Possible values are undef, indicating no error,'1:TIMEOUT' indicating that $timeout seconds had elapsed without amatch, '2:EOF' indicating an eof was read from $object, '3: spawnid($fileno) died' indicating that the process exited before matchingand '4:$!' indicating whatever error was set in $ERRNO during the lastread on $object's handle or during select(). All handles indicated byset_group plus STDOUT will have all data to come out of $objectprinted to them during expect() if log_group and log_stdout are set.Changed from older versions is the regular expression handling. Bydefault now all strings passed to expect() are treated as literals. Tomatch a regular expression pass '-re' as a parameter in front of thepattern you want to match as a regexp.Example: $object->expect(15, 'match me exactly','-re','match\s+me\s+exactly');This change makes it possible to match literals and regular expressionsin the same expect() call. Also new is multiline matching. ^ will now match the beginning oflines. Unfortunately, because perl doesn't use $/ in determining where lines break using $ to find the end of a line frequently doesn't work. Thisis because your terminal is returning "\r\n" at the end of every line. Oneway to check for a pattern at the end of a line would be to use \r?$ insteadof $. Example: Spawning telnet to a host, you might look for the escapecharacter. telnet would return to you "\r\nEscape character is'^]'.\r\n". To find this you might use $match='^Escape char.*\.\r?$'; $telnet->expect(10,'-re',$match); I<New more Tcl/Expect-like interface:>It's now possible to expect on more than one connection at a time byspecifying 'C<-i>' and a single Expect object or a ref to an arraycontaining Expect objects, e.g. expect($timeout, '-i', $exp1, @patterns_1, '-i', [ $exp2, $exp3 ], @patterns_2_3, )Furthermore, patterns can now be specified as array refs containing[$regexp, sub { ...}, @optional_subprams] . When the pattern matches,the subroutine is called with parameters ($matched_expect_obj,@optional_subparms). The subroutine can return the symbol`exp_continue' to continue the expect matching with timeout startinganew or return the symbol `exp_continue_timeout' for continuing expectwithout resetting the timeout count. $exp->expect($timeout, [ qr/username: /i, sub { my $self = shift; $self->send("$username\n"); exp_continue; }], [ qr/password: /i, sub { my $self = shift; $self->send("$password\n"); exp_continue; }], $shell_prompt);`expect' is now exported by default.=item $object->exp_before() I<or>=item $object->before()before() returns the 'before' part of the last expect() call. If the lastexpect() call didn't match anything, exp_before() will return the entireoutput of the object accumulated before the expect() call finished.Note that this is something different than Tcl Expects before()!!=item $object->exp_after() I<or>=item $object->after()returns the 'after' part of the last expect() call. If the lastexpect() call didn't match anything, exp_after() will return undef().=item $object->exp_match() I<or>=item $object->match()returns the string matched by the last expect() call, undef ifno string was matched.=item $object->exp_match_number() I<or>=item $object->match_number()exp_match_number() returns the number of the pattern matched by the lastexpect() call. Keep in mind that the first pattern in a list of patterns is 1,not 0. Returns undef if no pattern was matched.=item $object->exp_matchlist() I<or>=item $object->matchlist()exp_matchlist() returns a list of matched substrings from the brackets() inside the regexp that last matched. ($object->matchlist)[0]thus corresponds to $1, ($object->matchlist)[1] to $2, etc.=item $object->exp_error() I<or>=item $object->error()exp_error() returns the error generated by the last expect() call ifno pattern was matched. It is typically useful to examine the value returned bybefore() to find out what the output of the object was in determiningwhy it didn't match any of the patterns.=item $object->clear_accum()Clear the contents of the accumulator for $object. This gets rid ofany residual contents of a handle after expect() or send_slow() suchthat the next expect() call will only see new data from $object. Thecontents of the accumulator are returned.=item $object->set_accum($value)Sets the content of the accumulator for $object to $value. Theprevious content of the accumulator is returned.=item $object->exp_command() I<or>=item $object->command()exp_command() returns the string that was used to spawn the command. Helpfulfor debugging and for reused patternmatch subroutines.=item $object->exp_exitstatus() I<or>=item $object->exitstatus()
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -