【问题标题】:How do I recursively set read-only permission using Perl?如何使用 Perl 递归设置只读权限?
【发布时间】:2011-04-13 21:21:52
【问题描述】:

我希望$dir 及其下方的所有内容都是只读的。如何使用 Perl 进行设置?

【问题讨论】:

    标签: perl permissions file-permissions readonly


    【解决方案1】:

    您可以结合使用 File::Find 和 chmod(请参阅 perldoc -f chmod):

    use File::Find;
    
    sub wanted
    {
        my $perm = -d $File::Find::name ? 0555 : 0444;
        chmod $perm, $File::Find::name;
    }
    find(\&wanted, $dir);
    

    【讨论】:

    • 使用这个。比我的好。
    • 应该是:chmod 0555, $File::Find::name;
    • 这会将目录和文件都设置为 555。虽然这对于目录来说没问题,但您可能不希望所有文件都可执行。我想我会尝试给定其他答案之一的 shell 命令。
    • @Jistanidiot:很好的收获;我已经更新了我的答案,所以只有目录才能获得 +x 位。
    【解决方案2】:

    未经测试,但它应该可以工作。请注意,您的目录本身必须保持可执行

    set_perms($dir);
    
    sub set_perms {
         my $dir = shift;
         opendir(my $dh, $dir) or die $!;
         while( (my $entry = readdir($dh) ) != undef ) {
              next if $entry =~ /^\.\.?$/;
              if( -d "$dir/$entry" ) {
                  set_perms("$dir/$entry");
                  chmod(0555, "$dir/$entry");
              }
              else {
    
                  chmod(0444, "$dir/$entry");
              }
         }
         closedir($dh);
    }
    

    当然你也可以从 Perl 执行一个 shell 命令:

    system("find $dir -type f | xargs chmod 444");
    system("find $dir -type d | xargs chmod 555");
    

    如果您有很多条目,我会使用 xargs。

    【讨论】:

    • 如果你使用 shell,chmod -R 通常是最简单的。
    • @Ether - chmod -R 的问题是您无法区分目录和常规文件。您必须将所有文件设置为可执行文件,这可能存在安全风险。
    【解决方案3】:
    system("chmod", "--recursive", "a-w", $dir) == 0
      or warn "$0: chmod exited " . ($? >> 8);
    

    【讨论】:

      猜你喜欢
      • 2016-01-02
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多