Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quoting in bash and perl in recursive ssh command

Tags:

bash

ssh

perl

I am writing a perl script to login in to a server with ssh and do some shell commands on the server. The problem is that the server is only accessible by first logging into another server. (I am using password-less login with ssh keys).

The following bash script is working correctly, and illustrates the problem:

#! /bin/bash
server1="login.uib.no"
server2="cipr-cluster01"
ssh "$server1" "ssh $server2 \"echo \\\"\\\$HOSTNAME\\\"\""

It prints the correct host name to my screen: cipr-cluster01. However, when trying to do same thing in Perl:

my $server1="login.uib.no";
my $server2="cipr-cluster01";

print qx/ssh "$server1" "ssh $server2 \"echo \\\"\\\$HOSTNAME\\\"\""/;

I get the following output: login.uib.no. So I guess, there is some problems with the quoting for the perl script..

like image 281
Håkon Hægland Avatar asked May 11 '14 20:05

Håkon Hægland


2 Answers

qx works like double quotes. You have to backslash some more:

print qx/ssh "$server1" "ssh $server2 \"echo \\\\"\\\$HOSTNAME\\\\"\""/;

Using single quotes might simplify the command a lot:

print qx/ssh "$server1" 'ssh $server2 "echo \\\$HOSTNAME"'/;
like image 146
choroba Avatar answered Sep 23 '22 03:09

choroba


You can simplify the quoting a bit by using the ProxyCommand option that tells ssh to connect to $server2 via $server1, rather than explicitly running ssh on $server1.

print qx/ssh -o ProxyCommand="ssh -W %h:%p $server1" "$server2" 'echo \$HOSTNAME'/;

(There is some residual output from the proxy command (Killed by signal 1) that I'm not sure how to get rid of.)

like image 43
chepner Avatar answered Sep 24 '22 03:09

chepner