Powershell - Checking IP Address range based on CSV file - powershell

I have been developing VM provision script. My question is : I have here-string like below. now , I want to add route based on ip address range. I am using CSV file with BACKUPIP column.
if an BACKUPIP is in range 10.10.104.1 to 10.10.107.254 it will work route add xx.xx.xx.xx mask 255.255.255.0 xx.xx.xx.xx -p
if an BACKUPIP is in range 10.10.180.1 to 10.10.185.254 it will work route add yy.yy.yy.yy mask 255.255.255.0 yy.yy.yy.yy -p
Here is my script:
Import-Csv -Path .\vm.csv -UseCulture -PipelineVariable row |
ForEach-Object -Process {
# Create the VM, store result in $vm
if($($row.IP) -eq '???'){
route add xx.xx.xx.xx mask 255.255.255.0 xx.xx.xx.xx -p
}
else{
route add yy.yy.yy.yy mask 255.255.255.0 yy.yy.yy.yy -p
}
}
LAST UPDATE :
$rangeFrom104 = '10.10.104.1'
$rangeTo107 = '10.10.107.254'
$rangeFrom180 = '10.10.180.1'
$rangeTo185 = '10.10.185.254'
if (([version]$rangeFrom104) -lt ([version]$($row.IP)) -and ([version]$($row.IP)) -lt ([version]$rangeTo107) )
{
route add xx.xx.xx.xx mask 255.255.255.0 xx.xx.xx.xx -p
}
elseif (([version]$rangeFrom180) -lt ([version]$($row.IP)) -and ([version]$($row.IP)) -lt ([version]$rangeTo185) )
{
route add yy.yy.yy.yy mask 255.255.255.0 yy.yy.yy.yy -p
}

Really like the [Version] approach Lee_Dailey suggested.
Here's another approach that converts the IP addresses to their numeric values:
function Convert-IPv4ToDecimal ([string]$IpAddress){
# helper function to return the numeric value (uint32) of a dotted IP
# address string used for testing if an IP address is in range.
$n = [uint32[]]$IpAddress.Split('.')
# or use: $n = [uint32[]]([IpAddress]$IpAddress).GetAddressBytes()
# to get the obsolete property ([IpAddress]$IpAddress).Address
# you need to do the math in reversed order.
# return [uint32] ($n[3] -shl 24) + ($n[2] -shl 16) + ($n[1] -shl 8) + $n[0]
# for comparing different ranges as in this question, do not reverse the byte order
return [uint32] ($n[0] -shl 24) + ($n[1] -shl 16) + ($n[2] -shl 8) + $n[3]
}
$startRange1 = Convert-IPv4ToDecimal '172.25.104.1'
$endRange1 = Convert-IPv4ToDecimal '172.25.107.254'
$startRange2 = Convert-IPv4ToDecimal '172.25.112.1'
$endRange2 = Convert-IPv4ToDecimal '172.25.115.254'
Import-Csv -Path .\vm.csv -UseCulture | ForEach-Object {
# Create the VM, store result in $vm
# convert the .BACKUPIP to numeric value
$backupIp = Convert-IPv4ToDecimal $_.BACKUPIP
# test the IP range
if ($backupIp -ge $startRange1 -and $backupIp -le $endRange1) {
Write-Host "BACKUPIP '$($_.BACKUPIP)' is in Range 1"
route add xx.xx.xx.xx mask 255.255.255.0 xx.xx.xx.xx -p
}
elseif ($backupIp -ge $startRange2 -and $backupIp -le $endRange2) {
Write-Host "BACKUPIP '$($_.BACKUPIP)' is in Range 2"
route add yy.yy.yy.yy mask 255.255.255.0 yy.yy.yy.yy -p
}
else {
Write-Warning "No range defined for IP address '$($_.BACKUPIP)'"
}
}

