Search code examples
powershelltcpporttelnet

How can I automate Telnet port checking in Powershell?`


I'm currently trying to put together a script that queries AD for a list of computers, pings the computers to determine which ones are still active, and then telnets into a specific port on all the pingable computers. The output I'm looking for is a full list of pingable computers in AD for which I can't telnet to the said port.

I've read these few questions, but they don't quite hit on what I'm trying to do. I just want to see if the telnet connection is successful without entering telnet (or automate the quitting of telnet) and move on to the next machine to test. The AD and pinging portions of my script are set, I'm just stuck here. The things I've tried haven't quite worked as planned.

Here is the code for the first parts of the script, if needed:

Get-ADComputer -Filter * -SearchBase 'DC=hahaha,DC=hehehe' | ForEach {

$computerName = $_.Name

$props = @{
    ComputerName = $computerName
    Alive = $false
    PortOpen = $false
}

If (Test-Connection -ComputerName $computerName -Count 1 -Quiet) {

    $props.Alive = $true
}

Solution

  • Adapting this code into your own would be the easiest way. This code sample comes from the PowerShellAdmin wiki. Collect the computer and port you want to check. Then attempt to make a connection to that computer on each port using Net.Sockets.TcpClient.

    foreach ($Computer in $ComputerName) {
    
        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($Computer, $Port)
    
            # Make error messages visible again
            $ErrorActionPreference = 'Continue'
    
            # Determine if we are connected.
            if ($Socket.Connected) {
                "${Computer}: Port $Port is open"
                $Socket.Close()
            }
            else {
                "${Computer}: Port $Port is closed or filtered"  
            }
            # Apparently resetting the variable between iterations is necessary.
            $Socket = $null
        }
    }