Persistent SSH Connection – How to Stream Commands Over Time

linuxssh

Say that I have an application running on one PC that is sending commands via SSH to another PC on the network (both machines running Linux).

For example every time something happens on #1, I want to run a task on #2. In this setup, I have to create SSH connection on every single command.

Is there any simple way to do this with basic unix tools without programming custom client/server application? Basically all I want is to establish a connection over SSH and then send one command after another.

Best Answer

Not sure if it can be used in production but you can do something like this:

create file on #1

1> touch /tmp/commands

Then run command:

1> tail -f /tmp/commands | ssh username@x.x.x.x

That will open file /tmp/commands and start sending its content to server x.x.x.x (#2) and run it there line by line

now, every time something happens on #1 do:

1> echo "ls -l" >> /tmp/commands

or

1> echo "reboot" >> /tmp/commands

whatever you add to file /tmp/commands will be sent to #2 and executed. Just make sure you do not run anything interactive, or deal with it somehow.