Today I want to build an PowerShell script for a customer that will connect via Telnet to a switch or a firewall to run some commands and log the output. The next step is to be able to schedule this script to run at the beginning and at the end of the working day. The environment for this task is PowerShell 2.0 and RES ONE Automation 2015.
After some Internet searching I found an Get-Telnet PowerShell function that can do what I want. It will connect to the switch, and I can place the commands I want to run in an array or in a text file. I altered the script slightly to meet my needs. I only use the function because I run the script from within RES One Automation.
Function Get-Telnet { Param ( [Parameter(ValueFromPipeline=$true)] [String[]]$Commands = @("username","password","disable clipaging","sh config"), [string]$RemoteHost = "IPAddress", [string]$Port = "23", [int]$WaitTime = 1000, [string]$OutputPath = "C:\Temp\get-telnet.txt" ) #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 } Get-Telnet -Commands (get-content "$[CmdList]") -RemoteHost "$[Host]" -OutputPath "c:\temp\get-telnet.txt" -WaitTime 1500
I have configured the script to place the output of the commands to a text file in the temp folder of the target device where the script is deployed. The RES ONE Automation job that runs the script is configured to grab the log file and placed it with the other job results in the RES ONE Automation console.
When you schedule this job you can see an orange exclamation mark on the tab Job Parameters, this is there because I configured Module Parameters so this Job can be re-used for other purposes.
When you click on the Job Parameters tab you’ll see the above screen.
Here you can enter the variable data, where you have stored your commando list and to what host you are going to connect to. The first two lines of the commando list should be the username and password as you can see in the picture below.