Checking the output of “diff” command using shell

2019-08-20 09:47发布

问题:

I am comparing a file on my linux machine with another file on a remote machine (both AWS Instances) using the following command:

diff -s main <(ssh -i /home/ubuntu/sai_key.pem ubuntu@w.x.y.z 'cat /home/ubuntu/c1')

I want to write a shell script to do nothing when both files are same and update the file in the remote machine when the file in the linux machine (host) changes.

I want the shell script to check the remote file every 30 seconds.

I am running the shell script on my host machine only and not the remote one.

Could you please help me with that?

回答1:

First of all, I would recommend using cmp rather than diff (I believe it is more efficient), but this solution should work either way.

All you need to do is write a bash script with an if statement in it. If the cmp or diff command returns nothing, you don't need to take any action. In the other case, you just need to scp your current main file over to the remote host.

If you decide to use cmp, that if statement just needs to look like:

if cmp -s main <(ssh -i /home/ubuntu/sai_key.pem ubuntu@w.x.y.z 'cat /home/ubuntu/c1')
then
    echo "Match!"
else
    echo "No match!"
    scp ...
fi

If you really are dead set on using diff, comment below and I can write something up really quick that does the equivalent.

Checking the remote file (running this bash script) every 30 seconds may be slightly overkill, but it's really up to you. To achieve a periodic check (this only works for time intervals above 1 minute), you could use a cron scheduler. I recommend using Crontab Guru to create cron schedules and understand how they work. For your purpose, you would just need to add one line to your crontab (in your terminal run crontab -e to edit your crontab) as follows:

* * * * * /absolute/path/to/shell/script.sh

Make sure you chmod the script with the right permissions as well!



回答2:

There is no need for bash, diff, cmd, cron, ... Python can do everything with a little help from ssh:

import subprocess
import time

key_pair = 'AWS_Linux_key_pair.pem'
remote_name = 'ec2-user@ec2-3-16-214-98.us-east-2.compute.amazonaws.com'
file_name = 'fibonacci.py'
cat_string = "cat " + file_name

while True:
    command = 'ssh -i ' + key_pair + ' ' + remote_name + " '" + cat_string + "'"
    remote_lines = subprocess.getoutput(command)
    local_lines = subprocess.getoutput(cat_string)

    if remote_lines != local_lines:
        print("update")
        command = 'scp -i ' + key_pair + ' ' + file_name + ' ' + remote_name + ':'
        subprocess.getoutput(command)
    else:
        print("the same")
    time.sleep(30)