1Net::SSH::Expect(3)   User Contributed Perl Documentation  Net::SSH::Expect(3)
2
3
4

NAME

6       Net::SSH::Expect - SSH wrapper to execute remote commands
7

SYNOPSIS

9               use Net::SSH::Expect;
10
11               #
12               # You can do SSH authentication with user-password or without it.
13               #
14
15               # Making an ssh connection with user-password authentication
16               # 1) construct the object
17               my $ssh = Net::SSH::Expect->new (
18                   host => "myserver.com",
19                   password=> 'pass87word',
20                   user => 'bnegrao',
21                   raw_pty => 1
22               );
23
24               # 2) logon to the SSH server using those credentials.
25               # test the login output to make sure we had success
26               my $login_output = $ssh->login();
27               if ($login_output !~ /Welcome/) {
28                   die "Login has failed. Login output was $login_output";
29               }
30
31               # - now you know you're logged in - #
32
33               # Starting ssh without password
34               # 1) run the constructor
35               my $ssh = Net::SSH::Expect->new (
36                   host => "myserver.com",
37                   user => 'bnegrao',
38                   raw_pty => 1
39               );
40               # 2) now start the ssh process
41               $ssh->run_ssh() or die "SSH process couldn't start: $!";
42
43               # 3) you should be logged on now. Test if you received the remote prompt:
44               ($ssh->read_all(2) =~ />\s*\z/) or die "where's the remote prompt?"
45
46               # - now you know you're logged in - #
47
48               # disable terminal translations and echo on the SSH server
49               # executing on the server the stty command:
50               $ssh->exec("stty raw -echo");
51
52               # runs arbitrary commands and print their outputs
53               # (including the remote prompt comming at the end)
54               my $ls = $ssh->exec("ls -l /");
55               print($ls);
56
57               my $who = $ssh->exec("who");
58               print ($who);
59
60               # When running a command that causes a huge output,
61               # lets get the output line by line:
62               $ssh->send("find /");   # using send() instead of exec()
63               my $line;
64               # returns the next line, removing it from the input stream:
65               while ( defined ($line = $ssh->read_line()) ) {
66                   print $line . "\n";
67               }
68
69               # take a look in what is immediately available on the input stream
70               print $ssh->peek(0);    # you'll probably see the remote prompt
71
72               # the last read_line() on the previous loop will not include the
73               # remote prompt that appears at the end of the output, because the prompt
74               # doesn't end with a '\n' character. So let's remove the remainder
75               # prompt from the input stream:
76               $ssh->eat($ssh->peek(0));  # removes whatever is on the input stream now
77
78               # We can also iterate over the output in chunks,
79               # printing everything that's available at each 1 second:
80               $ssh->send ("find /home");
81               my $chunk;
82               while ($chunk = $ssh->peek(1)) { # grabs chunks of output each 1 second
83                   print $ssh->eat($chunk);
84               }
85
86               # Now let's run an interactive command, like passwd.
87               # This is done combining send() and waitfor() methods together:
88               $ssh->send("passwd");
89               $ssh->waitfor('password:\s*\z', 1) or die "prompt 'password' not found after 1 second";
90               $ssh->send("curren_password");
91               $ssh->waitfor(':\s*\z', 1) or die "prompt 'New password:' not found";
92               $ssh->send("new_password");
93               $ssh->waitfor(':\s*\z', 1) or die "prompt 'Confirm new password:' not found";
94               $ssh->send("new_password");
95
96               # check that we have the system prompt again.
97               my ($before_match, $match) = $ssh->waitfor('>\s*\z', 1);  # waitfor() in a list context
98               die "passwd failed. passwd said '$before_match'." unless ($match);
99
100               # closes the ssh connection
101               $ssh->close();
102

DESCRIPTION

