Enumerating networks and building routes with PowerShell

I've been working with a company that is in the process of setting up a remote datacenter for disaster recovery. They brought me in to help design their Exchange cross-site resilience, and I've been helping them with a few other things too.

Primary connectivity between the primary datacenter and the remote datacenter is via an L2TP tunnel, nailed up and encrypted, across the public Internet, using RRAS.

With over 300 servers in the primary datacenter and over 100 servers targeted in the remote datacenter, we needed a way to set up the proper routes for each server farm to access the other (in both cases, the default gateway is a TMG array).

I decided that I could do that in a few lines of PowerShell. Truth be told, the basic functionality is pretty simple – you iterate through the computers you are examining, look at the wired network interfaces on those computers, see those that have a particular source IP address, and give them a route to the destination network.

However – and as always, the devil is in the details – It Ain't That Simple (IATS – HAH!).

First of all, Active Directory was used as the source of computers. That's great! However, there are computers in AD that aren't in DNS. I have no clue how that happened, but one can surmise that the computers were cut off, their IP addresses reassigned, and the computer object never removed from AD. That's one condition we have to deal with.

Secondly, as a corollary to the above, workgroup computers aren't found at all. With the solution presented here, there were already DNS entries for these computers (and there were only a handful of them), so we temporarily created computer objects for them in AD.

Third, we found some computers have bad IP addresses (specifically 0.0.0.0). Again, I have no clue how that happened, but those have to be filtered out.

Fourth, group policies in this organization aren't applied very logically. That's not what they called me in for, so I had little say. Regardless, a number of computer did not have remote management enabled, thus preventing remote examination of their configuration and remote changes to their configuration. Detection of computers without remote management thus became something the script had to deal with.

Fifth, we had first decided to use 'ping' to determine the accessibility of the computers as part of the discovery process. Well, fewer than half of the computers allowed 'ping' through their firewalls, so that solution had to be summarily discarded. In order to determine accessibility, we actually had to attempt to access the computers.

Sixth, and this is actually a downstream symptom of the issue above, on some servers remote management generates an error. Those servers need to be detected and repaired.

Seventh, and finally, some servers have multiple IP addresses. This may mean that they are already being used as RRAS servers and they need human intelligence to determine whether a route change should be applied.

I didn't use "route add" because in some situations "route add" is known to fail, and "netsh interface ipv4 add route" is preferred.

The resulting utility script is not particularly pretty. But it's very useful and the techniques illustrated are likely to be useful for you in your scripting needs too. So, I present it for your pleasure. 🙂


[string] $nl = "`r`n"

$HKCR = 2147483648
$HKCU = 2147483649
$HKLM = 2147483650

$script:badIP         = @()
$script:commands      = @()
$script:cannotping    = @()
$script:cannotresolve = @()
$script:cannotmanage  = @()
$script:warningmsg    = @()

function msg
{
	$str = ''

	foreach( $arg in $args )
	{
		$str += $arg + ' '
	}
	Write-Host $str
}

function RegRead
{
	Param(
		[string]$computer,
		[int64] $hive,
		[string]$keyName,
		[string]$valueName,
		[ref]   $value,
		[string]$type = "REG_SZ"
	)

	$wmi = [wmiclass]"\\$computer\root\default:StdRegProv"
	if( $wmi -eq $null )
	{
		$script:cannotmanage += $computer
		return 1
	}

	$r = $wmi.GetStringValue( $hive, $keyName, $valueName )
	$value.Value = $r.sValue

	$wmi = $null

	return $r.ReturnValue
}


function test-ping( [string]$server )
{
	[string]$routine = "test-ping:"

	trap 
	{
		# we should only get here if the New-Object fails.

		write-error "$routine Cannot create System.Net.NetworkInformation.Ping for $server."
		return $false
	}

	$ping = New-Object System.Net.NetworkInformation.Ping
	if( $ping )
	{
		trap [System.Management.Automation.MethodInvocationException] 
		{
			###write-error "$routine Invalid hostname specified (cannot resolve $server)."
			msg "...cannot resolve $server in DNS"
			$script:cannotresolve += $server
			return $false
		}

		for( $i = 1; $i -le 2; $i++ )
		{
			$rslt = $ping.Send( $server )
			if( $rslt -and ( $rslt.Status -eq [System.Net.NetworkInformation.IPStatus]::Success ) )
			{
				### msg "$routine Can ping $server. Successful on attempt $i."
				$ping = $null
				return $true
			}
			sleep -seconds 1
		}
		$ping = $null
	}

	###write-error "$routine Cannot ping $server. Failed after 5 attempts."
	msg "...cannot ping $server"
	$script:cannotping += $server

	return $false
}

### 
### Main
###

$start = (get-date).DateTime.ToString()
msg 'Begin' $start

