Showing posts with label remote. Show all posts
Showing posts with label remote. Show all posts

08 November, 2015

List DNS scavenging settings on multiple servers remotely - AD

DDNS (Dynamic DNS where clients register their own DNS records) was a very good idea when it was published in RFC2136 and had been missing like a slice of bread, but it inevitably left some questions on the table. For example, if I let 100 000 hosts register their own records, who will tell them to clean-up their stuff if they don't need it anymore? On the other hand, if I don't use DDNS and I have only one DHCP server registering addresses, I can just regulate that one guy and tell it off if it doesn't cleanup its rubbish.

The answer is DNS scavenging which would be the butter on that slice of bread just to make it taste better and proper. But we want to make sure that the butter we put on the bread is not rotten. Otherwise we would need to throw the bread to the bin with the butter... ok, enough of this nonsense.

DNS scavenging essentially deletes stale / old records from the given DNS Zone. What we want to make sure that the scavenging process is properly configured otherwise we could end up losing very valuable DNS records and cause outages - believe me, you don't want an outage caused by something as fundamental as DNS.

There are a couple of rules we need to keep in mind:
  • The scavenging intervals have to be thought through - I'd go with the default settings 7+7 days
  • There should be only 1 DNS server scavenging the zone regularly even if we have lots of e.g. Domain Controllers hosting the zone.
  • The zone should be restricted and only that one server should be allowed to scavenge the zone. You can read more about scavenging e.g. here and here 
Question: if I have 100 domain controllers hosting an AD integrated zone how can I check if there's only one set to scavenge the zone. To get these settings from one server, you can use dnscmd /info. To do it on multiple servers you can do some dnscmd output parsing in powershell, e.g.:

Create an object where you will store the name of the DNS host, the scavenging interval set on that server and the default aging state on that server:
$sObject = "" | select hostname,ScavengingInterval,LastScav,DefaultAgingState

