How To Run A Bash Script on A Remote Machine Using SSH
2 min read

Remote script

It’s possible to execute remote scripts without copying the script file with these commands.

Simple way

Execute a command without sudo rights.

ssh root@MachineB 'bash -s' < local_script.sh

Sudo way

If you want sudo rights, this is the right command.

ssh root@MachineB 'echo "rootpass" | sudo -Sv && bash -s' < local_script.sh

Interactive way

You can also do in a more interactive way. This can be used when user input is required. It is also possible to pass on arguments.

ssh user@host ARG1=$ARG1 ARG2=$ARG2 'bash -s' <<'ENDSSH'
  # commands to run on remote host
  echo $ARG1 $ARG2
ENDSSH