2

I want to run a sript that is present in local machine, but it should perform operations on remote machine. I have already generated public-private keys, so no password authentiaction is required

4
  • 1
    why don't you just copy your script to remote machine?
    – Praweł
    Feb 14, 2011 at 11:50
  • Lots of reasons. Say you need to scrape data from fifty machines. If you ever change the script, which you rather worry about pushing changes to fifty machines, or just edit your one central script?
    – djeikyb
    Feb 14, 2011 at 12:49
  • @djeikyb A script can copy itself.
    – Ken Sharp
    Apr 16, 2015 at 3:16
  • @KenSharp what if you don't have write access on the remote? you just need to gather, say, system stats like mem and cpu usage? and if you copy, you'll likely want to remove. gets to be more work and more things to go wrong than just having the script locally.
    – djeikyb
    Apr 16, 2015 at 8:20

2 Answers 2

9

ssh is a good Unix citizen; we can pipe it around, we can redirect it's output and input in whatever ways imaginable.

ssh user@host sh < your_script.sh

This command is a redirection: your shell will open the (local!) file your_script.sh and feed it as input to the ssh command. ssh, in turn, will tunnel its stdin to the remote command, namely, sh instance. sh without arguments reads its script from stdin. Strictly speaking, the sh part is not even necessary — ssh runs shell by default — but it makes explanation easier.

So we got a sh instance, which is launched on remote host, but reads commands from your local file. Voila!

2
  • sh doesn't read my ~/.bash_profile. bash does.
    – Nakilon
    Mar 16, 2016 at 11:51
  • So just replace 'sh' with 'bash', right?
    – ulidtko
    Mar 16, 2016 at 12:04
0

This SO answers your exact question:bash - How do you use ssh in a shell script? - Stack Overflow

ssh user@host command
#for example
ssh user@host ls

If you have a big script which you want to execute. Then you can copy the script to the remote machine using sftp and then execute it via the above command.

1
  • You can even use the stdout of the remote command, like: ssh user@host command > localfile.txt or ssh user@host command | something | something2 ...
    – LGB
    Feb 14, 2011 at 12:42

You must log in to answer this question.