end0tknr's kipple - 新web写経開発

http://d.hatena.ne.jp/end0tknr/ から移転しました

SMB::Client for perl で接続し、file一覧をtraverse作成

↓こう書くみたい

#!/usr/local/bin/perl
use strict;
use warnings;
use Encode;
use File::Basename;
use File::stat;
use SMB::Client;
use Data::Dumper;

my $CONF =
    {nas_smb=>
     {share_uri=>'//10.100.21.???/nas',
      options=> {
                 username => 'ないしょ',
                 password => 'ないしょ',
                 quiet    => 0,
                 verbose  => 0,
                 log_level => SMB::LOG_LEVEL_INFO}},
    };


main( @ARGV );

sub main {
    my ($parent_path ) = @_;

    if(not defined($parent_path) or length($parent_path)==0){
        $parent_path = '';
    }
    
    # NAS接続client初期化
    my $smb_tree = init_nas_smb();
    unless($smb_tree){
        my $tmp_msg = "fail init_nas_smb()";
        die "$tmp_msg $!";
    }

    traverse_smb_tree($smb_tree, $parent_path);
}

sub traverse_smb_tree {
    my ($smb_tree, $parent_path ) = @_;

    my $find_path = join('/',$parent_path,'*');
    my @file_or_dirs = $smb_tree->find( $find_path );

    for my $file_or_dir ( @file_or_dirs ){
        
        next if( $file_or_dir->{name} eq '.' or
                 $file_or_dir->{name} eq '..');

        my $full_path = join('/', $parent_path, $file_or_dir->{name});

    # dir or fileの判定をいまいち、理解していません
        if( $file_or_dir->{attributes} == 16 ){
#        if( $file_or_dir->{allocation_size} == 0 ){
            print "DIR\t$full_path\n";
            traverse_smb_tree($smb_tree,$full_path);
            next;
        }

        my $disp_cols_str =
            join("\t",
                 "FILE",
                 $full_path,
                 $file_or_dir->size_string,
                 $file_or_dir->mtime_string);
        print $disp_cols_str,"\n";

    }
}

sub init_nas_smb {

    my $client = SMB::Client->new($CONF->{nas_smb}->{share_uri},
                                  %{$CONF->{nas_smb}->{options}});
    my $tree = $client->connect_tree;
    unless( $tree ){
        my $msg = "fail SMB::Client->connect_tree $CONF->{nas_smb}->{share_uri}";
        die "$msg $!";
    }
    return $tree;
}

1;