Hi Seq,

The power of Net::OpenSSH is that it can give you a lot of low-level control, which does mean you may need to implement some low-level stuff yourself, or instead use a higher-level module like Expect. The following works for me (both client and server are Debian-based Linux systems).

Server-side script that just prompts the user three times and generates some output. Drop this into /tmp/test.pl on the remote machine.

#!/usr/bin/env perl use warnings; use strict; use IO::Prompt 'prompt'; print STDOUT "I am STDOUT\n"; print STDERR "I am STDERR\n"; for (qw/Bar Quz Baz/) { my $resp = prompt("Foo $_? ", -yn); warn "You said no\n" if lc($resp) eq 'n'; print "<$resp>\n"; } print "Goodbye.\n";

Client-side script that executes the remote script. Note how it automatically answers two of the prompts, while allowing the user to answer the third.

#!/usr/bin/env perl use warnings; use strict; use Net::OpenSSH; use Expect; die "Usage: $0 HOST" unless @ARGV==1; my $ssh = Net::OpenSSH->new($ARGV[0]); die $ssh->error if $ssh->error; my @cmd = ('/tmp/test.pl'); my ($pty, $pid) = $ssh->open2pty(@cmd) or die $ssh->error; my $exp = Expect->init($pty); $exp->log_stdout(1); $exp->expect(5, [ qr/foo .+\?/i, sub { my $exp = shift; # prompt user if ($exp->match=~/quz/i) { $exp->send(scalar <STDIN>); } # automatic responses elsif ($exp->match=~/bar/i) { $exp->send("y\n"); } else { $exp->send("n\n"); } exp_continue; } ] ); $exp->soft_close; waitpid($pid, 0); $ssh->disconnect; print "Done.\n";

Hope this helps,
-- Hauke D


In reply to Re: Interactive commands via ssh by haukex
in thread Interactive commands via ssh by Seq

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.