2

I have a perl script as below, where I want to access a network path on a remote windows machine from a linux machine using rsh.

$cmd = "rsh -l $username $host \"pushd \\\\network\\path\\to\\the\\directory && dir\"";
print $cmd, "\n";
print qx($cmd);

When I run the script the third line prints output The system cannot find the path specified. However, if I run the command printed by the second line directly from the terminal it works fine.

I'm not able to understand why the script is not working. If the command works from the terminal, it should work using qx() too.

him
  • 487
  • 3
  • 12
  • It is unclear what exactly run from the command line. If this is the exact line you have inside `$cmd = "rsh ...."` then you might need to add another level of escaping, since the double quotes interpret `\\path` as `\path`. – Steffen Ullrich Jun 18 '19 at 05:59
  • When I run the command printed by the second line (ie string value of `$cmd`), from the terminal it runs fine. But, the third line (ie `qx($cmd)`) gives error as mentioned in the question. I have already used four backslashes ` \\\\ ` , in the beginning of the path and has escpaed every other backslash as ` \\ `. – him Jun 18 '19 at 06:04
  • 1
    Personally, I'd build the command using a combo of String::ShellQuote and Win32::ShellQuote – ikegami Jun 19 '19 at 01:56

1 Answers1

3

While you escape your meta-characters against interpolation by double-quotes and by the remote shell, qx might itself interpolate the string again, in which case you might need to add another level of escaping. From the documentation of qx:

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. ...
How that string gets evaluated is entirely subject to the command interpreter on your system. On most platforms, you will have to protect shell metacharacters if you want them treated literally. This is in practice difficult to do, as it's unclear how to escape which characters. See perlsec for a clean and safe example of a manual fork() and exec() to emulate backticks safely.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172