Perl – Filesys::SmbClient and Tie

We recently had need to grab a small file from a machine (network management devices running NT4 client) to a Perl script. We can’t make changes on these clients but the file is available on a network share.
Enter the Filesys::SmbClient module, the documentation of which shows the use of a Tie that would make reading the file much easier. The example however does not pass any parameters like login credentials.

Below are a couple of examples on how to make this work:

#!/usr/bin/perl

use strict;
use POSIX;

my @args = (
username => ‘userid’,
password => ‘passwd’,
debug => 10
);

local *FD;
tie *FD, ‘Filesys::SmbClient’, @args;
open FD, ‘smb://host/directory/file’
or die “Can’t read file:”, $!, “\n”;
print while (<FD>);

close (FD);

or

#!/usr/bin/perl

use strict;
use warnings;

use Filesys::SmbClient;
my %args = (
username => ‘account’,
password => ‘secret’,
workgroup => ‘domain’,
debug => 0
);

my $smb = new Filesys::SmbClient(%args);

my $filename = ‘smb://server/share/directory/file.name’;
my $remote = $smb->open($filename) or die “Can’t open $filename: $!\n”;
open my $local, ‘>’, ‘file.name’ or die “Can’t open file.name: $!\n”;
while ( defined( my $buffer = $smb->read($remote) ) ) {
last if $buffer eq ”;
print {$local} $buffer;
}
$smb->close($fd);

Bad Behavior has blocked 196 access attempts in the last 7 days.