Skip to main content

SSH Connections using PERL and Net::OpenSSH

By June 25, 2017September 12th, 2022No Comments

SSH Connections using PERLIn this module we look at a common system administration task and the need to run commands across many servers. Sure we could do this with Puppet or a similar configuration management tool. Checkout my Puppet videos on Pluralsight. But if our needs are more ill-defined or irregular then making SSH connection with PERL and Net::OpenSSH may be a a great option. Using the Net::OpenSSH module in PERL allows an easy connection to our servers. If we have many servers we can iterate a list of servers with the foreach structure. We use this in the demo. Similarly if we need to run many commands across the SSH Connections using PERL we can iterate through a list of commands.

First, we need to check the module is installed. We are using Ubuntu so we can use the prebuilt package provided:

$ sudo apt-get update; sudo apt-get install -y libnet-openssh-perl

In Red Hat and CentOS this can be obtained from the EPEL repo and the package perl-Net-OpenSSH. Modules can also be installed using cpan if you have it and the rest of the d eloper tools installed.

The code we create in the video is shown below.  We iterate through two demonstration servers alice and bob. On each server, we run the specified command. In out case, just running uname -r.

use strict;
use warnings;
use Net::OpenSSH;
my ($s);
my $username = 'ubuntu';
my $cmd = 'uname -r';
my @servers = ('alice', 'bob');
foreach $s (@servers) {
 my $ssh = Net::OpenSSH->new("$username\@$s",timeout => 30);
 $ssh->error and die "Unable to connect: " + $ssh->error;
 print "Connected to $s\n";
 my $fh = $ssh->pipe_out($cmd) or die "Unable to run command";
 while (<$fh>) {
   print "$s OUT: $_";
 close $fh;
 undef $ssh;


We don’t provide a password as we use  SSH-Keys for authentication.