5

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..

3 Answers 3

4

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"'/;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works! (I also found that print qx/ssh $server1 \"ssh $server2 \\\"echo \\\\\\\$HOSTNAME\\\"\"/; is working.. but your commands are simpler).
3

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.)

Comments

1

You can use Net::OpenSSH that is able to do the quoting automatically:

my $ssh_gw = Net::OpenSSH->new($gateway);
my $proxy_command = $ssh_gw->make_remote_command({tunnel => 1}, $host, 22);
my $ssh = Net::OpenSSH->new($host, proxy_command => $proxy_command);
$ssh->system('echo $HOSTNAME');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.