0

我有一个存储在文本文件中的文件列表(文件/文件夹的绝对路径)。我只需要从一台机器复制权限、用户:组属性(所有这些文件),并在另一台机器上的同一组文件上应用相同的设置。

我能想到的一种方法是通过检查一台机器上的属性并逐个文件在另一台机器上执行 chmod/chown 来逐个手动完成,但这似乎是一项乏味的任务。

知道如何自动化吗?

编辑:只是想明确一点,我不需要源机器中这些文件的数据,因为源机器中的数据不同。目标机器包含更新的数据,我现在只需要源机器的文件/文件夹权限和用户:组。

4

1 回答 1

2

这个怎么样?

#!/bin/bash

user="user"
host="remote_host"

while read file
do
    permission=$(stat -c %a $file) # retrieve permission
    owner=$(stat -c %U $file) # retrieve owner
    group=$(stat -c %G $file) # retrieve group

    # just for debugging
    echo "$file@local: p = $permission, o = $owner, g = $group"

    # copy the permission
    ssh $user@$host "chmod $permission $file" < /dev/null 

    # copy both owner and group
    ssh $user@$host "chown $owner:$group $file" < /dev/null

done < list.txt

我假设文件列表保存在“list.txt”中。

此外,您应该根据您的设置设置变量“用户”和“主机”。

我建议将 ssh 配置为“自动登录”。否则,您应该在每个循环中插入两次密码。这里有一个很好的教程来做这个没有密码的 SSH 登录

另一种仅建立一个 ssh 连接并为目录使用递归选项的解决方案(如评论中所述)如下:

#!/bin/bash

user="user"
host="remote_host"

cat list.txt | xargs stat -c "%n %a %U:%G" | ssh $user@$host '
while read file chmod_par chown_par 
do
    # $file contains %n
    # $chmod_par contains %a
    # $chown_par contains %U:%G

    if [ -d $file ]; then
            chmod -R $chmod_par $file
            chown -R $chown_par $file
    else
            chmod $chmod_par $file
            chown $chown_par $file  
    fi
done'
于 2013-08-24T08:19:20.343 回答