PowerShell and Telnet Integration Outputs Junk Chars - powershell

I have tried to get PowerShell automation for Telnet connecting to Windows Server 2012 R2, Ubuntu 16.04 and Windows XP SP3 and all servers are throwing junk characters as output.
I was going through rfc854 but I could not get this done.
Could you please help me on how to resolve this issue.
Below code would try to connect Telnet server with credentials and output dir list.
Code
param (
[string] $terminalServer = "192.168.19.131",
[int] $port = 23,
[string] $username = "username",
[string] $password = "password",
[int] $commandDelay = 1000,
[string] $output = ""
)
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 1000
## Read what data is available
$foundmore = $false
$stream.ReadTimeout = 2000
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
}
$output = ""
write-host "Connecting to $terminalServer on port $port..."
trap { Write-Error "Could not connect to the server: $_"; exit }
$socket = new-object System.Net.Sockets.TcpClient($terminalServer, $port)
write-host "Connected. `n"
$stream = $socket.GetStream()
$writer = new-object System.IO.StreamWriter $stream
## Receive the output that has buffered so far
$SCRIPT:output += GetOutput
$writer.WriteLine($username)
$writer.Flush()
Start-Sleep -m $commandDelay
$SCRIPT:output += GetOutput
$writer.WriteLine($password)
$writer.Flush()
Start-Sleep -m $commandDelay
$SCRIPT:output += GetOutput
$writer.WriteLine("dir")
$writer.Flush()
Start-Sleep -m $commandDelay
$SCRIPT:output += GetOutput
$writer.WriteLine("exit")
$writer.Flush()
Start-Sleep -m $commandDelay
## Close the streams
$writer.Close()
$stream.Close()
write-host "All streams are closed. The final output is"
$output
Output
D:\Tools\T24\PowerShell>powershell .\telnet_test.ps1
Connecting to 192.168.19.131 on port 23...
Connected.
All streams are closed. The final output is
??%??????'???? ??

I have tried with jBASE Telnetd Server Version 4.1.1 on Windows Server 2012 R2 and perfectly listing directory.
So, with Windows version of Telnet requires some more manipulation as per rfc854 implementation.

Related

Powershell TCP client with error handling

I need help with a Powershell TCP client that can monitor when the server closes the connection. The starting point for this code is from here and looks like this:
## Connect-Computer.ps1
## Interact with a service on a remote TCP port
param(
[string] $remoteHost = "localhost",
[int] $port = 23
)
try
{
## Open the socket, and connect to the computer on the specified port
write-host "Connecting to $remoteHost on port $port"
$socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)
if($socket -eq $null) { return; }
$stream = $socket.GetStream()
$writer = new-object System.IO.StreamWriter($stream)
$buffer = new-object System.Byte[] 1024
$encoding = new-object System.Text.AsciiEncoding
while($true)
{
## Allow data to buffer for a bit
start-sleep -m 500
## Read all the data available from the stream, writing it to the
## screen when done.
while($stream.DataAvailable)
{
$read = $stream.Read($buffer, 0, 1024)
write-host -n ($encoding.GetString($buffer, 0, $read))
}
## Read the user's command, quitting if they hit ^D
$command = read-host
## Write their command to the remote host
$writer.WriteLine($command)
$writer.Flush()
}
}
finally
{
## Close the streams
$writer.Close()
$stream.Close()
}
The problem is when the server closes the port the client continues to wait. How can I use a buffered read but still check if the port is still open? I dont need to know immediately if the port closes, just after a few minutes.
Thanks in advance for any help.

Telnet with PowerShell

I use this powershell script for getting output stream of telnet request.
Function Get-Telnet {
Param (
[Parameter(ValueFromPipeline=$true)]
[string[]]$Commands = #(),
[string]$RemoteHost = "0.0.0.0",
[string]$Port = "23",
[int]$WaitTime = 1000,
[string]$OutputPath = "C:\temp\telnet_output.log"
)
#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
$Result
}
This works for a Cisco switch and a telnet server, but for the Alcatel OmniPCX and the HPUX the stream reading is empty.

How to Configure cisco router using POWERSHELL SSH.net?

