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> and by
124       Net::Telnet and some of its methods work the same as these two modules.
125
126   IMPORTANT NOTES ABOUT DEALING WITH SSH AND PSEUDO-TERMINALS
127       This module uses Expect to start the local ssh client process, and
128       Expect will interact with this process through a local pseudo-terminal
129       (ptty). Similarly, the ssh client will connect to the SSH server and
130       there will receive an ssh login process attached to a ptty too.
131
132       During my tests I realized that the I/O to and from the ssh server
133       changes drastically from OS to OS if we let the local and remote pttys
134       configured on their defaults. The echo's and the \r\n translations make
135       a mess that we are never sure what will be sent to the other side and
136       what will be received here.
137
138       Many ptty features are system dependent and we can't rely on them
139       working the same on different OS's.
140
141       To avoid these problems I always recommend you to:
142
143       1) enable the 'raw_pty' constructor attribute. This disables most (if
144       not all) of the problematic features on the local ptty.
145
146       2) Similarly set the ptty on the remote server to 'raw -echo' as soon
147       as you login.  This can be done with:
148
149           $ssh->exec("stty raw -echo");
150
151       Obviously your server must support the 'stty' command for that.
152
153       3) If you won't run on the server interactive commands that prompt for
154       input, like 'passwd', you could prevent the ssh server from attributing
155       a ptty for the ssh login process. This is done by enabling the
156       'no_terminal' constructor attribute. What that does is passing the '-T'
157       option to the ssh client process when it is created. From the BSD ssh
158       client manual:
159           -T      Disable pseudo-tty allocation.
160
161       This will create the cleaner connection possible. You won't have a ptty
162       on the server, and, weirdly, you won't receive a remote prompt. Try
163       yourself 'ssh -T my.ssh.server' to see how it works. Notice that some
164       system commands that rely on a terminal won't work, say, 'who am i',
165       'stty', etc.
166
167       Also, interactive commands like 'passwd' or 'mail' won't be able to
168       print their prompts.
169
170       But other system commands will run better: 'ls -l' will be printed
171       without terminal control characters.  'ps -ef' will have the command
172       lines printed fully, since there is no 'columns' terminal limitation.
173
174       Moral of the story: pseudo terminals do many character translations
175       that can bring some unexpected results in some situations. Avoid them
176       if you can.
177

EXPORT

179       None by default.
180

CONSTRUCTOR ATTRIBUTES

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

METHODS

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

SEE ALSO

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

REPORTING BUGS

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

AUTHOR

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

THANKS

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