Perl Opendir登录?

时间:2013-10-14 06:24:26

标签: perl opendir strawberry-perl

我目前有一个功能可以从网络驱动器复制一些文件并将其粘贴到我的本地服务器文件夹。

sub getNetworkDrive {
    #my $dir="\\\\network\\Path";
    my ($dir, $move_to) = @_;

    opendir(DIR, $dir) or die "can't opendir $dir: $! \n";

    my @files=readdir(DIR);
    closedir DIR;

    foreach my $file (@files) 
    {
        if (-f "$dir$file") 
        {  
            #my $move_to="C:\\Projects\\Perl\\download\\$file";
            my $move_from = "$dir$file";
            copy($move_from, $move_to) or die "Copy Failed: $!";
            print "File: $file : has been downloaded Successfully\n";
        }
    }
}

当我使用我的用户执行脚本时,它完全正常,因为我的用户可以访问网络驱动器。

我想让这个脚本在脚本运行时提示输入授权的用户名和密码。

那么Opendir是否接受用户名和密码作为参数?如果没有那么我的替代方案是什么?

1 个答案:

答案 0 :(得分:0)

感谢mpapec

我为此添加了一个新功能,现在可以使用了

use Win32::NetResource qw/GetUNCName AddConnection CancelConnection/;
use Win32API::File qw/ CopyFile fileLastError /;
sub getNetworkDrive {
    my ($share_name, $user_name, $password) = @_;

    my $drive;
    for my $letter ('g' .. 'z' ) {
        my $mapped;
        $drive = "$letter:";
        GetUNCName( $mapped, $drive );
        last if not $mapped;
    }

    my $share = {
        RemoteName => $share_name,
        LocalName  => $drive,
    };

    print "connecting $share->{RemoteName} to $share->{LocalName}\n";
    if( not AddConnection( $share, $password, $user_name, 0 )) {
        die "connection error:\n", win32err();
    }

    for my $file( @ARGV ) {
        print "copying $file\n";
        CopyFile( $file, "$share->{LocalName}$file", 0 )
            or print "\tfailed: " . fileLastError() . "\n";
    }

    getNetworkDriveWithoutLogin($share->{LocalName}, "C:\\Projects\\Perl\\download\\");

    if( not CancelConnection( $share->{LocalName}, 0, 1 )) {
        print "disconnection error:\n", win32err();
    }
}