两台主机间文件同步
  IqJftG8zUrLM 2023年11月02日 96 0


说明:需要同步A主机上的一个文件到B主机上。

#!/bin/bash

# Function to synchronize, modify, and compare files
sync_modify_compare() {
    local source_folder="$1"
    local file="$2"
    local destination_host="$3"
    local destination_folder="$4"

    # Get MD5 hash of the source server file
    source_md5=$(md5sum "$source_folder/$file" | cut -d ' ' -f 1)

    # Sync the file to the destination server
    rsync -avzv "$source_folder/$file" "$destination_host:$destination_folder/" || {
        echo "Rsync failed."
        exit 1
    }

    # Get MD5 hash of the destination server file
    destination_md5=$(ssh "$destination_host" "md5sum '$destination_folder/$file'" | cut -d ' ' -f 1)

    # Compare MD5 hashes of the source and destination server files
    if [ "$source_md5" == "$destination_md5" ]; then
        echo "File MD5 hashes match, synchronization successful."
    else
        echo "File MD5 hashes do not match, synchronization failed."
        exit 1
    fi

    # Get content of the file from the destination server
    content_b=$(ssh "$destination_host" "cat '$destination_folder/$file'" 2>&1)
    exit_status_b=$?

    if [ $exit_status_b -ne 0 ]; then
        echo "Unable to retrieve content of the file on the destination server."
        exit 1
    fi

    # Save content of the file from the destination server to a temporary file
    temp_file=$(mktemp)
    echo "$content_b" > "$temp_file"

    # Use the diff command to compare file contents
    diff_output=$(diff "$source_folder/$file" "$temp_file")

    if [ -z "$diff_output" ]; then
        echo "File contents are identical on both hosts."
    else
        echo "File contents differ between the two hosts:"
        echo "$diff_output"
    fi

    # Remove the temporary file
    rm "$temp_file"
}

# Example usage:
# sync_modify_compare "/path/to/source" "file.txt" "user@destination_host" "/path/to/destination"


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
IqJftG8zUrLM