104       This module is a wrapper to the ssh executable that is available in
105       your system's $PATH.  Use this module to execute commands on the remote
106       SSH server.  It authenticates with the user and password you passed in
107       the constructor's attributes "user" and "password".
108
109       Once an ssh connection was started using the "connect()" method it will
110       remain open until you call the "close()" method. This allows you
111       execute as many commands as you want with the "exec()" method using
112       only one connection. This is a better approach over other ssh wrapper
113       implementations, i.e: Net::SCP, Net::SSH and Net::SCP::Expect, that
114       start a new ssh connection each time a remote command is issued or a
115       file is transfered.
116
117       It uses Expect.pm module to interact with the SSH server. A
118       "get_expect()" method is provided so you can obtain the internal
119       "Expect" object connected to the SSH server. Use this only if you have
120       some special need that you can't do with the "exec()" method.
121
122       This module was inspired by Net::SCP::Expect
123       http://search.cpan.org/~djberg/Net-SCP-Expect-0.12/Expect.pm
124       <http://search.cpan.org/~djberg/Net-SCP-Expect-0.12/Expect.pm> and by
125       Net::Telnet and some of its methods work the same as these two modules.
126
127   IMPORTANT NOTES ABOUT DEALING WITH SSH AND PSEUDO-TERMINALS
128       This module uses Expect to start the local ssh client process, and
129       Expect will interact with this process through a local pseudo-terminal
130       (ptty). Similarly, the ssh client will connect to the SSH server and
131       there will receive an ssh login process attached to a ptty too.
132
133       During my tests I realized that the I/O to and from the ssh server
134       changes drastically from OS to OS if we let the local and remote pttys
135       configured on their defaults. The echo's and the \r\n translations make
136       a mess that we are never sure what will be sent to the other side and
137       what will be received here.
138
139       Many ptty features are system dependent and we can't rely on them
140       working the same on different OS's.
141
142       To avoid these problems I always recommend you to:
143
144       1) enable the 'raw_pty' constructor attribute. This disables most (if
145       not all) of the problematic features on the local ptty.
146
147       2) Similarly set the ptty on the remote server to 'raw -echo' as soon
148       as you login.  This can be done with:
149
150           $ssh->exec("stty raw -echo");
151
152       Obviously your server must support the 'stty' command for that.
153
154       3) If you won't run on the server interactive commands that prompt for
155       input, like 'passwd', you could prevent the ssh server from attributing
156       a ptty for the ssh login process. This is done by enabling the
157       'no_terminal' constructor attribute. What that does is passing the '-T'
158       option to the ssh client process when it is created. From the BSD ssh
159       client manual:
160           -T      Disable pseudo-tty allocation.
161
162       This will create the cleaner connection possible. You won't have a ptty
163       on the server, and, weirdly, you won't receive a remote prompt. Try
164       yourself 'ssh -T my.ssh.server' to see how it works. Notice that some
165       system commands that rely on a terminal won't work, say, 'who am i',
166       'stty', etc.
167
168       Also, interactive commands like 'passwd' or 'mail' won't be able to
169       print their prompts.
170
171       But other system commands will run better: 'ls -l' will be printed
172       without terminal control characters.  'ps -ef' will have the command
173       lines printed fully, since there is no 'columns' terminal limitation.
174
175       Moral of the story: pseudo terminals do many character translations
176       that can bring some unexpected results in some situations. Avoid them
177       if you can.
178

EXPORT

180       None by default.
181

CONSTRUCTOR ATTRIBUTES