There exists a IPAddress class in .Net:
$MyIPAddress = [System.Net.IPAddress]'10.10.105.7'
$rangeFrom104 = [System.Net.IPAddress]'10.10.104.1'
$rangeTo107 = [System.Net.IPAddress]'10.10.107.254'
If ($rangeFrom104.Address -lt $MyIPAddress.Address -and $MyIPAddress.Address -lt $rangeTo107.Address) {
# route add xx.xx.xx.xx mask 255.255.255.0 xx.xx.xx.xx -p
}
As #Theo commented, the Address property is obsolete:
This property has been deprecated. It is address family dependent.
Please use IPAddress.Equals method to perform comparisons.
I guess this is due to compliance with IPv6 (but I presume that the property won't easily cease to exist as that would probably break some legacy programs). Anyways, that doesn't mean that the whole [System.Net.IPAddress] class is deprecated. Meaning that you might also use the GetAddressBytes method which I think better than a custom function or relying on a (smart! [version]) type but also are both limited to IPv4 (~4 bytes).
With using the GetAddressBytes method, you might simple convert the bytes to a hexadecimal string, which format is comparable (e.g. '10' -gt '0A') as long as the byte arrays are of the same size (e.g. both IPv4):
function Convert-IPAddressToHexadecimal ([Net.IPAddress]$IPAddress, [Switch]$IPv6) {
If ($IPv6) {$IPAddress = $IPAddress.MapToIPv6()}
[BitConverter]::ToString($IPAddress.GetAddressBytes())
}; Set-Alias IP2Hex Convert-IPAddressToHexadecimal
$MyIPAddress = IP2Hex '10.10.105.7' # 0A-0A-69-07
$rangeFrom104 = IP2Hex '10.10.104.1' # 0A-0A-68-01
$rangeTo107 = IP2Hex '10.10.107.254' # 0A-0A-6B-FE
If ($rangeFrom104 -lt $MyIPAddress -and $MyIPAddress -lt $rangeTo107) {
# route add xx.xx.xx.xx mask 255.255.255.0 xx.xx.xx.xx -p
}
If you do need to make your script IPv6 compliant and comparing IP addresses to both IPv4 ranges and IPv6 ranges, you might consider to map all IP addresses to an IPv6 address: using: $MyIPAddress.MapToIPv6().GetAddressBytes() (the -IPv6 switch):
IP2Hex -IPv6 '10.10.105.7' # 00-00-00-00-00-00-00-00-00-00-FF-FF-0A-0A-69-07
Update 2020-09-06:
It is unclear whether the Address property is really obsolete. See: Avoid byte[] allocations once IPAddress.Address is back #18966.
Anyhow, there is a pitfall in using the Address property for comparison as it appears that the address is stored as Big-Endian read from memory as Little-Endian format, see: System.Net.IPAddress returning weird addresses, causing the last byte in 10.10.104.1 (1) to become most significant.
This means that comparing the Address property might give an incorrect result if there are differences between multiple bytes in the concerned IP Addressed:
([IPAddress]'0.0.0.1').Address -lt ([IPAddress]'0.0.1.0').Address
False

Related

IP Address Input from Jenkins to Variable powershell

I Have Jenkins job that asks for IP Address
$ip = $env:Lan_ip
what the user enter goes to $ip
now $ip is 192.168.10.10 for Example
now I'm trying to insert this variable to FortiGate SSH
Invoke-SshCommand $Firewall -command ‘config system interface
edit port1
set ip $ip 255.255.255.0
end’
but he can not read the $ip I need to make it like INT separate with .
im getting this Error
node_check_object fail! for ip $ip
how can i convert the sting im getting from the user when he enter the ip address in for example --> 192.168.10.10
to usable variable in the code
From what I gather from here is that you need to give the subnet mask as a CIDR-formatted subnet mask like 255.255.255.0/24
To get that CIDR value off a subnet IP address, you can use this function:
function Get-SubnetMaskLength ([string]$SubnetMask) {
# $cidr = Get-SubnetMaskLength "255.255.240.0" --> 20
$result = 0
[IPAddress]$ip = $SubnetMask
foreach ($octet in $ip.GetAddressBytes()) {
while ($octet) {
$octet = ($octet -shl 1) -band [byte]::MaxValue
$result++
}
}
$result
}
So
$subNet = '255.255.255.0'
$cidr = Get-SubnetMaskLength $subNet # --> 24
$subNetAndCidr = '{0}/{1}' -f $subNet, $cidr # --> 255.255.255.0/24
P.S. Always use straight quotes instead of the curly thingies ‘ and ’ in code!

How to get IP Address range from subnet and netmask

Team,
I am new to the forum, also new to the development, i am currently using windows 2016, 2012 & 2008 servers in the environment. The script primarily should work on all the environment.
I wanted to find out the IP start ip address and end ip address.
$params = #{
"ComputerName" = "."
"Class" = "Win32_NetworkAdapterConfiguration"
"Filter" = "IPEnabled=TRUE"
}
$netConfigs = Get-WMIObject #params
foreach ( $netConfig in $netConfigs ) {
for ( $i = 0; $i -lt $netConfig.IPAddress.Count; $i++ ) {
if ( $netConfig.IPAddress[$i] -match '(\d{1,3}\.){3}\d{1,3}' ) {
$ipString = $netConfig.IPAddress[$i]
$ip = [IPAddress] $ipString
$maskString = $netConfig.IPSubnet[$i]
$mask = [IPAddress] $maskString
$netID = [IPAddress] ($ip.Address -band $mask.Address)
"IP address: {0}" -f $ip.IPAddressToString
"Subnet mask: {0}" -f $mask.IPAddressToString
"Network ID: {0}" -f $netID.IPAddressToString
}
}
}
Convert IP address to the subnet
[IPAddress] (([IPAddress] "192.168.100.45").Address -band ([IPAddress] "255.255.255.0").Address)
I am currently using 2016 & i am not getting how to proceed further to get the start ip address and end ip address in a single line of code.
Please advise
You can do the following to get the network and broadcast addresses:
$IP = '192.168.4.5'
$mask = '255.255.0.0'
$IPBits = [int[]]$IP.Split('.')
$MaskBits = [int[]]$Mask.Split('.')
$NetworkIDBits = 0..3 | Foreach-Object { $IPBits[$_] -band $MaskBits[$_] }
$BroadcastBits = 0..3 | Foreach-Object { $NetworkIDBits[$_] + ($MaskBits[$_] -bxor 255) }
$NetworkID = $NetworkIDBits -join '.'
$Broadcast = $BroadcastBits -join '.'
# Output
$NetworkID
192.168.0.0
$Broadcast
192.168.255.255
Explanation:
Since bitwise operators (see About Arithmetic Operators) are only supported on integer types, you must do a string to integer conversion to successfully use the operator[1].
The IP and Mask are split on the . character creating a two string array of the octets. The [int[]] cast converts the array into an Int32 array.
For the network address, we perform a -band (bitwise and) on the same index from each array. Since IPs have four octets, we only need to loop over the 0..3 range. The resulting Int32 array ($NetworkIDBits) items joined by the . character, putting the result in IP address format.
For the broadcast address, we perform a -bxor (bitwise XOR) on the integer array derived from the mask with 255. The goal is to flip all of the ones and zeroes in the mask. The result will be an increment value per octet that can be added to the octets of the network address. The final, calculated result is converted to IP address form using -join.
[1]: You don't always need to explicitly cast strings to integers for the conversion. PowerShell can automatically do this in some cases. For example, in my shell, I do not have to cast with [int[]]
The first ip is just the network address plus 1, although that is usually the gateway. For the broadcast address, I'll just point to this link: https://www.indented.co.uk/powershell-subnet-math/
Getting to the Broadcast Address is a bit more complicated than the
Network Address. A Bitwise Or is executed against an Inverted Subnet
Mask. For example, the Inverted form of 255.255.255.0 is 0.0.0.255.

