telnet connection testing through powershell

Welcome Forums General PowerShell Q&A telnet connection testing through powershell

This topic contains 4 replies, has 5 voices, and was last updated by

 
Participant
2 months, 4 weeks ago.

  • Author
    Posts
  • #162342

    Participant
    Topics: 4
    Replies: 0
    Points: 34
    Rank: Member

    Hi All,

    I want to check whether telnet connection to a SMTP server on port 25 is working or not from a machine. Below is the script i've written to do it.

    Now when i run the telnet command on a machine manually it is saying "421 4.3.2 Service not available.... Connection to host lost." so telnet connection is not working from that machine. that is fine.

    but if i run the below script on the same machine where telnet failed with above said error message, it is saying "Success". Not sure what is wrong with my script, please help

    $Socket = New-Object Net.Sockets.TcpClient

    # Suppress error messages
    $ErrorActionPreference = 'SilentlyContinue'

    # Try to connect
    $Socket.Connect("124.140.118.209", "25")

    # Make error messages visible again
    $ErrorActionPreference = 'Continue'

    # Determine if we are connected.
    if ($Socket.Connected) {
    Write-Output "Success"
    $Socket.Close()
    }
    else {
    Write-Output "Failed"
    }
    # Apparently resetting the variable between iterations is necessary.
    $Socket = $null

  • #162344

    Participant
    Topics: 1
    Replies: 1530
    Points: 2,591
    Helping Hand
    Rank: Community Hero
  • #162377
    js

    Participant
    Topics: 25
    Replies: 678
    Points: 1,629
    Helping Hand
    Rank: Community Hero
    test-netconnection 124.140.118.209 -port 25
    
  • #162411

    Participant
    Topics: 2
    Replies: 999
    Points: 1,946
    Helping Hand
    Rank: Community Hero

    JS, as for this ...

    test-netconnection 124.140.118.209 -port 25

    … yeppers, but this is only available if the OP in on an OS and PS version that has it. Hence, maybe the reason the OP is using what they are, or maybe they just don't know about Test-NetConnection either.

  • #162614

    Participant
    Topics: 1
    Replies: 59
    Points: 328
    Helping Hand
    Rank: Contributor

    Since you're testing access to a mail server, why not simply send a test message?

    $machine=$env:computername
    $MailParams = @{
                     To          = "me@mydomain.com"
                     From        = "me@mydomain.com"
                     SmtpServer  = "mymailserver.mydomain.com"
                     Subject     = "Connectivity Error from $machine"
                     Body     = "Connectivity Error from $machine"
    		    }
    Send-MailMessage @MailParams

    if it goes through, great. If it doesn't you'll get an error back that'll at least tell you if its from a mail server or not. If the error message is from the mail server great....access is open.

You must be logged in to reply to this topic.