[PowerShell]리모트 장비의 특정 포트 접속 가능 확인

ignos·2022년 7월 14일

PS > tnc 202.20.10.1 -port 9092

리모트 장비의 특정 포트 접속 가능 여부 파악하기 위해 종종 위 방법 사용했었는데 너~무 느려서 다른 방법 검색.

# Test-Port1.ps1
Param([string]$hostname,$port=80,$timeout=100)

$requestCallback = $state = $null
$client = New-Object System.Net.Sockets.TcpClient
$beginConnect = $client.BeginConnect($hostname,$port,$requestCallback,$state)
Start-Sleep -milli $timeOut
if ($client.Connected) { $open = $true } else { $open = $false }
$client.Close()
[pscustomobject]@{hostname=$hostname;port=$port;open=$open}

Test-Port1.ps1 202.20.10.1 9092

Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose)

# Test-Port2.ps1
# Does a TCP connection on specified port (135 by default)

$ErrorActionPreference = "SilentlyContinue"

# Create TCP Client
$tcpclient = new-Object system.Net.Sockets.TcpClient

# Tell TCP Client to connect to machine on Port
$iar = $tcpclient.BeginConnect($srv,$port,$null,$null)

# Set the wait time
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)

# Check to see if the connection is done
if(!$wait)
{
    # Close the connection and report timeout
    $tcpclient.Close()
    if($verbose){Write-Host "Connection Timeout"}
    Return $false
}
else
{
    # Close the connection and report the error if there is one
    $error.Clear()
    $tcpclient.EndConnect($iar) | out-Null
    if(!$?){if($verbose){write-host $error[0]};$failed = $true}
    $tcpclient.Close()
}

# Return $true if connection Establish else $False
if($failed){return $false}else{return $true}

Test-Port2.ps1 202.20.10.1 9092

둘 다 쓸만.

profile
ignoramus

0개의 댓글