read section of lines from Cisco IOS configuration loaded as text file in powershell

I'm not expert in powershell but looking to write function in powershell to read section of lines from Cisco IOS configuration loaded in as text file in powershell. there will be multiple sections with different names, each section have parent line with child section as below in configuration. "interface" section have names, "object" section have names and "object-group" section have names to filter them or search. so how to write function to get each section of lines and than parse further to get IPs from that section.
IOS Configuration Example:
interface GigabitEthernet0/0
description XXX
speed 1000
duplex full
nameif XXX
security-level 100
ip address 1.1.1.1 255.255.255.0
!
interface GigabitEthernet0/1
description YYY
speed 1000
duplex full
nameif YYY
security-level 100
ip address 2.2.2.2 255.255.255.0
!
...
object network APP_NETWORK
subnet 10.10.10.1 255.255.255.0
object network WEB_NETWORK
host 10.10.10.2
object network DB_NETWORK
range 10.10.10.3 10.10.10.5
...
object-group network APP_GROUP
network-object host 10.10.20.1
network-object host 10.10.20.2
network-object host 10.10.20.3
object-group network WEB_GROUP
network-object host 10.10.30.1
network-object host 10.10.30.2
network-object host 10.10.30.3
...
For Example I tried following to read all "object-group network" parent sections:
$config = Get-Content $runconfig -ErrorAction stop
$config | where { $_.Contains("object-group network") }
But not able to get its child section along with. how can write function to get parent and child section both.
Example1
Get-Section(object-group network APP_GROUP)
should return following
object-group network APP_GROUP
network-object host 10.10.20.1
network-object host 10.10.20.2
network-object host 10.10.20.3
Example2
Get-Section(nameif XXX) OR Get-Section(interface GigabitEthernet0/0)
should return something like this
interface GigabitEthernet0/0
description XXX
speed 1000
duplex full
nameif XXX
security-level 100
ip address 1.1.1.1 255.255.255.0
!
I have searched many blogs, your help or hints will be really appreciated! Thank you!
One way to do this is to use a state variable and an appropriate regular expression. Here's an example function:
function Get-Section {
param(
[String[]] $configData,
[String] $sectionName
)
$pattern = '(?:^(!)\s*$)|(?:^[\s]+(.+)$)'
$inSection = $false
foreach ( $line in $configData ) {
# Skip empty lines
if ( $line -match '^\s*$' ) {
continue
}
if ( $line -eq $sectionName ) {
$inSection = $true
continue
}
if ( $inSection ) {
if ( $line -match $pattern ) {
[Regex]::Matches($line, $pattern) | ForEach-Object {
if ( $_.Groups[1].Success ) {
$_.Groups[1].Value
}
else {
$_.Groups[2].Value
}
}
}
else {
$inSection = $false
}
if ( -not $inSection ) {
break
}
}
}
}
If your example data is in a text file (e.g., config.txt), you could extract the interface GigabitEthernet0/1 section as follows:
$configData = Get-Content "config.txt"
Get-Section $configData 'interface GigabitEthernet0/1'
The output would be:
description YYY
speed 1000
duplex full
nameif YYY
security-level 100
ip address 2.2.2.2 255.255.255.0
!
The function doesn't output the section's name because you already know it (you passed it to the function).
If you know the number of lines following the APP_GROUP, which in this case is 3, you can use that value for the -Context switch on Select-String:
$config | Select-String -Pattern '(object-group network APP_GROUP)' -Context 0,3
Which would give:
object-group network APP_GROUP
network-object host 10.10.20.1
network-object host 10.10.20.2
network-object host 10.10.20.3
Edit: Alternative regex solution below since no of lines is dynamic
$section = 'APP_GROUP'
$regex = "(?:object-group\snetwork\s$section\n)(\snetwork-object\shost\s.*\n)+(?=object-group)"
$oneline = Get-Content C:\temp\cisco.txt | Out-String
$oneline -match $regex
$matches[0]
network-object host 10.10.20.1
network-object host 10.10.20.2
network-object host 10.10.20.3

