I have a list of ACLs that I need to organize so I can remove them from another database. Some of the lines have subnets as the source, some have ip addresses. Does anyone know anyway I can organize this into a csv file like this:
Jerry,192.168.1.2,192.168.1.3
Jason,2.2.2.2,192.168.1.0 255.255.255.0
access-list outside line 1 extended permit tcp object-group Jerry host 10.10.10.1 eq 7030 0x1a9153aa
access-list outside line 1 extended permit tcp host 192.168.1.1 host 10.10.10.1 eq 7030 (hitcnt=6) 0x3b6b876b
access-list outside line 1 extended permit tcp host 192.168.1.2 host 10.10.10.1 eq 7030 (hitcnt=0) 0x592c1755
access-list outside line 1 extended permit tcp host 192.168.1.3 host 10.10.10.1 eq 7030 (hitcnt=0) 0x8cd36041
access-list outside line 1 extended permit tcp host 192.168.1.4 host 10.10.10.1 eq 7030 (hitcnt=17) 0x8c336546
access-list outside line 2 extended permit tcp object-group Jason host 10.10.10.5 eq 3051 0x4e3c0d1d
access-list outside line 2 extended permit tcp host 2.2.2.2 host 10.10.10.5 eq 3051 (hitcnt=0) 0xfeb14ea6
access-list outside line 2 extended permit tcp 192.168.1.0 255.255.255.0 host 10.10.10.5 eq 3051 (hitcnt=0) 0xfafda7ae
access-list outside line 2 extended permit tcp host 3.3.3.3 host 10.10.10.5 eq 3051 (hitcnt=10) 0xaed11ed5
Assuming that the input is text that must therefore be parsed (and that you have no way to request a structured text format at the source), you can use a switch statement:
& {
$addresses = $null
switch -regex ($lines) {
'(?<= object-group )\w+' {
if ($addresses) {
(, $user + $addresses) -join ','
}
$user = $Matches[0]
$addresses = [System.Collections.Generic.List[string]] #()
continue
}
'(?<= tcp host )\S+' { $addresses.Add($Matches[0]); continue }
'(?<= tcp )\S+ \S+' { $addresses.Add($Matches[0]) }
}
if ($addresses) {
(, $user + $addresses) -join ','
}
}
Output with your sample input:
Jerry,192.168.1.1,192.168.1.2,192.168.1.3,192.168.1.4
Jason,2.2.2.2,192.168.1.0 255.255.255.0,3.3.3.3
Note that if you want to write the resulting lines to a CSV file, you'll have to prepend a header row that gives each column a distinct name. For that, you'll at least have to know the maximum number of addresses across all rows, and the rows may have different numbers of fields filled in.
Therefore, a better way to structure your CSV is to normalize it and to write your data as name-address pairs, which also simplifies the code:
& {
switch -regex ($lines) {
'(?<= object-group )\w+' { $user = $Matches[0]; continue }
'(?<= tcp host )\S+' { [pscustomobject] #{ Name = $user; Address = $Matches[0] }; continue }
'(?<= tcp )\S+ \S+' { [pscustomobject] #{ Name = $user; Address = $Matches[0] } }
}
} | ConvertTo-Csv
Output:
"Name","Address"
"Jerry","192.168.1.1"
"Jerry","192.168.1.2"
"Jerry","192.168.1.3"
"Jerry","192.168.1.4"
"Jason","2.2.2.2"
"Jason","192.168.1.0 255.255.255.0"
"Jason","3.3.3.3"
Related
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!
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
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
I am trying to create a PowerShell script (Target Level OS 2008 R2) that 1.
Runs through a array of ports
List all firewall policy associated with the ports
Capture the "Rule Names" into a array currently stuck here
Run through each "Rule Name", either disable or enable the policy based on current state.
I am stuck at point 3 of my list above. Is anyone able to help or possibly direct me in the correct direction?
Current Code:
$array = #("3050", "300", "8080","7080","5090")
for ($i=0; $i -lt $array.length; $i++) {
$searchPort = "(LocalPort.*" + $array[$i] + ")"
$front = netsh advfirewall firewall show rule dir=in name=all |
Select-String -Pattern ($searchPort) -Context 9,4
Write-Host $front
}
Copy of result based on my current script:
Rule Name: interbase port
----------------------------------------------------------------------
Enabled: Yes
Direction: In
Profiles: Domain,Private,Public
Grouping:
LocalIP: Any
RemoteIP: Any
Protocol: TCP
LocalPort: 3050
RemotePort: Any
Edge traversal: No
Action: Allow
Rule Name: MT
----------------------------------------------------------------------
Enabled: Yes
Direction: In
Profiles: Domain,Private,Public
Grouping:
LocalIP: Any
RemoteIP: Any
Protocol: UDP
LocalPort: 300
RemotePort: Any
Edge traversal: No
Action: Allow
Rule Name: medtech port
----------------------------------------------------------------------
Enabled: Yes
Direction: In
Profiles: Domain,Private,Public
Grouping:
LocalIP: Any
RemoteIP: Any
Protocol: UDP
LocalPort: 300
RemotePort: Any
Edge traversal: No
Action: Allow
Simply extract the rule name from the pre-context of your match. Since you probably want to work with several elements from the pre- and post-context I'd recommend piping the output of Select-String into ForEach-Object instead of collecting it in a variable. Then you can toggle firewall rules e.g. like this:
$toggle = #{
'yes' = 'no'
'no' = 'yes'
}
netsh ... | Select-String -Pattern $searchPort -Context 9,4 | ForEach-Object {
$rule = $_.Context.PreContext[0] -replace 'rule name:\s*'
$enabled = $_.Context.PreContext[2] -replace 'enabled:\s*'
& netsh advfirewall firewall set rule name="$rule" new enable=$($toggle[$enabled])
}
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