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 server.

Pass The Script Over 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 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

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 and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. 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 *

Comment moderation is enabled. Your comment may take some time to appear.

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