ipmo ActiveDirectory
$computers = Get-AdComputer -Filter * -SearchBase "OU=Servers,DC=example,DC=com" -ResultSetSize $null | Select DnsHostName
msg "There are $($computers.Count) computers to check"
$computerCount = 0
foreach( $computer in $computers)
{
	$computerName = $computer.DnsHostName
	$computerCount++
	msg "Checking $computername... ($computerCount of $($computers.Count))"

#	if( -not ( test-ping $computerName ) )
#	{
#		###msg '...cannot resolve or ping'
#		msg ' '
#		continue
#	}

	### server IP addresses - I only care about IPv4
	$serverIPv4   = @()
	$serverIPname = @()

	$nicSettings = gwmi Win32_NetworkAdapterSetting -EA 0 -ComputerName $computerName
	if( $nicSettings -eq $null )
	{
		msg "...cannot access $computername"
		msg " "
		$script:cannotresolve += $computername
		continue
	}

	foreach( $nicSetting in $nicSettings )
	{
		### msg "Element=" $nicSetting.Element ## is of type Win32_NetworkAdapter
		if( $nicSetting.Element -eq $null )
		{
			msg "...netSetting.Element is null"
			continue
		}

		$nicElement = [wmi] $nicSetting.Element
		if( $nicElement -eq $null )
		{
			msg "...nicElement is null"
			continue
		}

		if( $nicElement.AdapterType -eq "Ethernet 802.3" )
		{
			### msg "Setting=" $nicSetting.Setting
			$nicConfig = [wmi] $nicSetting.Setting ## is of type Win32_NetworkAdapterConfiguration
			$nicGUID = $nicConfig.SettingID
			### msg "NicGUID=" $nicGUID
			### msg "NIC IPEnabled=" $nicConfig.IPEnabled.ToString()
			if( $nicConfig.IPEnabled -eq $true )
			{
				$returnValue = $true ## there is at least one valid NIC

				$hive = $HKLM
				$keyName = "System\CurrentControlSet\Control\Network\" +
					"{4D36E972-E325-11CE-BFC1-08002BE10318}\" + 
					$nicGUID + 
					"\Connection"
				$valueName = "Name"

				$name = ''
				$result = RegRead $computerName $hive $keyName $valueName ( [ref] $name ) 'reg_sz'
				if( $result -ne 0 )
				{
					$name = ""
				}

				###msg "NIC name:" $name

				$script:arrNicName += $name
				foreach( $ip in $nicConfig.IPAddress )
				{
					if( $ip.IndexOf( ':' ) -ge 0 )
					{
						$script:arrIPListPublic_v6 += $ip
						###msg "IPv6 address " $ip
					}
					else
					{
						$script:arrIPListPublic_v4 += $ip
						$serverIPv4   += $ip
						$serverIPname += $name
						###msg "IPv4 address:" $ip
					}
				}
			}
			$nicConfig = $null
		}
		$nicElement = $null
	}
	$nicSettings = $null

	$limit = $serverIPv4.Count - 1

	$allowedAddresses = 0
	for( $i = 0; $i -le $limit; $i++ )
	{
		$ip = $serverIPv4[ $i ]
		$name = $serverIPname[ $i ]

		if( $ip.Length -lt 10 )
		{
			$script:badIP += "$computerName $name $ip"
		}
		elseif( $ip.SubString( 0, 10 ) -eq "10.129.59." )
		{
			msg "*** YES - $computerName is on the server room secure network using NIC '$name' ***"
			$cmd = 'netsh -r ' + $computerName + 
				' interface ipv4 add route 10.129.68.0/22 "' + $name + '" 10.129.59.104'
			$script:commands += $cmd
			$allowedAddresses++
		}
		elseif( $ip.SubString( 0, 10 ) -eq "10.129.68." )
		{
			msg "*** YES - $computerName is on the datacenter network using NIC '$name' ***"
			$cmd = 'netsh -r ' + $computerName + 
				' interface ipv4 add route 10.129.59.0/20 "' + $name +'" 10.129.68.7'
			$script:commands += $cmd
			$allowedAddresses++
		}
	}
	if( $allowedaddresses -gt 1 )
	{
		msg "*** WARNING ***"
		$m = "$computerName has more than one IPv4 address. It may require extra configuration."
		msg $m
		$script:warningmsg += $m
		msg "*** WARNING ***"
	}

	if( $allowedaddresses -eq 0 )
	{
		msg "...no 10.129.59.0/24 or 10.129.68.0/24 IP addresses found on this computer (out of $($serverIPv4.Count))"
	}

	msg " "
}

msg "List of computers and NICs with bad IP addresses ($($script:badIP.Count))"
$script:badIP
' '

msg "List of computers in AD who cannot be accessed ($($script:cannotresolve.Count))"
$script:cannotresolve
' '

#msg "List of computers in AD who cannot be pinged ($($script:cannotping.Count))"
#$script:cannotping
#' '

msg "List of computer in AD who cannot be managed ($($script:cannotmanage.Count))"
$script:cannotmanage
' '

msg "Warning messages ($($script:warningmsg.Count))"
$script:warningmsg
' '

msg "Full list of routing commands ($($script:commands.Count))"
$script:commands
' '

msg 'Began at' $start
msg 'Done at' (get-date).DateTime.ToString()

 

Leave a Reply

Your email address will not be published. Required fields are marked *