Run a Local Shell Script on a Remote SSH Server

Introduction

In this tutorial, How to Run a Local Shell Script on a Remote SSH Server. You can pass entire scripts over SSH without having the .sh file on the remote Linux server.

To run a local shell script on a remote SSH server, you can use the ssh command with the following syntax:

ssh user@remote_host 'bash -s' < local_script.sh

Here’s a breakdown of the command:

  • user: Replace this with the username for the remote SSH server.
  • remote_host: Replace this with the IP address or hostname of the remote SSH server.
  • local_script.sh: Replace this with the path to your local shell script that you want to run on the remote server.

Pass The Script Over to Standard Input

ssh user@remotehost 'bash -s' < myscript_onLocal.sh
  • The bash -s command means “execute the following commands in a new bash session.”
  • The -s flag makes it read from the standard input
  • The < myscript_onLocal.sh bit will read a local script file into standard input.

The output terminal is as follows:

[vagrant@localhost ~]$ cat myscript_onLocal.sh
#!/bin/bash
echo "Target server"
cd /home
pwd
w
[vagrant@localhost ~]$
[vagrant@localhost ~]$ ssh vagrant@192.168.3.5 'bash -s' < myscript_onLocal.sh
vagrant@192.168.3.5's password:
Target server
/home
 14:00:46 up 21 min,  1 user,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
vagrant  pts/0    10.0.2.2         13:40   17:54   0.00s  0.00s -bash
[vagrant@localhost ~]$

Running Remote Commands Inside a Script

ssh vagrant@192.168.3.5 'bash -s' <<'ENDSSH'
  # The following commands run on the remote host
  lsb_release -a
  ls -l
  pwd
ENDSSH

The <<‘ENDSSH’ directive makes a “here-document” structure

The output as the picture below

Run a Local Shell Script on a Remote SSH Server

Conclusion

You have to Run a Local Shell Script on a Remote SSH Server. I hope will this your helpful. Thank you for reading the DevopsRoles page!

About HuuPV

My name is Huu. I love technology, especially Devops Skill such as Docker, vagrant, git, and so forth. I like open-sources, so I created DevopsRoles.com to share the knowledge I have acquired. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.