How to sudo run a local script over ssh

Viewed 4835

I try to sudo run a local script over ssh,

ssh $HOST < script.sh

and I tried

ssh -t $HOST "sudo -s && bash" < script.sh

Actually, I searched a lot in google, find some similar questions, however, I don't find a solution which can sudo run a local script.

3 Answers

To make Edward Itrich's answer more scalable and geared towards frequent use, you can set up a system where you only run a one line script that can be quickly ported to any host, file or command in the following manner:

Create a script in your Scripts directory if you have one by changing the name you want the script to be (I use this format frequently to change 1 word for my script name and create the file, set permissions and open for editing):

newscript="runlocalscriptonremotehost.sh"
touch $newscript && chmod +x $newscript && nano $newscript

In nano fill out the script as follows placing the directory and name information of the script you want to run remotely in the variable lines of runlocalscriptonremotehost.sh(only need to edit lines 1-3):

HOSTtoCONTROL="sudoadmin@192.168.0.254"
PATHtoSCRIPT="/home/username/Scripts/"
SCRIPTname="scripttorunremotely.sh"
scp $PATHtoSCRIPT$SCRIPTname $HOSTtoCONTROL:/tmp/ && ssh -t $HOSTtoCONTROL "sudo -s bash /tmp/$SCRIPTname"

Then just run:

sh ./runlocalscriptonremotehost.sh

Keep runlocalscriptonremotehost.sh open in a tabbed text editor for quick updating, go ahead and create a bash alias for the script and you have yourself an app-ified version of this frequently used operation.

Related