Search code examples
bashsshcommand-line-interface

Unable to run a local script on a remote server


As per the title, I am trying to run a script with an argument on my remote server, when the script is on my local server. In troubleshooting, I have tried to take it down to barebones and simply run it from the CLI:

ssh -t $user@$domain "sudo -S ./bash.sh $var"

bash.sh:

#!/bin/bash
echo $1

However I eventually realized this was running my script on the remote server with the same name... The end goal is to call a local bash script, which when prompted runs a command similar to the above (containing variables) on the remote server to verify the health. I've been banging my head and searching other StackOverflow posts, but have yet to be successful.

Main points: the local script must be called within another script, with an arg, with sudo on the remote, and without changing files or system variables on the remote system

Is there no way to do this without adjusting the remote system?

Another try, which shows the sudo password visibly when prompted, and never completes:

ssh -tt $user@$domain "sudo -S" < bash.sh $var

Solution

  • I have the following in my /etc/sudoers.d/local which possible sidesteps the prompt issue:

    %sudo   ALL=NOPASSWD: ALL
    

    Then either copy the script to the remote server:

    $ ssh remote "cat > /tmp/bash.sh && sudo /tmp/bash.sh your_arg; rm /tmp/bash.sh" < bash.sh
    

    Or expand the script into suitable command on the client side via stdin or an argument to bash. tail +2 will strip the #! line and modified bash.sh to refer to $arg instead of $1:

    $ { echo arg=anything; tail +2 bash.sh; } | ssh remote sudo bash
    anything
    
    ssh remote "sudo bash -c '$(echo arg=anything; tail +2 bash.sh)'"
    anything
    

    Consider ansible for this type of task.