Alex
Alex

Reputation: 175

Username as variable in SSH with Perl

in my Perl Script I would like to connect to a machine via

my $result = `ssh $user@machine`;

where $user is the username on the current machine. However this does obviously not work, as Perl recognizes the whole string as one variable. So, is there any other way to use a variable in the username when connecting over SSH?

I have seen that there is a SSH Perl module, however I would like to avoid using additional modules if there is another solution.

Thank you in advance!

Upvotes: 2

Views: 199

Answers (5)

Joshua Millett
Joshua Millett

Reputation: 1

This should work Alex:

`ssh "${user}"@"${machine}"`;

Upvotes: 0

ikegami
ikegami

Reputation: 385955

Perl recognizes the whole string as one variable.

No, that's not the problem. The problem is that in addition to parsing $user as a variable, and it parses @machine as a variable too.

It's simply a question of escape special characters.

my $result = `ssh $user\@machine`;

If the problem really was that you needed to communicate the end of a variable, you can use curlies.

my $count = 4;
my $item = 'book';
print("$count $items\n");     # XXX
print("$count ${item}s\n");   # 4 books

Upvotes: 3

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

Escape sigil Luke:

my $result = `ssh $user\@machine`;

There is not array @machine, isn't?

Backticks are Quote-like Operators. (I recommend using generic qx{} version over customary backticks.) It interpolates (unless you use qx'') content so it interpolates @machine as a content of machine array. It separates members by a content of $" variable which is space by default. If you don't have @machine variable defined and there is not use strict; it is interpolated as an empty string and without warning if there is not use warnings; or -W parameter provided.

Upvotes: 3

Kuthbudin
Kuthbudin

Reputation: 11

Try: my $result = ssh ${user}\@machine;

when you have multiple variables you can use {} to say that they are different like: ${user1}_${user2}

Upvotes: 0

ajays20078
ajays20078

Reputation: 368

You need to escape "@" in the string, as its a array and use double quotes around variable user.

Try:

my $result = `ssh "$user"\@machine`;

Upvotes: -1

Related Questions