Good, this is the code I'm using:
function escribe_log($dispositivo, $log, $comando){
$Fichero_Log = "C:\Modificacion_routers.log"
$texto = $dispositivo
$texto >> $Fichero_Log
$texto = $log
$texto >> $Fichero_Log
$texto = $comando
$texto >> $Fichero_Log
}
##PROGRAMA PRINCIPAL##
Import-Module SSH-Sessions
$ficheroIPS = "C:\ipsdispositivos.txt"
$ficheroComandos = "c:\comandos.txt"
$dispositivos = Get-Content $ficheroIPS
$comandos = Get-Content $ficheroComandos
foreach ($dispositivo in $dispositivos) {
New-SshSession -ComputerName $dispositivo -Username USUARIO -password PASSWORD
foreach ($comando in $comandos) {
$SshResults = Invoke-SshCommand -ComputerName $dispositivo -Command $comando
escribe_log $dispositivo $SshResults $comando
Start-Sleep -s 1
}
$comandos = Get-Content $ficheroComandos
}
Remove-sshSession -RemoveAll
Works perfectly to launch "sh" show commands, my problem is that when I launch a command automatically disconnects the session, then command is not possible to launch a "conf t" to enter configuration mode and then launch configuration commands.
Do you know if this library is possible to configure a router?
if that is not possible,
would they know me any alternative to configure the router using script?
SOLVED:
FUNCTION FOR CHANGES TO SSH ROUTER/SWITCH WITH POWERSHELL
Function set-SSH($devices, $ssh){
function ReadStream($reader)
{
$line = $reader.ReadLine();
while ($line -ne $null)
{
$line
$line = $reader.ReadLine()
}
}
function WriteStream($cmd, $writer, $stream)
{
$writer.WriteLine($cmd)
while ($stream.Length -eq 0)
{
start-sleep -milliseconds 1000
}
}
$stream = $ssh.CreateShellStream("dumb", 80, 24, 800, 600, 1024)
$reader = new-object System.IO.StreamReader($stream)
$writer = new-object System.IO.StreamWriter($stream)
$writer.AutoFlush = $true
while ($stream.Length -eq 0)
{
start-sleep -milliseconds 500
}
ReadStream $reader
foreach ($command in $commands) {
WriteStream $command $writer $stream
ReadStream $reader
Write-Host $reader
start-sleep -milliseconds 500
}
$stream.Dispose()
$ssh.Disconnect()
$ssh.Dispose()
}
There are three variables to initialize $commands, $ssh, $devices
#Example of file commands.txt...
#sh conf
#conf t
#int f0/1
#description Modify via powershell
#exit
#exit
#wr
#...
$fileCommands= ".\commands.txt"
$commands= Get-Content $fileCommands
#Example of file devices.csv...
#10.10.10.10;SWITCH01
#10.10.10.11;SWITCH02
#10.10.10.12;SWITCH03
#...
$devices = Import-Csv -path ".\devices.csv" -header 'ip','hostname' -delimiter ';'
$port = 22
$ssh = new-object Renci.SshNet.SshClient($devices[0].ip, $port, $user, $password)
Try{
$ssh.Connect()
Start-Sleep -s 1
set-SSH $commands $ssh
}catch{
}

Powershell v2.0 , unable to read the correct data from a tcpclient

I am very new to powershell programming,I have the following script, which reads from a socket stream as long as data is available, and then sends a "q" to exit the connection.
I am running this on win 2003 server std,Power shell V2.0.
When I execute the pgm, the output is the text from the pgm, which is reading and buffering.It almost looks like The following is the output:
Connecting to aardwolf.org on port 23
while($stream.DataAvailable)
{
$read = $stream.Read($buffer, 0, 1024)
write-Host $read
if($read -gt 0)
{
$outputBuffer += ($encoding.GetString($buffer, 0, $read))
}
}## Read the user's command, quitting if they hit
Following is the code:
# Interact with a service on a remote TCP port
param( [string] $remoteHost = "aardwolf.org",
[int] $port = 23 )
## Open the socket, and connect to the computer on the specified port
write-host "Connecting to $remoteHost on port $port"
$socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)
if($socket -eq $null) { return; }
$stream = $socket.GetStream()
$writer = new-object System.IO.StreamWriter($stream)
$buffer = new-object System.Byte[] 1024
$encoding = new-object System.Text.AsciiEncoding
while($true)
{
## Allow data to buffer for a bit
start-sleep -m 500
$outputBuffer = ""
## Read all the data available from the stream, writing it to the ## screen when done.
if($stream.CanRead)
{
while($stream.DataAvailable)
{
$read = $stream.Read($buffer, 0, 1024)
write-Host $read
if($read -gt 0)
{
$outputBuffer += ($encoding.GetString($buffer, 0, $read))
}
}## Read the user's command, quitting if they hit
}
write-Host $outputBUffer
$command = "q"
$writer.WriteLine($command)
$writer.Flush()
break
}
## Close the streams
if($writer -ne $null)
{
$writer.Close()
$stream.Close()
}
Need some help resolving the issue.

