脚本-01 Linux服务器文件迁移

需求

将服务器中的修改时间晚于某个时间的文件迁移到另一个服务器中,并与文件清单比较

脚本

#!/bin/bash

# 安装expect软件包
yum -y install expect
# 安装失败则退出
if [ $? == 1 ]
then
        exit 1
fi

# 找出 $1 文件下修改时间晚于 $2 的文件,可能包含文件夹及普通文件
files=$(find "$1" -newermt "$2")
if [ $? == 1 ]
then
        exit 1
fi


files_str=""
system_date=$(date "+%Y-%m-%d_%H:%M:%S")
bname=$(basename $0)
file_name=$(find $1 -name $bname)
cp_files=()
for file in $files
do
        # 既不是文件夹也不是参数传入的文件夹
        if [ ! -d $file ] && [ ! $file == $file_name ]
        then
                files_str+="${file} "
                file_date=$(ls -l $file | awk '{print $6,$7,$8}')
                echo "$file_date $file -> $3:$6" &>> cp_files_$system_date.log
                cp_files+=($file)
        fi
done

# 解决scp时需要手动输入密码的问题
expect <<-EOF                           
spawn scp -p ${files_str} $4@$3:$6
expect {
"New password:" {send "$5\r";exp_continue}
"*password" {send "$5\r"}
}
expect eof
EOF

echo "success"

echo "============================"

if [ ! -e $7 ]
then
        echo "the $7 is not exist"
        exit 1
fi

target_files=$(cat target_files.txt)
cp_target_jiaoji=(`echo ${cp_files[*]} ${target_files[*]}|sed 's/ /\n/g'|sort|uniq -c|awk '$1!=1{print $2}'`)

files_list_1=(`echo ${cp_files[*]} ${cp_target_jiaoji[*]}|sed 's/ /\n/g'|sort|uniq -c|awk '$1==1{print $2}'`)
echo "the files are copied that not in target files:"
echo ${files_list_1[*]}

echo ""
files_list_2=(`echo ${target_files[*]} ${cp_target_jiaoji[*]}|sed 's/ /\n/g'|sort|uniq -c|awk '$1==1{print $2}'`)
echo "the files are not copied that in target files"
echo ${files_list_2[*]}



运行说明、

./cp_file_version_2.sh /root/Desktop/ "2024-04-29 15:13:00" 192.168.109.129 root 123456 /root/Desktop/cp_files target_files.txt

# 共七个参数
# /root/Desktop/   要复制的文件所在路径,用绝对路径
# "2024-04-29 15:13:00"  时间
# 192.168.109.129  目标服务器地址
# root  目标服务器的用户名
# 123456  目标服务器用户密码
# /root/Desktop/cp_files  目标服务器的目的路径,用绝对路径
# target_files.txt   存放要复制的文件清单   只一列,用绝对路径表示文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值