PowerShellの「Test-NetConnection」使って指定したポートがアクセスできるかを確認することができる。
ただ、細かいあたりは指定できないようで、タイムアウト待ち時間やリトライ回数の指定などはできない。標準だと10秒待つようです。
雑に、192.168.1.1~192.168.1.254の範囲でssh用のポート22番が空いているものがあるかを確認するものとして以下を書いた。
for ($count=1; $count -lt 255; $count++){ $ipaddr="192.168.1."+$count if( (Test-NetConnection $ipaddr -port 22).TcpTestSucceeded -eq "True"){ Write-Host $ipaddr } }
ただ、アクセスできなかった場合、下記の様に「警告」が出力される作りになっている。
警告: TCP connect to (192.168.1.10 : 22) failed
警告: Ping to 192.168.1.10 failed with status: TimedOut
探せば警告を抑止する手法もありそうですが、面倒なので省略しています。
Test-NetConnectionを使う限りはカスタマイズできないので「Test network ports faster with PowerShell」にていくつか例が提示されています。
その1
function testport ($hostname='yahoo.com',$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} } testport hostname port open -------- ---- ---- yahoo.com 80 True
その2
Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose) # Test-Port.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}