PowerShell force [int] to wrap (IP to Long conversion)

Just a quick question as I'm kind of new to math in PowerShell
I need to make a converter in PowerShell that converts IP to Long. It works fine for lower values, but on higher ones it is causing an Integer Overflow.
[int]$a = Read-Host "First bit of IP address"
[int]$b = Read-Host "2nd bit of IP address"
[int]$c = Read-Host "3rd bit of IP address"
[int]$d = Read-Host "4th bit of IP address"
$a *= 16777216
$b *= 65536
$c *= 256
$base10IP = $a + $b + $c + $d
Write-Host $base10IP
Works fine if I input some low-int IP address, like 10.10.10.10 (out 168430090)
But there are cases where this leads to Int overflow. I would like PowerShell to wrap around if [int] reaches maximum value and provide me a negative value.
I work as a service desk and one of the software I support needs IP in Long form, including negative values.
Is it doable in PowerShell ?
Please advise if you need more details or something is not clear.
Alex
A simple solution would be to use [long] instead of [int].
[long]$a = Read-Host "First bit of IP address"
[long]$b = Read-Host "2nd bit of IP address"
[long]$c = Read-Host "3rd bit of IP address"
[long]$d = Read-Host "4th bit of IP address"
$a *= 16777216
$b *= 65536
$c *= 256
$base10IP = $a + $b + $c + $d
Write-Host $base10IP
And you can do what you want in even less lines of code
[IPAddress]$ip = Read-Host "IP address"
$ip.Address
UPDATE
Your comment explains a long wasn't what you where after. It sounds like an int you are looking for.
I could not find a way to have PowerShell do unchecked (losing precision) conversions or arithmetic, but using the BitConverter class you can get it working.
[byte]$a = 10
[byte]$b = 113
[byte]$c = 8
[byte]$d = 203
[BitConverter]::ToInt32(($a, $b, $c, $d), 0)
or
[IPAddress]$ip = "10.113.8.203"
$bytes = [BitConverter]::GetBytes($ip.Address)
[BitConverter]::ToInt32($bytes, 0)
Please note that IPAddress also supports IPv6 addresses, but this last conversion to an int clearly can't hold an IPv6 address.

