<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Networking | TekCookie</title>
	<atom:link href="https://tekcookie.com/category/networking/feed/" rel="self" type="application/rss+xml" />
	<link>https://tekcookie.com</link>
	<description>Everything about IT</description>
	<lastBuildDate>Wed, 06 Oct 2021 17:59:40 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://i0.wp.com/tekcookie.com/wp-content/uploads/2021/06/cropped-TekCookie-211.png?fit=32%2C17&#038;ssl=1</url>
	<title>Networking | TekCookie</title>
	<link>https://tekcookie.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">174510684</site>	<item>
		<title>Simple IP Scanner</title>
		<link>https://tekcookie.com/ip-scanner/</link>
					<comments>https://tekcookie.com/ip-scanner/#respond</comments>
		
		<dc:creator><![CDATA[jeffythampi]]></dc:creator>
		<pubDate>Tue, 07 Apr 2020 13:03:26 +0000</pubDate>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[IP Scanner]]></category>
		<category><![CDATA[IP Scanner using Powershell]]></category>
		<category><![CDATA[Simple IP Scanner]]></category>
		<guid isPermaLink="false">https://tekcookie.com/?p=633</guid>

					<description><![CDATA[Like in the heading, this is a very simple IP scanner for scanning small networks using ICMP. This post is not just for a simple IP scanner, But demonstrates sequential and parallel code execution. This script can be used to ping ip range from 1 to 254 Result: Above script does the job sequentially and [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Like in the heading, this is a very simple IP scanner for scanning small networks using ICMP.</p>



<p>This post is not just for a simple IP scanner, But demonstrates sequential and parallel code execution.</p>



<p>This script can be used to ping ip range from 1 to 254</p>



<pre class="wp-block-code"><code lang="powershell" class="language-powershell line-numbers">$networkSegment = "192.168.1."
$startIP = 1
$endIP = 20
#To ping from 192.168.1.1 to 192.168.1.20

$scanResult = @()

$startIP..$endIP | ForEach-Object {
    Write-Progress -Activity "PINGING $networkSegment$_" -Status "Progress:" -PercentComplete ($_/$endIP*100)
    if(Test-Connection "$networkSegment$_" -Count 1 -ErrorAction SilentlyContinue)
    {
        $pingResult = New-Object -TypeName PSObject -Property @{
            IP = "$networkSegment$_"
            Status = "ACTIVE"
        }
    }
    else
    {
        $pingResult = New-Object -TypeName PSObject -Property @{
            IP = "$networkSegment$_"
            Status = "INACTIVE"
        }
    }
    $scanResult += $pingResult
}
$scanResult</code></pre>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<p>Result:</p>
</div></div>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/Pinging.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-636"/></figure>



<p>Above script does the job sequentially and thereby increases the execution time. Below is another code which does the ping parallelly</p>



<p>Powershell workflow is used to for parallel execution. In workflow, foreach -parallel loop is available. For new version of powershell, I.e. PowerShell 7, -parallel parameter is available.</p>



<pre class="wp-block-code"><code lang="powershell" class="language-powershell line-numbers">#Workflow definition
workflow Start-Scan
{
    Param
    (
        # Start IP
        [int]
        $startIP,

        # End IP
        [int]
        $endIP,

        #Network Info
        [string]
        $networkSegment
    )

    $sequence = $startIP..$endIP

    #limiting the parallel task to 8 at a time
    foreach -parallel -throttlelimit 8 ($item in $sequence)
    {
        
        if(Test-Connection "$networkSegment$item" -Count 1 -ErrorAction SilentlyContinue)
        {
            $pingResult = New-Object -TypeName PSObject -Property @{
                IP = "$networkSegment$item"
                Status = "ACTIVE"
            }
        }
        else
        {
            $pingResult = New-Object -TypeName PSObject -Property @{
                IP = "$networkSegment$item"
                Status = "INACTIVE"
            }
        }
        $pingResult
    }
}
#End of Workflow definition

#invoking the workflow
#To ping from 192.168.1.1 to 192.168.1.20

$result = Start-Scan 1 254 "192.168.1."
$result | Select IP, Status</code></pre>



<p>Result:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/Pinging-parallel.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-638"/></figure>



<p>As expected, the result of the parallel execution is not in the order. But the script executed faster.</p>



<div style="height:70px" aria-hidden="true" class="wp-block-spacer"></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Thank you for reading my post. Hope this is helpful to you.</p></blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://tekcookie.com/ip-scanner/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">633</post-id>	</item>
		<item>
		<title>Automate Configuration backup and Inventory of Network Devices</title>
		<link>https://tekcookie.com/network-devices-config-backup/</link>
					<comments>https://tekcookie.com/network-devices-config-backup/#comments</comments>
		
		<dc:creator><![CDATA[jeffythampi]]></dc:creator>
		<pubDate>Wed, 01 Apr 2020 06:00:00 +0000</pubDate>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Cisco Switch backup]]></category>
		<category><![CDATA[Cisco Switch Inventory]]></category>
		<category><![CDATA[Powershell parallel]]></category>
		<category><![CDATA[powershell parallel execution]]></category>
		<category><![CDATA[powershell runspace]]></category>
		<guid isPermaLink="false">https://tekcookie.com/?p=368</guid>

					<description><![CDATA[This article demonstrates how to fetch information from network devices. The Powershell code will telnet to the network switches and fetch the device information. Also, it performs configuration backup. I have posted another article to get network device configuration backup using python (Click here to view the article) which is in a sequential way. This [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-text-align-justify">This article demonstrates how to fetch information from network devices. The Powershell code will telnet to the network switches and fetch the device information. Also, it performs configuration backup. </p>



<p class="has-text-align-justify">I have posted another article to get network device configuration backup using python (<a href="https://tekcookie.com/automate-cisco-switch-backup-using-python/"><span class="has-inline-color has-vivid-cyan-blue-color">Click here to view the article</span></a>) which is in a sequential way. This post describes the use of parallel processing and Telnet.</p>



<p>SSH is another way to backup the network device. Please have a look at F5 backup article @ <a rel="noreferrer noopener" href="https://tekcookie.com/automate-f5-backup-with-powershell/" target="_blank"><span class="has-inline-color has-vivid-cyan-blue-color">Automate-F5-Backup</span></a>.</p>



<div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="has-text-align-left wp-block-heading">Automate Cisco Switch Configuration backup and Inventory</h2>



<h4 class="wp-block-heading"><strong>Use Case:  Fetch Network Switch information using Powershell</strong></h4>



<p class="has-text-align-justify"><strong>Mail from CIO:</strong> There has been an incident where our inventory database is corrupted and the backup data is unreadable. We need to find all the network switch details which is required for auditing. Please make it ready ASAP!</p>



<p class="has-text-align-justify"><strong>Solution</strong>: As the management interface is configured for all the devices, we can telnet or ssh to the switch and fetch the information. As the number of switches is quite high, we will automate the task with PowerShell. </p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Apart from usual scripting technique, because the task can be executed independent of the devices. We have introduce parallel task which drastically reduce the execution time.</p></blockquote>



<p>For parallel execution, we are using runspace. I have used the foreach-parallel code from <a href="https://powertoe.wordpress.com/2012/05/03/foreach-parallel/" target="_blank" rel="noopener"><span class="has-inline-color has-vivid-cyan-blue-color">https://powertoe.wordpress.com/2012/05/03/foreach-parallel/</span></a></p>



<p>To telnet to the switches, we are using the Get-Telnet function from <a href="https://community.spiceworks.com/scripts/show/1887-get-telnet-telnet-to-a-device-and-issue-commands" target="_blank" rel="noopener"><span class="has-inline-color has-vivid-cyan-blue-color">https://community.spiceworks.com/scripts/show/1887-get-telnet-telnet-to-a-device-and-issue-commands</span></a>. I have tested it with Cisco switches and it works perfectly.</p>



<pre class="wp-block-code"><code lang="powershell" class="language-powershell line-numbers">#Creating folder where the configuration backup and inventory file will be saved
#Running the script will create a folder Script in C drive if it is not available
if(!(Get-Item C:\Script -ErrorAction SilentlyContinue)){
    New-Item -Path C:\ -Name Script -ItemType Directory
}
if(!(Get-Item C:\Script\SWBKP -ErrorAction SilentlyContinue)){
    New-Item -Path C:\Script -Name SWBKP -ItemType Directory
}


#Class SwitchSpec definition - To save the switch information
Class SwitchSpec {

    [string]$Serial
    [string]$Model
    [string]$DeviceIP
    #To sort the result based on 4th octet of IP address
	[int]$IPNo
	
    SwitchSpec() {
        $this.Serial = ""
        $this.Model = ""
        $this.DeviceIP = ""
        $this.IPNo = ""
    }

    readInfo($FileName) {
        $Contents = Get-Content $FileName
		
        foreach($content in $Contents) {
            if($content.ToUpper() -like "*SYSTEM SERIAL NUMBER*" -and $content.ToUpper() -notlike "*| INC SYSTEM SERIAL NUMBER*" ) {
                $this.Serial = $content.Split(':')[1].trim()
            }
            if($content.ToUpper() -like "*MODEL NUMBER*" -and $content.ToUpper() -notlike "*| INC MODEL NUMBER*" ) {
                $this.Model = $content.Split(":")[1].trim()
            }
            $this.DeviceIP = $FileName.Split('_')[0].split('\')[-1]
            $this.IPNo = [int]$this.DeviceIP.Split('.')[-1]
        }
    }
}


### ForEach-Parallel Code###
function ForEach-Parallel {
    param(
        [Parameter(Mandatory=$true,position=0)]
        [System.Management.Automation.ScriptBlock] $ScriptBlock,
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [PSObject]$InputObject,
        [Parameter(Mandatory=$false)]
        [int]$MaxThreads=10
    )
    BEGIN {
        $iss = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
        $pool = [Runspacefactory]::CreateRunspacePool(1, $maxthreads, $iss, $host)
        $pool.open()
        $threads = @()
        $ScriptBlock = $ExecutionContext.InvokeCommand.NewScriptBlock("param(`$_)`r`n" + $Scriptblock.ToString())
    }
    PROCESS {
        $powershell = [powershell]::Create().addscript($scriptblock).addargument($InputObject)
        $powershell.runspacepool=$pool
        $threads+= @{
            instance = $powershell
            handle = $powershell.begininvoke()
        }
    }
    END {
        $notdone = $true
        while ($notdone) {
            $notdone = $false
            for ($i=0; $i -lt $threads.count; $i++) {
                $thread = $threads[$i]
                if ($thread) {
                    if ($thread.handle.iscompleted) {
                        $thread.instance.endinvoke($thread.handle)
                        $thread.instance.dispose()
                        $threads[$i] = $null
                    }
                    else {
                        $notdone = $true
                    }
                }
            }
        }
    }
}
### End of ForEach-Parallel Code###


#Fetching the Switch IP, UserName and Password from CSV file - the file format is added at the end of this article
$SwitchIP = Get-Content "C:\Script\SwitchIPDetails.csv" | ConvertFrom-Csv

$SwitchIP | ForEach-Parallel { 

	#Assigning each devices IP, username and password to variable
	$IP = $_.deviceIp
	$U = $_.userName
	$P = $_.password


	$__DateTime = Get-Date
	$FilePath = "C:\Script\SWBKP\" + $IP + "_Backup_$($__DateTime.Day)_$($__DateTime.Month)_$($__DateTime.Year).txt"

	#As the telnet is initiated inside the parallel runspace, we have to define the Get-telnet function inside foreach-parallel script block
	#I have removed the help metadata to minimize the code. Please refer to the original post for full information
	Function Get-Telnet
	{   Param (
			[Parameter(ValueFromPipeline=$true)]
			[String[]]$Commands = @("username","password","disable clipaging","sh run"),
			[string]$RemoteHost = "HostnameOrIPAddress",
			[string]$Port = "23",
			[int]$WaitTime = 1000,
			[string]$OutputPath = "C:\Script\SwitchInfos.cs"
		)
		#Attach to the remote device, setup streaming requirements
		$Socket = New-Object System.Net.Sockets.TcpClient($RemoteHost, $Port)
		If ($Socket)
		{   $Stream = $Socket.GetStream()
			$Writer = New-Object System.IO.StreamWriter($Stream)
			$Buffer = New-Object System.Byte[] 1024 
			$Encoding = New-Object System.Text.AsciiEncoding

			#Now start issuing the commands
			ForEach ($Command in $Commands)
			{   $Writer.WriteLine($Command) 
				$Writer.Flush()
				Start-Sleep -Milliseconds $WaitTime
			}
			#All commands issued, but since the last command is usually going to be
			#the longest let's wait a little longer for it to finish
			Start-Sleep -Milliseconds ($WaitTime * 4)
			$Result = ""
			#Save all the results
			While($Stream.DataAvailable) 
			{   $Read = $Stream.Read($Buffer, 0, 1024) 
				$Result += ($Encoding.GetString($Buffer, 0, $Read))
			}
		}
		Else     
		{   
			$Result = "Unable to connect to host: $($RemoteHost):$Port"
		}
		#Done, now save the results to a file
		$Result | Out-File $OutputPath
	}



	#This will telnet to the switches and initiate the following switch commands
	#terminal length 0 								---- Set terminal length to zero
	#sh run | inc ip address							---- 
	#sh version | inc System [Ss]erial [Nn]umber
	#sh version | include Model [Nn]umber
	#sh vtp status
	#sh run
	
	Get-Telnet -RemoteHost $IP -Commands $U,$P,"terminal length 0","sh version | inc System [Ss]erial [Nn]umber","sh version | include Model [Nn]umber","sh vtp status","sh run" -OutputPath $FilePath -WaitTime 1000

}




#Defining a list of type class which is defined at the top of this code
$SwitchInfoList = New-Object Collections.Generic.List[SwitchSpec]

#Read all configuration files created by Get-Telnet function
$files = Get-childitem C:\Script\SWBKP\
$files | % {

$objSwitchInfo = New-Object ([SwitchSpec]::new())
$objSwitchInfo.readInfo($_.FullName)
$SwitchInfoList.Add($objSwitchInfo)
}

$SwitchInfoList | select DeviceIP, Serial, Model, IPNo | Sort-Object IPNo | Export-Csv C:\Script\SwitchInfos.csv -NoTypeInformation</code></pre>



<p>Finally we have the device information @ C:\Script\SwitchInfos.csv and configurations @ C:\Script\SWBKP\192.168.1.1_Backup_27_2_2020.txt</p>



<p>The input file &#8220;C:\Script\SwitchIPDetails.csv&#8221; should have details such as IP Address, Username, and Password as shown below.</p>



<pre class="wp-block-code"><code class="">deviceIp,userName,password
10.0.0.1,admin,complexpassword
10.0.0.2,admin,complexpassword2</code></pre>



<div style="height:70px" aria-hidden="true" class="wp-block-spacer"></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Thank you for reading my post. Hope it is helpful for you.</p></blockquote>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://tekcookie.com/network-devices-config-backup/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">499</post-id>	</item>
		<item>
		<title>Automate Cisco switch backup using Python</title>
		<link>https://tekcookie.com/automate-cisco-switch-backup-using-python/</link>
					<comments>https://tekcookie.com/automate-cisco-switch-backup-using-python/#respond</comments>
		
		<dc:creator><![CDATA[jeffythampi]]></dc:creator>
		<pubDate>Sun, 30 Jun 2019 13:15:54 +0000</pubDate>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Cisco switch backup using Python]]></category>
		<category><![CDATA[Cisco switch backup with Python]]></category>
		<category><![CDATA[switch backup using Python]]></category>
		<category><![CDATA[telnet using python]]></category>
		<guid isPermaLink="false">https://adminscripter.wordpress.com/?p=126</guid>

					<description><![CDATA[This python script reads the device information from a csv file and fetches its configuration via telnet session and save to specified location. CSV Template: deviceIp,userName,password 192.168.1.1,admin,secretpwd 192.168.1.2,admin,secretpwd2 The script initiates telnet session with the device along with userId and password to login into enable mode and executes &#8220;show run&#8221; command to fetch the configuration [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>This python script reads the device information from a csv file and fetches its configuration via telnet session and save to specified location.</p>



<p>CSV Template:</p>



<pre class="wp-block-preformatted"><strong>deviceIp,userName,password</strong> 
192.168.1.1,admin,secretpwd 
192.168.1.2,admin,secretpwd2</pre>



<p>The script initiates telnet session with the device along with userId and password to login into enable mode and executes &#8220;show run&#8221; command to fetch the configuration</p>



<hr class="wp-block-separator"/>



<h3 class="wp-block-heading">Python code to fetch switch configuration:</h3>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import telnetlib as tel
import csv
import datetime
import os


#Declaration
#path of the csv file
#deviceFilePath = "D:/Script/DeviceIp.csv"
#path to save the backup files
#directoryLocation = "D:/Script/"


#Methods
###This method initiate telnet connection to devices
def Initiate_Telnet(indexCount, hostIP, userId, passwd, directoryLocation):
    commands_ShowConfig = "sh run"
    commands_terminalLength = "terminal length 0"
    response = os.system("ping -n 1 -w 700 " + hostIP)
    if response == 0:
        try:
            #connecting to host device
            telConnection = tel.Telnet(hostIP, timeout=2)

            #sending username value and password value
            uName = telConnection.read_until('Username:'.encode('utf-8'), timeout=5)
            telConnection.write(userId.encode('utf-8') + b"\n")
            uPass = telConnection.read_until('Password:'.encode('utf-8'), timeout=5)
            telConnection.write(passwd.encode('utf-8') + b"\n")

            #checking for "#"
            telConnection.write(b"\n")
            mode = telConnection.read_until('#'.encode('utf-8'), timeout=5)
            #x = b' \r\nBZPDAMG0204#'
            mode = str(mode.decode('utf-8'))

            if(mode[-1] == "#"):
                #sending terminal length command to get full configuration
                telConnection.write(commands_terminalLength.encode('utf-8') + b"\n")
                telConnection.write(commands_ShowConfig.encode('utf-8') + b"\n")
            elif(mode[-1] == ":"):
                outputData = b"Password Wrong"
            elif(mode[-1] == "&gt;"):
                outputData = b"Not Enable Mode"


            #sending terminal length command to get full configuration
            #telConnection.write(commands_terminalLength.encode('utf-8') + b"\n")
            #telConnection.write(commands_ShowConfig.encode('utf-8') + b"\n")

            #read till end, so passing a string which may not appear in the configuration
            outputData = telConnection.read_until('stringNotInConfiguration'.encode('utf-8'), timeout=5)

            #close telnet connection
            telConnection.close()
        except:
            outputData = b"telnet not available"
    else:
        outputData = b"Host not pinging"

    #exporting the data to text file and close file
    Write_Info_toFile(directoryLocation, hostIP, outputData)

    return (indexCount, hostIP)
#end Initiate_Telnet


###This method writes info to file
def Write_Info_toFile(directory, fileName, dataString):
    datestring = datetime.datetime.now()
    datestring = str(datestring).replace(':','_').replace('-','_').replace(' ','__').split('.')[0]
    
    #exporting the data to text file and close file
    dataString = dataString.decode('utf-8')
    
    #validation
    if(dataString == "telnet not available"):
        text_file = open(directory + "Log_backup_.txt", "a+")
        dataString = fileName + " " + dataString + "\n"
    elif(dataString == "Host not pinging"):
        text_file = open(directory + "Log_backup_.txt", "a+")
        dataString = fileName + " " + dataString + "\n"
    elif(dataString == ""):
        text_file = open(directory + "Log_backup_.txt", "a+")
        dataString = fileName + " Login Failed" + "\n"
    else:
        text_file = open(directory + fileName + "_backup_" + datestring + ".txt", "w")

    text_file.write(dataString)
    text_file.close()
#end Write_Info_toFile

#start function
def Start_Telnet(deviceFilePath = "D:/Script/DeviceIp.csv", directoryLocation = "D:/Script/"):
    with open(deviceFilePath) as csvDeviceDetails:
        csdData = csv.reader(csvDeviceDetails, delimiter=',')
        #print(csdData)
        lineCount = 0
        for (ipAddress, userName, password) in csdData:
            if(lineCount == 0):
                #First entry is heading
                lineCount += 1
            else:
                lineCount += 1
                Initiate_Telnet(0, ipAddress, userName, password, directoryLocation)

Start_Telnet("D:/Script/DeviceIp.csv", "D:/Script/")</code></pre>



<p>Note: This works for switches which has login to &#8220;enable mode&#8221;, for other modes, extra conditions has to be added.</p>



<div style="height:70px" aria-hidden="true" class="wp-block-spacer"></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Hope you liked this article and thank you for reading</p></blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://tekcookie.com/automate-cisco-switch-backup-using-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">126</post-id>	</item>
	</channel>
</rss>
