Perl 脚本查找 Unix 上所有无主文件和目录 - 如何进一步优化?

标签 perl unix scripting find file-find

按照我在其他帖子中的发现和建议 How to exclude a list of full directory paths in find command on Solaris ,我决定编写此脚本的 Perl 版本,并了解如何优化它以比 native find 命令运行得更快。到目前为止,结果令人印象深刻!

此脚本的目的是报告 Unix 系统上所有无主文件和目录,以实现审计合规性。该脚本必须接受要排除的目录和文件列表(通过完整路径或通配符名称),并且必须占用尽可能少的处理能力。它旨在运行在我们(我工作的公司)支持的数百种 Unix 系统上,并且能够在所有这些 Unix 系统上运行(多个操作系统、多个平台:AIX、HP-UX、Solaris 和 Linux)我们无需先安装或升级任何东西。换句话说,它必须与我们期望在所有系统上运行的标准库和二进制文件一起运行。

我尚未使脚本能够识别参数,因此所有参数都硬编码在脚本中。我计划最后有以下参数,并且可能会使用 getopts 来做到这一点:

-d = comma delimited list of directories to exclude by path name
-w = comma delimited list of directories to exclude by basename or wildcard
-f = comma delimited list of files to exclude by path name
-i = comma delimited list of files to exclude by basename or wildcard
-t:list|count = Defines the type of output I want to see (list of all findinds, or summary with count per directory)

这是我迄今为止所做的来源:

#! /usr/bin/perl
use strict;
use File::Find;

# Full paths of directories to prune
my @exclude_dirs = ('/dev','/proc','/home');

# Basenames or wildcard names of directories I want to prune
my $exclude_dirs_wildcard = '.svn';

# Full paths of files I want to ignore
my @exclude_files = ('/tmp/test/dir3/.svn/svn_file1.txt','/tmp/test/dir3/.svn/svn_file2.txt');

# Basenames of wildcard names of files I want to ignore
my $exclude_files_wildcard = '*.tmp';
my %dir_globs = ();
my %file_globs = ();

# Results will be sroted in this hash
my %found = ();

# Used for storing uid's and gid's present on system
my %uids = ();
my %gids = ();

# Callback function for find
sub wanted {
    my $dir = $File::Find::dir;
    my $name = $File::Find::name;
    my $basename = $_;

    # Ignore symbolic links
    return if -l $name;

    # Search for wildcards if dir was never searched before
    if (!exists($dir_globs{$dir})) {
        @{$dir_globs{$dir}} = glob($exclude_dirs_wildcard);
    }
    if (!exists($file_globs{$dir})) {
        @{$file_globs{$dir}} = glob($exclude_files_wildcard);
    }

    # Prune directory if present in exclude list
    if (-d $name && in_array(\@exclude_dirs, $name)) {
        $File::Find::prune = 1;
        return;
    }

    # Prune directory if present in dir_globs
    if (-d $name && in_array(\@{$dir_globs{$dir}},$basename)) {
        $File::Find::prune = 1;
        return;
    }

    # Ignore excluded files
    return if (-f $name && in_array(\@exclude_files, $name));
    return if (-f $name && in_array(\@{$file_globs{$dir}},$basename));

    # Check ownership and add to the hash if unowned (uid or gid does not exist on system)
    my ($dev,$ino,$mode,$nlink,$uid,$gid) = stat($name);
    if (!exists $uids{$uid} || !exists($gids{$gid})) {
        push(@{$found{$dir}}, $basename);
    } else {
        return
    }
}

# Standard in_array perl implementation
sub in_array {
    my ($arr, $search_for) = @_;
    my %items = map {$_ => 1} @$arr;
    return (exists($items{$search_for}))?1:0;
}

# Get all uid's that exists on system and store in %uids
sub get_uids {
    while (my ($name, $pw, $uid) = getpwent) {
        $uids{$uid} = 1;
    }
}

# Get all gid's that exists on system and store in %gids
sub get_gids {
    while (my ($name, $pw, $gid) = getgrent) {
        $gids{$gid} = 1;
    }
}

# Print a list of unowned files in the format PARENT_DIR,BASENAME
sub print_list {
    foreach my $dir (sort keys %found) {
        foreach my $child (sort @{$found{$dir}}) {
            print "$dir,$child\n";
        }
    }
}

# Prints a list of directories with the count of unowned childs in the format DIR,COUNT
sub print_count {
    foreach my $dir (sort keys %found) {
        print "$dir,".scalar(@{$found{$dir}})."\n";
    }
}

# Call it all
&get_uids();
&get_gids();

find(\&wanted, '/');
print "List:\n";
&print_list();

print "\nCount:\n";
&print_count();

exit(0);

如果您想在系统上测试它,只需创建一个包含通用文件的测试目录结构,使用为此目的创建的测试用户 chown 整个树,然后删除该用户。

我会接受您给我的任何提示、技巧或建议。

祝您阅读愉快!

最佳答案

尝试从这些开始,然后看看是否还有其他可以做的。

  1. 使用散列而不是需要使用 in_array() 搜索的数组。这样您就可以一步执行直接哈希查找,而不是每次迭代都将整个数组转换为哈希。

  2. 您不需要检查符号链接(symbolic link),因为它们将被跳过,因为您尚未设置 follow选项。

  3. 最大限度地利用 _ ;避免重复IO操作。 _是一个特殊的文件句柄,每当您调用 stat() 或任何文件测试时,都会在其中缓存文件状态信息。这意味着您可以调用 stat _-f _而不是stat $name-f $name 。 (在我的机器上调用 -f _-f $name 快 1000 倍以上,因为它使用缓存而不是执行其他 IO 操作。)

  4. 使用 Benchmark 模块来测试不同的优化策略,看看你是否真的获得了任何东西。例如。

    use Benchmark;
    stat 'myfile.txt';
    timethese(100_000, {
        a => sub {-f _},
        b => sub {-f 'myfile.txt'},
    });
    
  5. 性能调优的一般原则是在尝试调优之前准确找出慢速部分的位置(因为慢速部分可能不在您期望的位置)。我的建议是使用 Devel::NYTProf ,它可以为您生成 html 配置文件报告。从概要来看,如何使用它(从命令行):

    # profile code and write database to ./nytprof.out
    perl -d:NYTProf some_perl.pl
    
    # convert database into a set of html files, e.g., ./nytprof/index.html
    # and open a web browser on the nytprof/index.html file
    nytprofhtml --open
    

关于Perl 脚本查找 Unix 上所有无主文件和目录 - 如何进一步优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7867686/

相关文章:

xml - 使用Perl从xml文件中提取字符串

unix - 相当于 PowerShell 中的 *Nix 'which' 命令?

bash - 使用 awk 将行中的变量存储在文本文件中并切入 for 循环

C# 嵌入脚本解释器时限制命名空间

perl - Devel::Cover 条件三元运算符的分支覆盖

perl - 找出所有相乘得到 X 的整数?

jquery - 如何使用 jQuery 模糊事件向 Perl 脚本发出 AJAX 请求?

unix - 可以在终端中突出显示制表符吗?

powershell - Windows Powershell 是否有 Try/Catch 或其他错误处理机制?

python - 捕获外部命令的输出并将其写入文件