It's hard communicating with an interactive application. It might even be impossible without using a pseudo tty if it buffers its output when STDOUT isn't a terminal (like Perl does).

Since sftp can work non-interactively, you'd be better off using calling sftp multiple times, once for each action you wish to perform. open $fr_sftp, '-|', 'sftp', ... would work nicely for that.

But since you're interested in open2 for educational purposes, I'd start with the following.

{ package SFTP; use IO::Handle qw( ); sub new { my $class = shift(@_); my ($to_sftp, $fr_sftp); # open2 dies on error. my $pid = open2($to_sftp, $fr_sftp, 'sftp', @_); $to_sftp->autoflush(1); return bless({ pid => $pid, to_sftp => $to_sftp, fr_sftp => $fr_sftp, }, $class); } sub DESTROY { my ($self) = @_; ...send exit command to child... ...kill child if necessary... waitpid($self->{pid}, 0); } sub do { my ($self) = @_; my $fr_sftp = $self->{fr_sftp}; my $to_sftp = $self->{to_sftp}; print $to_sftp "command"; my $response; for (;;) { my $line = <$fr_sftp>; last if $line =~ $prompt; $response .= $line; } return $response; } } my $sftp = SFTP->new(...sftp args...); my $response = $sftp->do("...\n");

open3 handles STDERR, but that makes the parent code more complicated since it needs to use select to avoid the deadlock that occurs when the child blocks writing to its STDERR and the parent blocks reading from the child's STDOUT and vice-versa.


In reply to Re^3: Short example using IPC::Open2 or IPC::Open3 by ikegami
in thread Short example using IPC::Open2 or IPC::Open3 by Limbic~Region

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.