Automating Telnet with PowerShell

How can I write a PowerShell script to automate this set of commands?
Telnet to a machine,
execute few commands,
analyze at the output in the telnet window,
based on that output, send few more commands
Ok this isn't the most elegant solution, and it does rely on shudder VBscript but here it goes...
Create a VBScript to actually expedite the telnet session, this is an example
set oShell = CreateObject("WScript.Shell")
oShell.run("Telnet")
WScript.Sleep 1000
oShell.SendKeys("Open 127.0.0.1 23")
WScript.Sleep 1000
oShell.SendKeys("{Enter}")
WScript.Sleep 1000
oShell.SendKeys("n")
WScript.Sleep 1000
oShell.SendKeys("{Enter}")
WScript.Sleep 1000
oShell.SendKeys"MyName"
WScript.Sleep 1000
oShell.SendKeys("{Enter}")
WScript.Sleep 1000
oShell.SendKeys("MyPassword")
WScript.Sleep 1000
oShell.SendKeys("{Enter}")
WScript.Sleep 1000
oShell.SendKeys("MyCommand")
WScript.Sleep 1000
oShell.SendKeys("{Enter}")
WScript.Sleep 1000
Then use Powershell to invoke that script and pass it the commands you want executing, in the example below these commands are stored in a file called CommandList.txt
function Connect-MyTelnet{
Param(
[string] $IPAddress,
[string] $Port,
[string] $UserName,
[string] $Password,
[string] $cmdlistPath
)
## - Setting default values:
if($port -eq $null){ $Port = "23"; };
if($cmdlistPath -eq $null) { $CmdlistPath = 'c:\temp\cmdlist.txt'; };
## create vbscript file: MyTelnetSession.vbs
## - For Microsoft Telnet:
$MyVBScript = #"
set oShell = CreateObject("WScript.Shell")`r`n
oShell.run("Telnet")`r`n
WScript.Sleep 1000`r`n
oShell.SendKeys("Open $IPAddress $Port")`r`n
WScript.Sleep 1000`r`n
oShell.SendKeys("{Enter}")`r`n
WScript.Sleep 1000`r`n
oShell.SendKeys("n")`r`n
WScript.Sleep 1000`r`n
oShell.SendKeys("{Enter}")`r`n
WScript.Sleep 1000`r`n
oShell.SendKeys("$UserName")`r`n
WScript.Sleep 1000`r`n
oShell.SendKeys("{Enter}")`r`n
WScript.Sleep 1000`r`n
oShell.SendKeys("$Password")`r`n
WScript.Sleep 1000`r`n
oShell.SendKeys("{Enter}")`r`n
WScript.Sleep 1000`r`n
"#;
## - Get file with telnet commands:
[array] $Cmdlist = Get-Content $cmdlistPath;
## loop through and build each telnet command line:
foreach($cmd in $cmdlist)
{
## - Build VBscript lines:
$MyVBScript += 'oShell.SendKeys("'+$cmd+'")'+"`r`n";
$MyVBScript += "WScript.Sleep 1000`r`n";
$MyVBScript += 'oShell.SendKeys("{Enter}")'+"`r`n";
$MyVBScript += 'WScript.Sleep 1000'+"`r`n";
}
## - Close Telnet Session:
$MyVBScript += 'oShell.SendKeys(" QUIT")'+"`r`n";
$MyVBScript += "WScript.Sleep 1000`r`n";
$MyVBScript += 'oShell.SendKeys("{Enter}")'+"`r`n";
$MyVBScript += 'WScript.Sleep 1000'+"`r`n";
## - Save and execute generated VBscript:
$MYVBScript | Out-File -FilePath c:\temp\MyTelnet.vbs -Encoding ASCII;
& c:\temp\MyTelnet.vbs
}; Set-Alias ct Connect-MyTelnet;
And that should do what you are asking...
Note: Not my solution, found from this blog post and I have made use of it once or twice.
Rather than try to automate a telnet executable, just create the socket and issue the commands, read them back, and make decisions based on that. Here is an oversimplified example connecting to my local web server:
function test() {
$msg = [System.Text.Encoding]::ASCII.GetBytes("GET / HTTP/1.0`r`nHost: localhost`r`n`r`n")
$c = New-Object System.Net.Sockets.TcpClient("localhost", 80)
$str = $c.GetStream()
$str.Write($msg, 0, $msg.Length)
$buf = New-Object System.Byte[] 4096
$count = $str.Read($buf, 0, 4096)
[System.Text.Encoding]::ASCII.GetString($buf, 0, $count)
$str.Close()
$c.Close()
}
Obviously you would need to change it from port 80, and pass a username/password instead of a web request header... but this should be enough to get you started.
I wouldn't do anything with sockets here because you are going to need to implement at least parts of the telnet spec. If I remember, that spec is a bit funny. But there are some .NET telnet implementations listed here: C# Telnet Library that you can probably adapt or use directly from powershell in the same way that Goyuix is using the socket code in his answer.
I suggest you to use TeraTerm this free software.
you can telnet to your machine, and then run a TTL script.
it is very powerful and reliable. I am using it every day for my work.
you can do more search if you are interested.
example of TTL script:
i = 100
do while i>0
sendln 'un 1357'
wait '>'
sendln '.w 4 42800024 0000000a'
wait '>'
sendln '.w 4 42800014 00000004'
wait 'in service'
sendln 'info'
wait'>'
sendln 'start'
wait '20'#13#10'>' '0'#13#10'>'
if result!=2 then
break
endif
i = i - 1
loop
Here's a very basic Telnet client in PowerShell. It's essentially just the .net Framework's TcpClient, with some extra code to reject any IAC commands (i.e. when negotiating its abilities with the server it just says "I don't/won't do that" to all requests, ensuring that the most basic NVT implementation can be used).
Code maintained here: https://gist.github.com/JohnLBevan/e28fbb6c0dfdd45a21e03c104999c212
Function New-TelnetClient {
[CmdletBinding()]
Param (
[Parameter()]
[string]$ComputerName = '127.0.0.1'
,
[Parameter()]
[int]$PortNo = 23
,
[Parameter()]
[System.Text.Encoding]$Encoding = [System.Text.Encoding]::ASCII
,
[Parameter()]
[int]$BufferSize = 1024
)
[System.Net.Sockets.TcpClient]$telnet = New-Object 'System.Net.Sockets.TcpClient'
try {
$telnet.PSTypeNames.Add('ClearChannel.Net.Sockets.TelnetClient')
$telnet | Add-Member -MemberType 'NoteProperty' -Name 'Encoding' -Value ($Encoding)
$telnet | Add-Member -MemberType 'NoteProperty' -Name 'EndOfCommand' -Value ([System.Environment]::NewLine)
$telnet | Add-Member -MemberType 'NoteProperty' -Name 'BufferSize' -Value ($BufferSize)
$telnet.Connect($ComputerName, $PortNo)
$telnet | Add-Member -MemberType 'NoteProperty' -Name 'Writer' -Value (New-Object -TypeName 'System.IO.StreamWriter' -ArgumentList ($telnet.GetStream()))
$telnet.Writer.AutoFlush = $true
$telnet | Add-Member -MemberType 'ScriptMethod' -Name 'SendCommand' -Value ({
Param([string]$CommandText)
#$this.Writer.WriteLine($CommandText + $this.EndOfCommand) #writeline should stick the line endings in place anyway, but just to be sure, added this
$this.Writer.WriteLine($CommandText)
(New-Object -TypeName 'PSObject' -Property #{Direction='Input'; Value=$CommandText; When=((Get-Date).ToUniversalTime())})
})
$telnet | Add-Member -MemberType 'ScriptMethod' -Name 'HandleIac' -Value ({
if ($this.Available) {
[int]$byte = $this.GetStream().ReadByte()
[byte]$defaultResponse = 254 # for most IAC requests, we'll respond with don't
switch ($byte) {
-1 { # end of stream (shouldn't happen, but handled in case)
Write-Warning 'Unexpected end of stream whilst processing IAC'
return
}
255 { # Escaped IAC character
Write-Debug 'IAC Escaped'
return $byte
}
253 { #if we get a DO, change default response to WON'T instead of DON'T
$defaultResponse = 252
# do not break; continue to next case statement
}
{(251, 252, 253, 254) -contains $_} { # Will, Won't, Do, Don't
$byte = $this.GetStream().ReadByte() # this is the option we need to respond to; currently we just deny all options to get a raw NVT
switch ($byte) {
-1 {
Write-Warning 'Unexpected end of stream whilst processing IAC'
}
# if we want to handle specific IAC codes we can add support here
default {
$this.GetStream().WriteByte(255) # IAC
$this.GetStream().WriteByte($defaultResponse) # Don't/Won't
$this.GetStream().WriteByte($byte) # whatever you told me
}
}
return
}
default {
Write-Warning "$byte is not a control character, but was received after an IAC character"
}
}
}
})
$telnet | Add-Member -MemberType 'ScriptMethod' -Name 'GetBytes' -Value ({
Start-Sleep -Milliseconds 500 #added to get correct output; otherwise we seem to fly past the handshake :/
while ($this.Available -gt 0) {
[int]$byte = $this.GetStream().ReadByte() #held as int to allow -1 status code for end of stream
switch ($byte) {
-1 { # end of stream
return
}
255 { #IAC control character received
Write-Verbose 'IAC Command Received'
$this.HandleIac()
break
}
{($_ -ge 0) -and ($_ -lt 255)} { # normal data (not sure if it's worth returning the 0s... haven't seen anything to suggest that they're special though, as -1 is the eof.
[byte]$byte
Write-Debug "found $byte"
break
}
default {
throw "Received value $_ when expecting a byte (0-255)"
}
}
}
})
$telnet | Add-Member -MemberType 'ScriptMethod' -Name 'GetOutput' -Value ({
[byte[]]$bytes = $this.GetBytes()
if (($null -ne $bytes) -and ($bytes.Length -gt 0)) {
Write-Verbose "raw output is $(($bytes | %{"$_"}) -join ', ')"
$this.Encoding.GetString($bytes)
} else {
write-verbose 'no output this time'
}
})
$telnet | Add-Member -MemberType 'ScriptMethod' -Name 'ReceiveThenSendCommands' -Value ({
Param([string[]]$Commands)
foreach ($commandText in $commands) {
$this.GetOutput()
$this.SendCommand($commandText)
}
$this.GetOutput()
})
if ($telnet.Connected) {
$telnet
} else {
throw 'Failed to connect'
}
} catch {
Remove-TelnetClient -TelnetClient $telnet
}
}
Function Remove-TelnetClient {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[AllowNull()]
[PSObject]$TelnetClient
)
if ($null -ne $TelnetClient) {
if ($TelnetClient.Connected) {
$TelnetClient.GetStream().Close()
$TelnetClient.Close()
}
if($TelnetClient.Dispose) {
$TelnetClient.Dispose()
}
}
}
Here's an example of how it would be used in a normal scripted session:
# Example Usage
$telnet = New-TelnetClient -ComputerName 'TelnetServerNameFqdnOrIp'
try {
$telnet.ReceiveThenSendCommands(#(
'myTelnetUsername'
'myPlaintextTelnetPassword'
'DIR' #or whatever command I want to run
)) | Format-List # show the output in a readable format, including when it contains new line characters
} finally {
Remove-TelnetClient $telnet
}
But if you wanted to run it in interactive mode, just call SendCommand when you want to push commands to the server, and GetOutput to see results; e.g. you can run each line below one at a time.
$telnet = New-TelnetClient -ComputerName 'TelnetServerNameFqdnOrIp'
$telnet.GetOutput() # will probably display a welcome message & logon prompt
$telnet.SendCommand('myUsername') # send your username
$telnet.GetOutput() # will probably echo back your username then prompt for a password
$telnet.SendCommand('myPassword') # send your password
$telnet.GetOutput() # unlikely to output anything for a valid password; will give an error for an invalid one
$telnet.SendCommand('DIR') # send whatever commands you want to run
$telnet.GetOutput() # get the output of those commands
Remove-TelnetClient $telnet # once you're done, cleanly closes down the client
I have created a powershell script to telnet multiple stores from single host and has options to capture or no capture the tracert and ping command
Command to telnet multiple host and capture tracert and ping command
#Mutlple Telneting guide
#Created by : Mohit
#How to use ?
#Step 1 : Add mutiple IPs in DestinationIP.csv
#Step 2 : Run Batch file TelnetMultipleHost.bat
####################################################################################################################
$DestinationIP= Get-Content .\DestinationIP.csv
$ipV4 = (Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString
####################################################################################################################
write-host "-------------------Welcome to Multiple Telnet Host Panel-------------------------"
write-host ""
write-host ""
write-host "IMPORTANT: Make sure you are running this tool from source IP which in this case is " $ipV4
write-host ""
$Ports = Read-Host -Prompt "Enter Destination Port No.(# for multple ports just seperate ports with ,)"
write-host ""
write-host "Port No. you entered:" $Ports
write-host ""
write-host "Select Option"
write-host ""
write-host "Type 1 for telnet Host WITH trace logs"
write-host "Type 2 for telnet Host WITHOUT trace logs"
write-host ""
$option =Read-Host -Prompt "Type here"
write-host ""
Start-Transcript -Path .\TraceLogs_$ipV4.txt
switch($option)
{
#Type 1 for telnet Host WITH trace logs
1{
foreach ($Destination in $DestinationIP)
{
foreach ($Port in $Ports) {
# Create a Net.Sockets.TcpClient object to use for # checking for open TCP ports.
$Socket = New-Object Net.Sockets.TcpClient
# Suppress error messages
$ErrorActionPreference = 'SilentlyContinue'
# Try to connect
$Socket.Connect($Destination, $Port)
# Make error messages visible again
$ErrorActionPreference = 'Continue'
# Determine if we are connected.
if ($Socket.Connected) {
"${Destination}: Port $Port is open"
$Socket.Close()
}
else {
"${Destination}: Port $Port is closed or filtered"
if (test-connection $Destination -count 1 -quiet) {
write-host $Destination "Ping succeeded." -foreground green
} else {
write-host $Destination "Ping failed." -foreground red
}
Test-NetConnection $Destination -TraceRoute
}
# Apparently resetting the variable between iterations is necessary.
$Socket = $null
}
}
}
# Type 2 for telnet Host WITHOUT trace logs
2{
foreach ($Destination in $DestinationIP) {
foreach ($Port in $Ports) {
# Create a Net.Sockets.TcpClient object to use for
# checking for open TCP ports.
$Socket = New-Object Net.Sockets.TcpClient
# Suppress error messages
$ErrorActionPreference = 'SilentlyContinue'
# Try to connect
$Socket.Connect($Destination, $Port)
# Make error messages visible again
$ErrorActionPreference = 'Continue'
# Determine if we are connected.
if ($Socket.Connected) {
"${Destination}: Port $Port is open"
$Socket.Close()
}
else {
"${Destination}: Port $Port is closed or filtered"
}
# Apparently resetting the variable between iterations is necessary.
$Socket = $null
}
}
}
}
Stop-Transcript
Please note: TelnetMultipleHost.bat this batch is used to run the powershell command
Make sure we have bat, ps1 file in same directory
Code for batch file:
#echo off
Powershell.exe -executionpolicy remotesigned -File .\TelnetMultipleHost.ps1
pause
i use below script for telnet to multiple ip's:
$server_list = #('1.1.1.1:443', '10.100.8.22:3389', '10.100.8.21:22')
Foreach ($t in $server_list)
{
$source = $t.Split(':')[0]
$port = $t.Split(':')[1]
Write-Host "Connecting to $source on port $port" | Out-File 'output.txt' -Append
try
{
$socket = New-Object System.Net.Sockets.TcpClient($source, $port)
}
catch [Exception]
{
Write-Host $_.Exception.GetType().FullName | Out-File 'output.txt' -Append
Write-Host $_.Exception.Message | Out-File 'output.txt' -Append
}
Write-Host "Connected`n" | Out-File 'output.txt' -Append
}
when you are connected to ip's script show you you are connected to