Through the ports on the equipment to the user machines

Good time of day, Gabriele.

This post tells You about how to use PowerShell again we will be able to make our lives easier and to automate the search for equipment and ports, which sit on users ' computers. This is necessary in the moment when you have to traverse vlan's (or just for information).
"

Background

It all started about a year ago. One day, our senior administrator suggested that I try to write a script on the subject. Scratching the pumpkin, I agreed to try. I have never worked with networking equipment (well, home router doesn't count), so he sent me was a sample sequence of commands with which all this can be done.

Using Putty, I tried to do it all manually, it worked and I began to think how to automate. And not just to automate, but to do it with PowerShell. Why PoSh? While I really like (although I still never want to get off), it was possible to do it in something else, but I badly wanted to do it through PoSh.

So how to connect to the equipment needed via Telnet and SSH (mainly via Telnet, as at the time SSH was not everywhere, but more on that later) I spent a lot of time on the Internet to see how PowerShell can work with these protocols.
Then I turned to the 2 mechanisms of connection:
    the
  1. using plink.exe (from Putty)
  2. the
  3. Netcmdlets company /n software

Using mainly plink.exe I got something that was hardly a work of art. It was huge, piled up a script that absolutely no one wanted to show. And even more so to write an article about it here.
And since it worked (occasionally, I even enjoy them), I put optimization on the back burner and do other things.

As time passed, many things have changed, but about their offspring I don't forget, periodically attempting to rewrite it again, and to get rid of a bunch of unnecessary things. Finally I did it!

Vader, rise!

The most important incident was that updated the firmware of the switches, and it is now possible to connect to them via SSH. Well, fine, then hammered on telnet.
This was followed by 1 more change: once telnet is no longer needed, we can use plink.exe (from Putty) and all the glory goes to NetCmdlets.
Not enough after talking with the tech support from this company, I finally understood the function of these tools, and began work.

What I needed:
    the
  1. Check correctness of the IP address of the computer
  2. the
  3. Check the computer on the network
  4. the
  5. to connect to each equipment in sequence, starting with the most important, and find out which ports hanging our device
  6. the
  7. to Show it all to the user that he (i.e. I) is satisfied

NetCmdlets

So I want to thank the people who made them, a small retreat and pair words about these cmdlets:
To read about them and download them here. You can download it as trial version (30 days) and full ($100). I used the trial version, because after the end of the term, simply be reinstalled.
Recently online powershellmagazine.com heard these cmdlets for free, I managed to capture. So be on the alert! But back to our sheep.
Selecting a set of these cmdletов, I began to study them. This set is large enough, so I'm not going to describe everything that is there. stop 2:
the
    the
  • Connect-SSh
  • the
  • Invoke-SSh

You can only do Invoke-SSh but then you will not have permanent session with the device (i.e., for example, to run the command "conf t" on the device already will be). This cmdlet Connect-we create a SSh connection to the device, and Invoke-SSh command in progress. Everything is quite simple.

Parsing the output, and regular expressions

I was expecting a very romantic parsing the output of shell of Cisco iOS, because the Invoke-SSH displays the output in the Text column, i.e. passing a variable output, we receive a text.
Here we come to the aid of regular expressions. But who was being parsed large text, knows that to get the fragment out is not easy, but thanks to PowerShell, we brilliantly out of this situation.
At the moment, read PowerShell in Action 2nd Edition. Someone who is studying PoSh, I highly recommend this book. And in it I read about such things as named regexp. The point is that when PowerShell has a variable $Mathces that records all matches when using regular expressions:

the
PS [13] > $Matches
PS [14] > $a="123 saa ass"
PS [15] > $a-match "\d+"
True
PS [16] > $Matches

Name Value 
---- ----- 
0 123 

But that's not all! The whole bun is that if we add
? in our expression, we get the following:
PS [17] > $a -match "(?<Numbers>\d+)" True PS [18] > $Matches Name Value ---- ----- Numbers 123 0 123 PS [19] > $Matches.Numbers 123

Thus we can apply directly the results of matches and to bypass the parsing of such a wonderful thing (R burner split!). I don't know about you, but for me it was a discovery (for example, on Russian resources for PowerShell nothing about this) that I was ready to scream like a schoolgirl.
Interestingly, in other languages is there?

the script

Actually, the script itself.
the
## output Function information on end equipment
Function LastSwitch
{
"IP address switch: {0}, port {1}" -f $IpSwitch,$Port
If ($CiscoPhone) {"Computer connected via a Cisco IP Phone"}
Read-Host "Press Enter for continue..."
break 
}
##Check the correctness of
For (;;)
{
$ip=Read-host "Enter ip"
If ($ip -match "(\d{1,3}\.){3}\d{1,3}") {break}
else {Write-Warning "Invalid IP address! Try again..."}
}
##Check for the presence of a computer in a network
if ((test-connection $ip -quiet) -ne "True") 
{
Write-Warning "Computer not online!"
Read-Host "Press Enter to continue..."
break
}
$cred = get-credential Admin ##Account to connect to devices
$IpSwitch = "10.138.30.1" ##the Founder of our switches
$MAC = $null
$CiscoPhone = $false
For (;;)
{
$conn = Connect-ssh -Server $IpSwitch -Credential $cred-ShellPrompt "#" -Force
Invoke-SSH -Connection $conn -Command "terminal length 0" | out-null
Invoke-SSH -Connection $conn -Command "ping $ip" | out-null
If (!$MAC)
{
## Get the MAC address of the device
((Invoke-SSH -Connection $conn -Command "sh arp | i $ip ").text | 
Where-Object {$_ -match "\w"}) -match "(?<MAC>\w{4}\.\w{4}\.\w{4})" | out-null
$MAC = $Matches.MAC
}
## Find the port on which the hanging equipment
(((Invoke-SSH -Connection $conn -Command "sh mac address-table address $MAC").Text | 
where-object {$_ -match $mac}) | 
Select-Object -First 1) -match "(?<port>((\D{2}\d{1,3})/|Po)(\d{1,3})(/\d{1,3})?)" | out-null
$port = $Matches.Port
## Check the number of equipment connected to the port
$portInfo = (Invoke-SSH -Connection $conn -Command "show mac address-table interface $port").Text | 
where-object {$_ -match $port}
If (($portInfo | measure).Count-eq 1) {LastSwitch}
## Information about the port
$DetailPortInfo = (Invoke-SSH -Connection $conn -Command "sh cdp neighbors $port detail" -Force).Text
##  If  information about the port is the entry "Cisco IP phone", the computer is connected cases the IP phone.
If ($DetailPortInfo -match "Cisco IP phone") {$CiscoPhone = $true; LastSwitch}
(($DetailPortInfo | where-object {$_ -match "IP address: (\d{1,3}\.){3}\d{1,3}"}) | 
Select-Object -First 1) -match "(?<ip>(\d{1,3}\.){3}\d{1,3})" | out-null
"IP address switch: {0}, port {1}" -f $IpSwitch,$Port
$IpSwitch = $Matches.IP
Disconnect-SSH $conn
}

A few comments:
the
    the
  • Credentials we obtained using Get-Credential. Too lazy to enter it every time the credentials can be done automatically by placing an encrypted password in a text file. More information can be read here
  • the
  • In our switches is a limit to the output for 1 time (i.e. flipping can with a space (analogy from PowerShell: get-help | more)). We do not like, because the Invoke-SSH is not able to scroll, and in the end we will get the error. To solve this problem, we disable it for the session using the command terminal length 0
  • the
  • ((\D{2}\d{1,3})/|Po)(\d{1,3})(/\d{1,3})?- a regular expression designed us to find ports. All it gets are ports: Fa5, Gi0/2, Te2/0/8, Po255, etc. (if you suddenly forgot something, email me and I will fix)
  • the
  • because we do not want to output unnecessary information (from the Invoke-SSH), this conclusion is we all sent to nowhere (out-null)
Article based on information from habrahabr.ru

Комментарии

Популярные сообщения из этого блога

Address FIAS in the PostgreSQL environment. Part 4. EPILOGUE

PostgreSQL: Analytics for DBA

Audit Active Directory tools with Powershell releases. Part 1