两台主机间文件同步

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值