Wednesday, July 27, 2016

Running Powershell Script on Multiple Machines

 on  with No comments 
In , ,  
Part of my responsibility is remediation of the vulnerabilities picked up by the monthly vulnerability scan.  You know the routine, every month Nessus scans the entire network, rattling the locks on the doors and windows of every host it comes across, and then spits out pretty reports detailing everything it finds.  A lot of things are one off findings on a machine or two that have just been recently imaged or have a piece of software that isn't on the other machines.  We'll usually knock those out by hand.  But occasionally a new vulnerability comes along and there are hundreds or even thousands of machines with the vulnerability, and there isn't an existing tool or process to take care of it.  This is where PowerShell comes in handy.

The first example script I have here is to knock out a common vulnerability that keeps coming up, Nessus Plugin 63155, "Microsoft Windows Unquoted Service Path Enumeration.  We have a PowerShell script already available from Microsoft to deal with this problem, but it unfortunately is written to only run on the host machine.  So my contribution is a wrapper script that takes a file called hostslist.txt from the current user's My Documents folder, and executes Microsoft's script on each machine in that list.  Put one hostname per line, nothing more.

$a = Get-Content $env:userprofile\DOCUMENTS\hostlist.txt

foreach ($i in $a)
{
  Invoke-Command -filepath c:\scripts\Windows_Path_Enumerate_v3.1.ps1 -computername $i
}


The next example again involves Windows services, but this time it's the permissions on the executable.  Since it's running icacls.exe, rather than a PowerShell script, it was a little more complicated to hack together, but nothing that was impossible.   This again takes a list of hostnames from the users's My Documents folder and executes icacls on those machines.

I like this one better overall because you can stuff any number of PowerShell cmdlet's inside the braces on the ScriptBlock parameter.

$a = Get-Content $env:userprofile\DOCUMENTS\hostlist.txt
$command = 'c:\windows\system32\icacls.exe c:\Progra~2 /remove Everyone /T /C'

foreach ($i in $a)
{
  Invoke-Command -ComputerName $i -ScriptBlock {Invoke-Expression $args[0]} -ArgumentList $command
}


If you're new to scripting, or to PowerShell, I highly suggest the videos available at the Microsoft Virtual Academy.  A lot of the PowerShell related videos I watched when I was studying for the MCSA 2012 were taught by Jeffrey Snover, the architect of PowerShell himself and/or Jason Hemlick, Microsoft MVP and Pluralsight author.
Share:

0 comments:

Post a Comment

Discuss this post!