两台主机间文件同步

说明:需要同步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"

你可能感兴趣的:(运维,linux,运维)