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
-
1why 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?– djeikybFeb 14, 2011 at 12:49
-
@djeikyb A script can copy itself.– Ken SharpApr 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.– djeikybApr 16, 2015 at 8:20
2 Answers
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!
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.
-
You can even use the stdout of the remote command, like:
ssh user@host command > localfile.txt
orssh user@host command | something | something2 ...
– LGBFeb 14, 2011 at 12:42