21

Possible Duplicate:
how to use ssh to run shell script on a remote machine?

I am trying to make a bash script that runs on my remote server's daily cron jobs to automatically login through ssh to another unix box, run a few commands and then leave.

#!/bin/bash
ssh machinehost.com -l admin -p 2222 "/usr/bin/find /share/Public/backups/set0 -mtime +14 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set1 -mtime +4 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set2 -mtime +3 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set3 -mtime +21 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set4 -mtime +2 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set5 -mtime +2 | xargs rm -f;
                               "

The problem I am having is I need to modify my current existing code to do something a little more complicated before each command like

if [ $(ls /share/Public/backups/set1 -1 | wc -l ) -gt 4 ] then run above command
fi

How would I go about running this command on the remote ssh machine and not on my local cron one?

Community
  • 1
  • 1
Nicarlo
  • 213
  • 1
  • 2
  • 4
  • @Wooble The other question was asking for a way to run a shell script on a remote computer, where as that is a solution to the problem for this poster. I think the question is different enough. – mopsled Aug 13 '11 at 02:52

3 Answers3

47

Try writing your bash script locally and calling:

ssh user@example.com 'bash -s' < local_script.sh

(Found in the discussion here)

Community
  • 1
  • 1
mopsled
  • 8,445
  • 1
  • 38
  • 40
3

Write a script, copy it to the remote machine and from ssh run just that script.

Tomas
  • 57,621
  • 49
  • 238
  • 373
1

Another workaround is to use python. There is a module called pexpect that can solve your problem, and even more complicated scenario.

TheOneTeam
  • 25,806
  • 45
  • 116
  • 158