Perl (Scripting) - Local and remote variables over SSH

by
Jeremy Canfield |
Updated: March 09 2020
| Perl (Scripting) articles
Let's say you have two servers, server1.example.com and server2.example.com, and you want to create a variable on server1, then SSH into server2, create a variable on server2, and be able to use both variables in the SSH session to server2. In this example, variable $a is created on server 1, and has a value of Hello. In the SSH connection to server2, variable $b is created with a value of World. In the SSH connection, both $a and $b are echoed.
#!/usr/bin/perl
use strict;
use warnings;
use Net::SSH::Perl;
my $host = "your_hostname";
my $user = "your_username";
my $pass = "your_password";
my $a = "Hello";
my $ssh = Net::SSH::Perl->new($host);
$ssh->login($user, $pass);
my ($stdout, $stderr, $exit) = $ssh->cmd("b='World'; echo $a \$b;");
print "$stdout\n";
Running the Perl script will print both $a (Hello) and $b (World), which means that the SSH session was able to use both the host $a variable and the local $b variable.
~]# perl example.pl
Hello World
Did you find this article helpful?
If so, consider buying me a coffee over at