当前位置:首页 > 编程笔记 > 正文
已解决

两台主机间文件同步

来自网友在路上 178878提问 提问时间:2023-09-20 14:45:15阅读次数: 78

最佳答案 问答题库788位专家为你答疑解惑

说明:需要同步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 filesource_md5=$(md5sum "$source_folder/$file" | cut -d ' ' -f 1)# Sync the file to the destination serverrsync -avzv "$source_folder/$file" "$destination_host:$destination_folder/" || {echo "Rsync failed."exit 1}# Get MD5 hash of the destination server filedestination_md5=$(ssh "$destination_host" "md5sum '$destination_folder/$file'" | cut -d ' ' -f 1)# Compare MD5 hashes of the source and destination server filesif [ "$source_md5" == "$destination_md5" ]; thenecho "File MD5 hashes match, synchronization successful."elseecho "File MD5 hashes do not match, synchronization failed."exit 1fi# Get content of the file from the destination servercontent_b=$(ssh "$destination_host" "cat '$destination_folder/$file'" 2>&1)exit_status_b=$?if [ $exit_status_b -ne 0 ]; thenecho "Unable to retrieve content of the file on the destination server."exit 1fi# Save content of the file from the destination server to a temporary filetemp_file=$(mktemp)echo "$content_b" > "$temp_file"# Use the diff command to compare file contentsdiff_output=$(diff "$source_folder/$file" "$temp_file")if [ -z "$diff_output" ]; thenecho "File contents are identical on both hosts."elseecho "File contents differ between the two hosts:"echo "$diff_output"fi# Remove the temporary filerm "$temp_file"
}# Example usage:
# sync_modify_compare "/path/to/source" "file.txt" "user@destination_host" "/path/to/destination"
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"两台主机间文件同步":http://eshow365.cn/6-10020-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!