[Thamesvalley-pm] using ssh within perl scripts

ed ed-pm at s5h.net
Tue Oct 30 11:20:28 PDT 2007


On Tue, 30 Oct 2007 17:45:10 +0000
Greg Matthews <gmatt at nerc.ac.uk> wrote:

> Seems like I'm the only one to ask for advice here...
> 
> I'm using ssh to connect to a series of machines like so:
> 
> open( SSH, "$ssh_bin $ssh_opts $host $command |") or die...
> while (<SSH>) {
> 	....
> }
> close SSH;
> 
> I'm opening a new ssh shell for each command.
> 
> I want to capture the output of various commands to a set of lists or 
> files. For instance, the output of "uname -a" needs to be recorded in
> a file uname.out.
> 
> Is it possible to send a series of commands through the same SSH 
> session? and capture the output for each separately?
> 
> That would save repetitive long timeouts when hosts are down.
> 
> So far I have figured out that I can open ssh like this:
> 
> open(SSH,"| /usr/bin/ssh $options $host");
> print SSH "$command1\n";
> print SSH "$command2\n";
> close SSH;
> 
> but I haven't figured out how to capture the results of each command 
> separately.

It's not possible to do that, unfortunately.
 
> hope this makes sense and someone can point me the right direction

There is a nice library called IPC that includes Open2 and Open3. Open2
does what you would expect from open( "| dd |" ). Open3 includes a file
handle for stderr.

If you would like to communicate with ssh, and access stdin, stdout and
stderr, then open3 is the function for you.

  perldoc IPC::Open3

Will provide you with some useful information, using it isn't as
complicated as the examples look though, simply use:

  my $pid = open3( my $stdin, my $stdout, my $stderr, 
    "/usr/bin/ssh somehost" );

  while( <$stdout> ) {
    chomp;
    print( "Data from stdout: $_\n" );
  }

  kill( 9, $pid );

-- 
The 5 1/4 Floppy Drive to Alderan is reporting a faulty control module
because of Nutty drinking a bottle of peach schnapps. Covad is ignoring
the fact that they have one network admin left. ::
http://www.s5h.net/ :: http://www.s5h.net/gpg
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.pm.org/pipermail/thamesvalley-pm/attachments/20071030/9c0a5dc5/attachment.bin 


More information about the Thamesvalley-pm mailing list