183       The constructor accepts all the following attributes that can be set in
184       the form of attribute => 'value' pairs.  They are presentend in three
185       groups: 1) attributes to configure the ssh client process; 2)
186       attributes to configure the underlying Expect object; 3) attributes to
187       configure this module;
188
189   ATTRIBUTES TO CONFIGURE THE SSH CLIENT PROCESS
190       Some of the attributes bellow will enable/disable some options of the
191       ssh client. Refer to you ssh client documentation to know what each one
192       does.
193
194       string binary
195           the complete path to the 'ssh' executable in your machine. The
196           default is 'ssh' what means the ssh used by default is the first
197           one found in your $PATH environment variable.
198
199       string user
200           the username to login.
201
202       string password
203           the password used to login. You won't need to set this field if you
204           have public-key authentication configured for you ssh user. Read
205           run_ssh() documentation for more info.
206
207       string host
208           the address(dns name/ip) to the ssh server
209
210       string port
211           Feeds the -p ssh client option with alternate ssh port. This option
212           is not set by default.
213
214       boolean no_terminal
215           If enabled adds the -T ssh client option to the ssh command line.
216           See the discussion on "IMPORTANT NOTES ABOUT DEALING WITH SSH AND
217           PSEUDO-TERMINALS" to know if you want to enable this.
218
219       char escape_char
220           Passes a character to the -e ssh client option. This enables ssh
221           escapes. Since this option can cause trouble, it is explicitly
222           turned off by default with a '-e none' option being set on the ssh
223           command line.
224
225       string ssh_option
226           This lets you add your own ssh options to the command line. Set
227           this string to the options you want, like '-v -p 2022', and your
228           options will be added to the ssh command line that will start the
229           ssh process.
230
231   CONSTRUCTOR OPTIONS THAT CONFIGURE THE INTERNAL EXPECT OBJECT
232       The following constructor attributes can be used to configure special
233       features of the internal Expect object used to communicate with the ssh
234       server. These options will be passed to the Expect object inside the
235       "connect" method before it spawns the ssh process.
236
237       string log_file
238           Used as argument to the internal Expect->log_file() method. Default
239           is no logfile.
240
241       boolean log_stdout
242           Used as argument to the internal Expect->log_sdtout() method.
243           Default is 0, to disable log to stdout.
244
245       boolean exp_internal
246           Argument to be passed to the internal Expect->exp_internal()
247           method. Default is 0, to disable the internal exposure.
248
249       boolean exp_debug
250           Argument to be passed to the internal Expect->debug() method.
251           Default is 0, to disable debug.
252
253       boolean raw_pty
254           Argument to be passed to the internal Expect->raw_pty() method.
255           It's recommended that you enable this. See the disscussion in
256           "IMPORTANT NOTES ABOUT DEALING WITH SSH AND PSEUDO-TERMINALS" to
257           know why.  Default is 0 to let the local ptty as its defaults.
258
259       boolean restart_timeout_upon_receive
260           If this is enabled the timeout in all reading operations works as
261           an inactivity timeout - it'll not start counting while there is
262           data arriving on input stream. Default is 0.
263
264   CONSTRUCTOR OPTIONS TO CONFIGURE THIS MODULE
265       string terminator
266           the line terminator in use on the SSH server, this will added at
267           the end of each command passed to the "exec()" method. The default
268           is "\n".
269
270           It also affects the read_line() method, it expect each line to be
271           terminated by the 'teminator' character. Lines can also be ended
272           with "\r" or "\r\n" in some systems.  Remember to adjust this for
273           your system.
274
275           You can also use the terminator() method to set this attribute.
276
277       integer timeout
278           The maximum time to wait for a pattern to show up on input stream
279           before giving up in a read operation. The default is 1 second.
280
281           Timeout must always be an integer >= 0.
282
283           This attribute can also be get/set with the "timeout()" method.
284
285       boolean debug
286           Causes some methods to print debug messages to the STDERR. This
287           feature is not widely implemented yet.  (only eat() implements it
288           until this moment)
289

METHODS

