Running comands on remote machines using shell script

Scenario is… I wan’t to run a script on Machine A using Cron. The only problem is that the script that runs on Machine A has to carry out jobs on Machine B.

The first issue is getting past having to put in a password on Machine A so that is can access Machine B during the script. I solved this issue by using ssh-keygen, I ran a single command on Machine A that produced a set of keys. I then copied these keys over to Machine B and put them in the /home/username/.ssh folder. This allows Machine A to connect to Machine B without manually typing a password. See Man Page for ssh-keygen for more information on how to do this.

The second issue was finding out how to run a command remotely with arguments. For example say that I want to find out the Date on Machine B and have that date returned to Machine A as a variable, and here is the tricky bit… I want the date formatted in a particular way too. The easiest way that I could see to do this is to run the ssh command while passing in the Linux command and formatting arguments in one string (on one line of the shell script) like this newDate=`ssh username@machineb “date +’%y%m%d'”`

The above line consists of a variable name newDate and equals sign, this assigns the command to that variable name. Notice the back tic at the start and the end of the command, this is so the command will be excecuted. Also notice that I have put the arguments for the command in double quotes and the formatting argument in single quotes. It will not work unless you do this. Just to clear up confusion is ends in …%d then single quote then double quote then back tic.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s