Question

I currently have one function to copy some files from the network drive and paste it to my local server folder.

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";
        }
    }
}

It works perfectly fine when I use my user to execute the script, because my user have access to the network drive.

I would like to make this script to prompt for an authorized username and password whenever the script is runned.

So does Opendir accept username and password as parameter? if it doesn't then what is my alternative?

Was it helpful?

Solution

Thanks to mpapec

I added a new function for this and it works now

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();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top