Pergunta

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

Foi útil?

Solução

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"'/;

Outras dicas

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

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');
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top