Tuesday, April 22, 2014

Using File::Copy to Deploy Files to a Windows UNC Path



Below is script that illustrates the use of File::Copy to copy files to a UNC path on a Windows network.  The example code downloads a copy of the hosts file made available by the Malware Domain List and copies it to the appropriate directory on a Windows machine in order to prevent the machine from being able to successfully resolve those malicious sites.  

#!usr/bin/perl

use LWP;
use File::Copy;
use strict;
use warnings;

#URL of hosts file
my $URI = 'http://www.malwaredomainlist.com/hostslist/hosts.txt';

#downloads host file
my $ua = LWP::UserAgent->new();
my $request = HTTP::Request->new(GET => $URI);
my $response = $ua->request($request);
my $content = $response->content();
#print $content;

#writes downloaded hosts file to file
open(my $hosts2, ">", "hosts2.txt");
print $hosts2 "$content";
close $hosts2;

#opens file that stores list of PC names
open(my $computers, "<", "computers.txt")
   or die "cannot open < computers.txt: $!";

#copies file to proper location on each computer  
while(<$computers>){
   my $computer=$_;
   print $computer;
   my $path1='hosts2.txt';
   my $path2="\\\\$computer\\C\$\\WINDOWS\\system32\\drivers\\etc\\hosts";
   copy("$path1","$path2") or die "Copy failed: $!";
}

close $computers;