3

I am trying to execute a local script on remote server via ssh using keytab authentication. I am able to connect to remote via ssh as sachin(user who gets the ticket) and then I am spawning a bash process as another user, remoteuser. So far so good. Here's the command

ssh -q -o BatchMode=yes -o StrictHostKeyChecking=no -l sachin sachin@remote_host 'sudo -u remoteuser /bin/bash' < ./hello.sh

Problem starts when I am trying to pass an argument to hello.sh. I tried the following

ssh -q -o BatchMode=yes -o StrictHostKeyChecking=no -l sachin sachin@remote_host 'sudo -u remoteuser /bin/bash' < ./hello.sh "hello"

I get

/bin/bash: hello: Permission denied.

But without parameters script is executed as remoteuser. So, I don't think any special permission is required.

hello.sh is a simple shell script.

#!/bin/bash
echo $1

Any Idea what's wrong?

2

It looks as if you are expecting "hello" to be passed as an argument to the script, but you don't give it as a command line argument to the shell.

Instead, to pass a script on standard input to bash, use bash -s. This also allows you to pass additional command line argument with e.g. bash -s "hello":

ssh ...options... 'sudo -u remoteuser /bin/bash -s "hello"' <./hello.sh

Note though, that this makes the shell's standard input stream be the shell script, so reading data from standard input becomes difficult inside the script itself.

Another option is obviously to transfer the script over to the remote system and run it there.


Your command

ssh ...options... 'sudo -u remoteuser /bin/bash' <./hello.sh "hello"

is identical to

ssh ...options... 'sudo -u remoteuser /bin/bash' "hello" <./hello.sh

The positioning of the redirection on the line does not matter here. See e.g. How is this command legal ? "> file1 < file2 cat"

  • Thank you so much that works just fine. I don't think it's feasible but out of curiosity I was wondering if it's possible to pass local variables? I mean, set a variable locally like TEST_VAR and then pass it as $TEST_VAR instead of hard coded string. – Sachin Feb 20 at 14:16
  • @Sachin One way would be to use double quotes around sudo ..., as in "sudo -u remoteuser /bin/bash -s '$test_var'". $test_var would be expanded by the local shell in the command string. – Kusalananda Feb 20 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.