291       boolean run_ssh() - forks the ssh client process
292                   # boolean run_ssh() - forks the ssh client process opening an ssh connection to the SSH server.
293                   #
294                   #       This method has three roles:
295                   #       1)      Instantiate a new Expect object configuring it with all the defaults and user-defined
296                   #               settings.
297                   #       2)      Define the ssh command line using the defaults and user-defined settings
298                   #       3)      Fork the ssh process using the spawn() method of the Expect instance we created.
299                   #               The SSH connection is established on this step using the user account set in the 'user'
300                   #               constructor attribute. No password is sent here, that happens only in the login() method.
301                   #
302                   #       This method is run internally by the login() method so you don't need to run it yourself
303                   #       in most of the cases. You'll run this method alone if you had set up public-key authentication
304                   #       between the ssh client and the ssh server. In this case you only need to call this method
305                   #       to have an authenticated ssh connection, you won't call login(). Note that when you
306                   #       use public-key authentication you won't need to set the 'password' constructor attribute
307                   #       but you still need to define the 'user' attribute.
308                   #       If you don't know how to setup public-key authentication there's a good guide at
309                   #       http://sial.org/howto/openssh/publickey-auth/
310                   #
311                   # returns:
312                   #       boolean: 1 if the ssh ran OK or 0 otherwise. In case of failures, use $! to do get info.
313
314       string login([$login_prompt, $password_prompt] [,$test_success])  -
315       authenticates on the ssh server.
316                   # string login ([$login_prompt, $password_prompt] [,$test_success]) - authenticates on the ssh server.
317                   #       This method responds to the authentication prompt sent by the SSH server.
318                   #       You can customize the "Login:" and "Password:" prompts that must be expected by passing their
319                   #       patterns as arguments to this method, although this method has default values that work to most
320                   #       SSH servers out there.
321                   #       It runs the run_ssh() method only if it wasn't run before(), but it'll die
322                   #       if run_ssh() returns false.
323                   #
324                   # param:
325                   #       $login_prompt: A pattern string used to match the "Login:" prompt. The default
326                   #               pattern is qr/ogin:\s*$/
327                   #
328                   #       $password_prompt: A pattern string used to match the "Password:" prompt. The default
329                   #               pattern is qr/[Pp]assword.*?:|[Pp]assphrase.*?:/
330                   #
331                   #       $test_success: 0 | 1. if 1, login will do an extra-test to verify if the password
332                   #               entered was accepted. The test consists in verifying if, after sending the password,
333                   #               the "Password" prompt shows up again what would indicate that the password was rejected.
334                   #               This test is disabled by default.
335                   #
336                   #       OBS: the number of paramaters passed to this method will tell it what parameters are being passed:
337                   #       0 parameters: login() : All the default values will be used.
338                   #       1 parameter:  login(1) : The $test_success parameter is set.
339                   #       2 parameters: login("Login:", "Password:") : the $login_prompt and $password_prompt parameters are set.
340                   #       3 parameters: login("Login:", "Password;", 1) : the three parameters received values on this order.
341                   #
342                   # returns:
343                   #       string: whatever the SSH server wrote in my input stream after loging in. This usually is some
344                   #               welcome message and/or the remote prompt. You could use this string to do your verification
345                   #               that the login was successful. The content returned is removed from the input stream.
346                   # dies:
347                   #       IllegalState: if any of 'host' or 'user' or 'password' fields are unset.
348                   #       SSHProccessError: if run_ssh() failed to spawn the ssh process
349                   #       SSHConnectionError: if the connection failed for some reason, like invalid 'host' address or network problems.
350
351       string exec($cmd [,$timeout]) - executes a command in the remote
352       machine returning its output
353           exec('command') runs 'command' in the remote machine and returns
354           all the output generated by 'command' into a string.
355
356       boolean waitfor($pattern [,$timeout])
357                   # boolean waitfor ($string [, $timeout, $match_type])
358                   # This method reads until a pattern or string is found in the input stream.
359                   # All the characters before and including the match are removed from the input stream.
360                   #
361                   # After waitfor returns, use the methods before(), match() and after() to get the data
362                   # 'before the match', 'what matched', and 'after the match' respectively.
363                   #
364                   # If waitfor returns false, whatever content is on input stream can be accessed with
365                   # before(). In this case before() will return the same content as peek().
366                   #
367                   # params:
368                   #       $string: a string to be matched. It can be a regular expression or a literal string
369                   #                        anb its interpretation as one or other depends on $match_type. Default is
370                   #                        're', what treats $string as a regular expression.
371                   #
372                   #       $timeout: the timeout in seconds while waiting for $string
373                   #
374                   #       $match_type: match_type affects how $string will be matched:
375                   #               '-re': means $string is a regular expression.
376                   #               '-ex': means $string is an "exact match", i.e., will be matched literally.
377                   #
378                   # returns:
379                   #       boolean: 1 is returned if string was found, 0 otherwise. When the match fails
380                   #                        waitfor() will only return after waiting $timeout seconds.
381                   #
382                   # dies:
383                   #       SSH_CONNECTION_ABORTED if EOF is found (error type 2)
384                   #       SSH_PROCESS_ERROR if the ssh process has died (error type 3)
385                   #       SSH_CONNECTION_ERROR if unknown error (type 4) is found
386
387       string before() - returns the "before match" data of the last waitfor()
388       call.
389           When waitfor() matches, if there is any content before the match,
390           this will be returned by before().
391
392           If the last waitfor() didn't match, before() will return all the
393           current content on the input stream, just as if you had called
394           peek() with the same timeout.
395
396       string match() - returns the "match" data of the last waitfor() call,
397       or undef if didn't match.
398       string after() - returns the "after match" data of the last waitfor()
399       call, or undef if didn't match.
400       void close() - terminates the ssh connection
401       void send($string) - sends $string to the SSH server, returns nothing
402           Sends the string to the SSH server. If the ssh server process is
403           attached to a pseudo-terminal (this is the default) it is likely
404           that the echo terminal property will be on, what will make the
405           server place the command you just sent in our input stream, i.e.,
406           you'll see the command you sent in your next read operation.
407
408           To avoid this, try to disable the echo property on the server-side,
409           using
410
411            $ssh->exec("stty -echo");
412
413           It's also advisable to disable the terminal character convertions
414           on server-side, what will make you sure that every character you
415           sent will be received "as-is" to the other side.
416
417           So you'll probably use this to disable character conversions and
418           echo:
419
420            $ssh->exec("stty raw -echo");
421
422           Of course you're server must support the 'stty' command for that
423           work.
424
425           To guarantee that your characters are not converted by your local
426           pseudo-terminal before you send them out, set the constructor
427           option:
428
429                   raw_pty => 1
430
431           And if you don't need a terminal on the server-side at all, set the
432           constructor option bellow to 1:
433
434                   no_terminal => 1
435
436       string peek([$timeout]) - returns what is in the input stream without
437       removing anything
438                   # peek([$timeout]) - returns what is in the input stream without removing anything
439                   #       peek() returns what is available on the input stream until $timeout seconds.
440                   #       If there is data continuosly arriving on the input stream, subsequent calls to peek()
441                   #       will return a growing amount of data.
442                   #
443                   # dies:
444                   #       SSH_CONNECTION_ABORTED if EOF is found (error type 2)
445                   #       SSH_PROCESS_ERROR if the ssh process has died (error type 3)
446                   #       SSH_CONNECTION_ERROR if unknown error (type 4) is found
447
448       string eat($string) - removes all the head of the input stream until
449       $string inclusive.
450                   # string eat($string)- removes all the head of the input stream until $string inclusive.
451                   #       eat() will only be able to remove the $string if it's currently present on the
452                   #       input stream because eat() will wait 0 seconds before removing it.
453                   #
454                   #       Use it associated with peek to eat everything that appears on the input stream:
455                   #
456                   #       while ($chunk = $exp->eat($exp->peak())) {
457                   #               print $chunk;
458                   #       }
459                   #
460                   #       Or use the read_all() method that does the above loop for you returning the accumulated
461                   #       result.
462                   #
463                   # param:
464                   #       string: a string currently available on the input stream.
465                   #               If $string doesn't start in the head, all the content before $string will also
466                   #               be removed.
467                   #
468                   #               If $string is undef or empty string it will be returned immediately as it.
469                   #
470                   # returns:
471                   #       string: the removed content or empty string if there is nothing in the input stream.
472                   #
473                   # dies:
474                   #       SSH_CONNECTION_ABORTED if EOF is found (error type 2)
475                   #       SSH_PROCESS_ERROR if the ssh process has died (error type 3)
476                   #       SSH_CONNECTION_ERROR if unknown error (type 4) is found
477                   #
478                   # debbuging features:
479                   #       The following warnings are printed to STDERR if $exp->debug() == 1:
480                   #               eat() prints a warning is $string wasn't found in the head of the input stream.
481                   #               eat() prints a warning is $string was empty or undefined.
482                   #
483
484       string read_all([$timeout]) - reads and removes all the output from the
485       input stream.
486           The reading/removing process will be interrupted after $timeout
487           seconds of inactivity on the input stream.
488
489       string read_line([$timeout]) - reads the next line from the input
490       stream and returns it.
491                   # string read_line([$timeout]) - reads the next line from the input stream
492                   # Read a line of text. A line is considered to be terminated by the 'teminator'
493                   # character. Default is "\n". Lines can also be ended with "\r" or "\r\n".
494                   # Remember to adequate this for your system with the terminator() method.
495                   # When there are no more lines available, read_line() returns undef. Note that this doen't mean
496                   # there is no data left on input stream since there can be a string not terminated with the
497                   # 'terminator' character, notably the remote prompt could be left there when read_line() returns
498                   # undef.
499                   #
500                   # params:
501                   #       $timeout: the timeout waiting for a line. Defaults to timeout().
502                   #
503                   # returns:
504                   #       string: a line on the input stream, without the trailing 'terminator' character.
505                   #                       An empty string indicates that the line read only contained the 'terminator'
506                   #                       character (an empty line).
507                   #       undef: when there are no more lines on the input stream.
508                   #
509
510       void restart_timeout_upon_receive( 0 | 1 ) - changes the timeout
511       counter behaviour
512                   # void restart_timeout_upon_receive( 0 | 1 ) - changes the timeout counter behaviour
513                   # params:
514                   #       boolean: if true, sets the timeout to "inactivity timeout", if false
515                   #                       sets it to "absolute timeout".
516                   # dies:
517                   #       IllegalParamenter if argument is not given.
518
519       Expect get_expect() - returns the internal Expect object
520           params:
521               none
522
523           returns:
524               an "Expect" object connected to the SSH server. It will die if
525               you try to run it without being connected.
526
527           dies:
528               IllegalState: if this there is no valid ssh connection
529               established
530

SEE ALSO

532       Net::SCP::Expect, Net::SCP, Net::SSH::Perl, Expect
533

REPORTING BUGS

535       To report bugs please use the bug reporting tool available on CPAN
536       website, in the module's page. That way I can keep track of what I need
537       to do and I can also communicate with you through that tool.
538

AUTHOR

540       Bruno Negrao Guimaraes Zica. <bnegrao@cpan.org>.
541

THANKS

543       Daniel Berger, author of Net::SCP::Expect. Special thanks to the people
544       helping me improve this module by reporting their tests and the bugs
545       they find.
546
548       Copyright (C) 2007 by Bruno Negrao Guimaraes Zica
549
550       This library is free software; you can redistribute it and/or modify it
551       under the same terms as Perl itself, either Perl version 5.8.3 or, at
552       your option, any later version of Perl 5 you may have available.
553
554
555
556perl v5.12.3                      2008-04-23               Net::SSH::Expect(3)
Impressum