Calling a variable without a space before it in powershell?

I am trying to use variables from a imported CSV file to substitute variables in a string.
Here's the code.
param( [string] $CSV)
$VMs = Import-Csv $CSV
Foreach ($VM in $VMs) {
psexec \\$VM.VM_Name -h netsh interface ip set address name='"Local Area Connection"' static $VM.IP_Address 255.255.255.0 $VM.Gateway 1
}
this is what it returns:
psexec \#{VM_Name=TESTCSVVM; IP_Address=10.12.81.82; Gateway=10.12.81.1; VLAN=H
Q_VM_81}.VM_Name -h netsh interface ip set address name="Local Area Connection"
static 10.12.81.82 255.255.255.0 10.12.81.1 1
Here's what I want it to look like:
psexec \TESTCSVVM -h netsh interface ip set address name="Local Area Connection"
static 10.12.81.82 255.255.255.0 10.12.81.1 1
Here's the CSV file:
"VM_Name","IP_Address","Gateway","VLAN"
"TESTCSVVM","10.12.81.82","10.12.81.1","HQ_VM_81"
How do I make sure theres no space between the \ and the 1st variable $VM.VM_Name?
Thanks
Try this :
Foreach ($VM in $VMs) {
psexec \\\\$($VM.VM_Name) -h netsh interface ip set address `
name='"Local Area Connection"' `
static $VM.IP_Address 255.255.255.0 $VM.Gateway 1
}
Also, generally wrapping variables in quotes will work too.
So if:
$path = C:\Windows\
$File = MyFile.ext
write-host "$path$File
Would look like:
C:\Windows\myFile.ext