Take the output of dnscmd /info and go through each line:
dnscmd $srv /info | %{

If it's the line where scavenging info is stored, do some regex matching to take out the bits you need:
if($_ -imatch "last scav"){
$value = ([regex]::Match($_, "= .+$")).value -replace "= ",""

Add it to your output object:
$sObject.LastScav = $value

It will show you an output like this:
Note the date and result of the last scavenging run









The full script:
 # get the list of Windows DNS servers from the pipe  
 $hostlist = @($Input)  
   
 $hostlistlength = ($hostlist | measure).count  
   
 # go through each host  
 foreach($srv in $hostlist){  
    $sObject = "" | select hostname,ScavengingInterval,LastScav,DefaultAgingState  
   
    # run dnscmd to get the detailed info of each DNS server  
    dnscmd $srv /info | %{  
       $value = $null  
   
       # pick out the data from dnscmd output with regex matches  
       if($_ -imatch "last scav"){  
          $value = ([regex]::Match($_, "= .+$")).value -replace "= ",""  
          $sObject.LastScav = $value  
          $value = $null  
       }  
       elseif($_ -imatch "ScavengingInterval"){  
          $value = ([regex]::Match($_, "= .+$")).value -replace "= ",""  
          $sObject.ScavengingInterval = $value  
          $value = $null  
       }  
       elseif($_ -imatch "DefaultAgingState"){  
          $value = ([regex]::Match($_, "= .+$")).value -replace "= ",""  
          $sObject.ScavengingInterval = $value  
          $value = $null  
       }  
    }  
    $sObject  
 }  
   




02 June, 2013

Edit scheduled task remotely - OS

The other day, I had a couple of 100 servers where I needed to edit a particular scheduled task. Fortunately or unfortunately all of them were Windows 2008 servers. Why am I saying that?
On Windows 2003, scheduled tasks are simple, there's one command or action, start time, run as credentials and some little other bits. So if you want to "edit" a task, you can just delete and recreate it with whatever change you wanted to make.
Unfortunately, on Windows 2008, it's not that simple. There are multiple triggers you can define, multiple actions a task can run...etc.:

Scheduled Task on Windows 2008

However, fortunately, you can export a scheduled task into an xml file, which is quite cool as the xml format is easy to handle in PowerShell.
You can just edit the xml and import it back (basically recreate the whole task with all the settings defined in the xml).

Easy to get xml representation of a Scheduled task in PowerShell

A couple of key things in the script below. Connect to the remote machine and get task details:
$schedSvc = New-object -ComObject Schedule.Service
$schedSvc.connect($srv) 
$schFolder = $schedSvc.GetFolder("\") 
$schFolder = $schFolder.GetFolder($taskfolder) 
$schedTask = $schFolder.GetTask($taskName) 
$schedTask.xml | Out-File "$env:TEMP\$srv-$taskname.xml" -Force

Edit the xml and create a new file:
gc "$env:TEMP\$srv-$taskname.xml" | %{
....
....
} | Out-File "$env:TEMP\$srv-$taskname-new.xml" -Force 


Recreate the scheduled task remotely (for this I use schtasks.exe for the sake of simplicity, although the COM object mentioned above could be used as well):
$res = schtasks.exe /create /S $srv /RU SYSTEM /TN "$taskfolder\$taskName" /XML "$env:TEMP\$srv-$taskname-new.xml" /F

The script has Object type output which looks like this:
ComputerName oldValue Result
------------ -------- ------
R2D2              120 OK
JARJAR            120 OK
C3PO             3456 OK

The script (without log and error handling):
   
        
        
 param(     [string] $hosts = "",  
           [string] $taskName = "",  
           [string] $taskFolder = "",  
           [string] $newvalue = "")  
   
 #### Collate the host list.  
 $hostlist = @($Input)  
 if ($hosts) {  
      if($hosts -imatch " "){  
           $hostsArr = @($hosts.split(" "))  
           $hostlist += $hostsArr  
      }  
      else{  
           $hostlist += $hosts  
      }  
 }  
   
 foreach($srv in $hostlist){  
      $script:sObject = "" | select ComputerName,oldValue,Result  
      $script:sObject.ComputerName = $srv  
        
      # connect to remote host and export the scheduled task to an xml  
      $schedSvc = New-object -ComObject Schedule.Service  
      $schedSvc.connect($srv)  
      $schFolder = $schedSvc.GetFolder("\")  
      $schFolder = $schFolder.GetFolder($taskfolder)  
      $schedTask = $schFolder.GetTask($taskName)  
      $schedTask.xml | Out-File "$env:TEMP\$srv-$taskname.xml" -Force  
        
      # edit the given text in the xml  
      if(Test-Path "$env:TEMP\$srv_$taskname.xml"){  
           gc "$env:TEMP\$srv-$taskname.xml" | %{  
             
                if($_ -imatch "\\myapplication.exe\."){  
                     $script:sObject.oldValue = ([regex]::Match($_, "-parameter=\d")).Value -ireplace "-parameter=",""  
   
                     $newline = $_ -ireplace "parameter=\d+", "parameter=$newvalue"  
                       
                }  
                else{  
                     $newline = $_  
                }  
                $newline  
           } | Out-File "$env:TEMP\$srv-$taskname-new.xml" -Force  
             
             
           # import the new task xml  
           $res = schtasks.exe /create /S $srv /RU SYSTEM /TN "$taskfolder\$taskName" /XML "$env:TEMP\$srv-$taskname-new.xml" /F  
             
           if($res -imatch "Success"){  
                $script:sObject.Result = "OK"  
           }  
           else{  
                $script:sObject.Result = "Could not import task $taskname"  
           }  
      }  
      else{  
           $script:sObject.Result = "Could not export task $taskname"  
      }  
      $objColl += $script:sObject  
 }  
   
 $objColl  
   


t


07 December, 2012

Machine Policy Retrieval - SCCM

A very efficient way to break tens of thousands of machines is to install something on them using a deployment / configuration management software, such as SCCM.

It's always a bad idea to send out a package on a Friday afternoon - and hope for the best - because the longest afternoons are usually the Friday ones, they can last several days when you need to remediate a couple of 1000 hosts where application installations got corrupted because of your Friday SCCM package. What you want, before hitting the full list of 1000s of servers with a package is to send it out to a couple and quickly see the result. However, if you send out a package it can take up to an hour to see the results in SCCM - depending on your SCCM site settings... How can you make it quicker? Invoke a client action on each host called "Machine Policy Retrieval & Evaluation Cycle".

SCCM Client Actions
I know there are many very good tools out there for SCCM with UI and multiple functions and fancy remote host handling capabilities, however, a couple of years ago - because I like the command line way - I thought I'd write a quick script which is able to invoke SCCM Client side actions on multiple hosts remotely At the same time it would have the capability of pipe'ing the output to another PowerShell script or some file or export it to csv...whatever.

Background:
SCCM client has several agents and those can perform actions, such as downloading policies and packages from the server, perform software or hardware inventories...etc. Because all these agents are built on WMI, you can invoke actions by creating WMI instances of specific WMI classes on the remote machine.


OK, so the idea is there. When you want to break.. khm deploy something on many, many servers, you just pick about 50 or maybe 100 firts, send out the package and then... and this is where powershell comes in: run the following script to invoke the MAchine Policy Retrieval & Evaluation Cycle which will make the client download the package and run it + report back to the SCCM server.

$hostlist = @($Input)

if($($hostlist.length) -gt 0){
    foreach ($srv in $hostlist) {

        # Binding \\$srv\root\ccm:SMS_Client
        $SMSCli = [wmiclass] "\\$srv\root\ccm:SMS_Client"

        if($SMSCli){

            #Invoking $actionName
            $check = $SMSCli.RequestMachinePolicy()
            $check = $SMSCli.EvaluateMachinePolicy()
        }
        else{
            write-host "$srv, Could not bind WMI class SMS_Client"
        }
    }
}


Save it as a something.ps1 file and use it like this:
PS C:\> gc hostlist.txt | something.ps1

Clipboard friendly code:
 $hostlist = @($Input)  
   
 if($($hostlist.length) -gt 0){  
      foreach ($srv in $hostlist) {  
           # Binding \\$srv\root\ccm:SMS_Client  
           $SMSCli = [wmiclass] "\\$srv\root\ccm:SMS_Client"  
           if($SMSCli){  
                #Invoking $actionName   
                $check = $SMSCli.RequestMachinePolicy()  
                $check = $SMSCli.EvaluateMachinePolicy()  
                  
           }  
           else{  
                write-host "$srv, Could not bind WMI class SMS_Client"  
           }  
      }  
 }