使用shell脚本检查“diff”命令的输出

问题描述 投票:0回答:2

我使用以下命令将我的linux机器上的文件与远程机器上的另一个文件(两个AWS实例)进行比较:

diff -s main <(ssh -i /home/ubuntu/sai_key.pem [email protected] 'cat /home/ubuntu/c1')

我想编写一个shell脚本,当两个文件相同时什么也不做,并在linux机器(主机)中的文件发生变化时更新远程机器中的文件。

我希望shell脚本每隔30秒检查一次远程文件。

我只在主机上运行shell脚本而不是远程脚本。

你能帮帮我吗?

python linux amazon-web-services shell ubuntu
2个回答
1
投票

首先,我建议使用cmp而不是diff(我相信它更有效),但这个解决方案应该以任何方式工作。

您需要做的就是编写一个带有if语句的bash脚本。如果cmpdiff命令没有返回任何内容,则不需要采取任何操作。在另一种情况下,您只需要将当前的scp文件main发送到远程主机。

如果你决定使用cmp,if语句只需要看起来像:

if cmp -s main <(ssh -i /home/ubuntu/sai_key.pem [email protected] 'cat /home/ubuntu/c1')
then
    echo "Match!"
else
    echo "No match!"
    scp ...
fi

如果你真的死定了使用diff,请在下面评论,我可以写一些非常快的东西,相同的。

每隔30秒检查一次远程文件(运行这个bash脚本)可能有些过度,但这完全取决于你。要实现定期检查(这仅适用于1分钟以上的时间间隔),您可以使用cron调度程序。我建议使用Crontab Guru来创建cron计划并了解它们的工作原理。为了您的目的,您只需要在crontab中添加一行(在终端中运行crontab -e以编辑crontab),如下所示:

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

确保你使用正确的权限chmod脚本!


1
投票

不需要bash,diff,command,cron,...... Python可以通过ssh的一些帮助来完成所有事情:

import subprocess
import time

key_pair = 'AWS_Linux_key_pair.pem'
remote_name = '[email protected]'
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)
© www.soinside.com 2019 - 2024. All rights reserved.