How to sudo run a local script over ssh How to sudo run a local script over ssh shell shell

How to sudo run a local script over ssh


Reading the error message of

$ ssh -t $HOST "sudo -s && bash" < script.shPseudo-terminal will not be allocated because stdin is not a terminal.

makes it pretty clear what's going wrong here.

You can't use the ssh parameter -t (which sudo needs to ask for a password) whilst redirecting your script to bash's stdin of your remote session.

If it is acceptable for you, you could transfer the local script via scp to your remote machine and then execute the script without the need of I/O redirection:

scp script.sh $HOST:/tmp/ && ssh -t $HOST "sudo -s bash /tmp/script.sh"

Another way to fix your issue is to use sudo in non-interactive mode -n but for this you need to set NOPASSWD within the remote machine's sudoers file for the executing user. Then you can use

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


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.


First of all divide your objective in 2 parts. 1) ssh to the host. 2) run the command you want as sudo. After you are certain that you can 1) access the host and 2) have sudo privileges then you can combine the two commands with &&. What x_cmd && y_cmd does is that the y_cmd gets executed after x_cmd has exited successfully.