1

Currently I am executing run scripts using perl system by sshing into a remote machine:

system("ssh -t remote $dir/bashscript> $dir/stdout.stdout 2> $dir/stderr.stderr &");

I want to pass an environment variable to the bashscript on my remote machine (a directory to be specific). What is the best way to do it? And what should I add in my bashscript to accept the argument?

0

2 Answers 2

1

Try this:

system("ssh -t remote FOO='dir/dir/filename.stderr' $dir/bashscript> $dir/stdout.stdout 2> $dir/stderr.stderr &");

Note that if the value comes from an untrusted source this can be dangerous. You should really escape the value before you pass is like that. For example, you could do something like this:

my $foo='some value here';
$foo=~s/'/'\\''/g; # escape the '
system("ssh -t remote env FOO='$FOO' $dir/bashscript> $dir/stdout.stdout 2> $dir/stderr.stderr &");

In either case, bashscript can access the value via $FOO.

Sign up to request clarification or add additional context in comments.

8 Comments

why would it be dangerous?
If the remote server allows it, using ssh -o SendEnv=FOO ... would be preferable.
also what's the best way to refactor my bash script to properly accept $FOO?
@acbh It is possible the value of the variable may contain special characters that will change the behavior of the (remote) shell. Even worse, a specially crafted value can cause the shell to execute arbitrary commands.
@chepner Yes, that is simpler, but I think most ssh servers only accept only a few variables by default.
|
0

With all of @redneb's caveat's about sanitizing input

ssh remotehost FOO=bar \; export FOO \; script > out 2> err

or if you're sure that the shell on the remote host will be bash, the more compact

ssh remotehost export FOO=bar \; script > out 2> err

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.