Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## PowerShell: Script To Telnet To Remote Hosts And Run Commands Against Them With Output To A File ##
- ## Overview: Useful for Telnet connections to Cisco Switches and other devices. Can add additional command strings
- ## Usage Examples: Add your environment specific details into the parameters below, or include when calling the script:
- ## ./Auth-Telnet.ps1 "127.0.0.1" "23" "admin" "password"
- param(
- [string] $remoteHost = "10.64.80.15",
- [int] $port = 23,
- [string] $username = "****",
- [string] $password = "****",
- [int] $commandDelay = 1000
- )
- [string] $output = ""
- ## Read output from a remote host
- function GetOutput
- {
- ## Create a buffer to receive the response
- $buffer = new-object System.Byte[] 1024
- $encoding = new-object System.Text.AsciiEncoding
- $outputBuffer = ""
- $foundMore = $false
- ## Read all the data available from the stream, writing it to the
- ## output buffer when done.
- do {
- ## Allow data to buffer for a bit
- start-sleep -m $commandDelay
- ## Read what data is available
- $foundMore = $false
- $stream.ReadTimeout = $commandDelay
- do {
- try {
- $read = $stream.Read($buffer, 0, 1024)
- if ($read -gt 0) {
- $foundMore = $true
- $outputBuffer += ($encoding.GetString($buffer, 0, $read))
- }
- } catch { $foundMore = $false; $read = 0 }
- } while ($read -gt 0)
- } while ($foundMore)
- $outputBuffer
- }
- function Main
- {
- do {
- ## Open the socket, and connect to the computer on the specified port
- Write-Host "Connecting to $remoteHost on port $port"
- trap { Write-Error "Could not connect to remote computer: $_"; exit }
- $socket = New-Object System.Net.Sockets.TcpClient($remoteHost, $port)
- # Write-Host "Connected. Press ^D followed by [ENTER] to exit.`n"
- Write-Host "Connected.`n"
- $stream = $socket.GetStream()
- $writer = New-Object System.IO.StreamWriter $stream
- ## Receive the output that has buffered so far
- while (-not (GetOutput -match "Username:")) { sleep 1 }
- $writer.WriteLine($username)
- $writer.Flush()
- while (-not (GetOutput -match "Password:")) { sleep 1 }
- $writer.WriteLine($password)
- $writer.Flush()
- $SCRIPT:output += GetOutput
- ## Close the streams
- $writer.Close()
- $stream.Close()
- $output
- $output | Out-File ".\$remoteHost.txt" #Change this to suit your environment
- } until ($SCRIPT:output -match "Authentication Successful")
- }
- Main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement