Automating Tasks with SSH

From docwiki
Revision as of 17:18, 23 March 2020 by Mond (talk | contribs)
Jump to: navigation, search


Motivation

Besides interactive login, SSH can also be used to automate thing by directly executing remote commands and also connecting STDIN and STDOUT to transfer date.

To understand the following examples, make sure you know about Redirecting and Piping input and output of commands.


Executing a remote command

Lets assume you have created an alias for your host with the name myweb. Then you can do. E.g:

$ ssh myweb "find ./var/www"

This would list all files below /var/www on the remote server and the output is displayed on your local server. This means you could also redirect the output on your local server. Either to a command or to a file:

$ ssh myweb "find ./var/www" | grep \\.png > images-on-my-webserver.txt

So the above example runs the same find command on the myweb server. The output is transported via the ssh channel and available as STDOUT on our local server. On our local server we filter it through the grep command to only contain lines that end with .png and finally we redirect the output on our local server to the file images-on-my-webserver.txt

Now of course it we could save a bit of bandwidth if we would already filter on the remote side:

$ ssh myweb "find ./var/www | grep \\.png" > images-on-my-webserver.txt

(note the different positions of the " )

We can also redirect the input to commands.

E.g.

$ echo bla | ssh myweb "cat - > test.txt"
$ raspistill -w 320 -h 240 -n -t 1 -o - | ssh myweb "cat - > /var/www/livecam.jpg"

The first example just creates a file text.txt on the remote server with the content bla. The second example could be run on your raspberry PI and uses the raspistill to read an image from the camera and write it to STDOUT (-o - ). Instead of storing the file locally the file is directly transmitted to the remote host where it is cat into a file named livecam.jpg