Powershell Test-Connection 으로 네트워크상의 Host들 확인하기

Powershell cmdlet 중 하나인 Test-Connection 은 네트워크상의 Host와 ICMP 패킷을 이용하여 연결을 테스트 할 수 있다. 이 cmdlet은 흔히 cmd 에서 사용하는 ping.exe와 매우 유사하다.

Test-Connection [-ComputerName]  [[-Source] ] [-AsJob] [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-BufferSize ] [-Count ] [-Credential ] [-Delay ] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Quiet] [-ThrottleLimit ] [-TimeToLive ] []

ping.exe 로 할 수 있는 것은 거의 다 할 수있고, Powershell Cmdlet인 만큼 다른 cmdlet과 조합해 쓰면 더욱 유용할 것이다.

간단한 것부터 시작 해 보자.
IP가 192.168.0.10인 Host 로 Test-Connection 한다.

Test-Connection 192.168.0.10	# Test-Connection -ComputerName 192.168.0.10

성공적이라면 다음과 같은 결과를 볼 것이다.

Source   Destination  IPV4Address  IPV6Address                  Bytes Time(ms)
------   -----------  -----------  -----------                  ----- --------
TALSU-PC 192.168.0.20 192.168.0.20 fe80::3d95:e8c9:298f:33dc%13 32    0
TALSU-PC 192.168.0.20 192.168.0.20 fe80::3d95:e8c9:298f:33dc%13 32    0
TALSU-PC 192.168.0.20 192.168.0.20 fe80::3d95:e8c9:298f:33dc%13 32    0
TALSU-PC 192.168.0.20 192.168.0.20 fe80::3d95:e8c9:298f:33dc%13 32    0

성공적으로 ICMP 패킷을 보내고 응답을 받은 모습이다. (자신의 IP로 하면 100% 성공할 수 있다.)

실패하면 다음과 같은 Error 가 발생 한다.

Test-Connection : ‘192.168.0.10’ 컴퓨터에 대한 연결 테스트가 실패했습니다. 데이터베이스를 검색하는 동안 복구할 수 없는 오류가 발생했습니다
위치 줄:1 문자:16
+ Test-Connection <<<< 192.168.0.10 | clip + CategoryInfo : ResourceUnavailable: (192.168.0.10:String) [Test-Connection], PingException + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

ICMP 패킷을 보내고 응답이 없을때마다. 같은 에러가 계속 발생 한다.

Error가 보고 싶지 않고 접속 결과만 얻기 위해서는 -Quiet Parameter를 사용면 그 결과에 따라 $true, $false (Bool)를 반환 한다.

Test-Connection 192.168.0.10 -Quiet		# Error 없이 [bool] 타입을 반환한다.

이번에는 한번에 같은 Class에 있는 Host 들에게 모두 Test-Connection을 시도해 보자.

1..255 | Foreach-Object { Test-Connection "192.168.0.$_" }

192.168.0.1 ~ 192.168.0.255 까지 모두 Test-Connection을 시도 하면서 결과를 보일 것이다. 그런데 ICMP패킷을 4번씩 보내고 응답이 없는 Host에는 Error 메세지가 4번씩 나오기 때문에 보기도 쉽지 않고 출력을 다른곳에 활용하기도 불편해 보인다.

ICMP 패킷을 하나만 보내고 결과는 Bool 타입으로 받아 응답하는 Host 번호만 보면 좋을 것 같다.

1..255 | Where-Object { Test-Connection "192.168.0.$_" -Count 1 -Quiet }

예상대로 동작한다.

보기 좋게 출력 되도록 조금더 손봐서 스크립트로 만들어두면 편리 하다.

Test-MultipleConnections1.ps1

param (
	[string]$Gateway,
	[int]$StartPosition = 1,
	[int]$EndPosition = 255
	)

if ($Gateway -match "(d{1,3}.){2}d{1,3}")
{
	$StartPosition..$EndPosition |
	Foreach-Object {
		$Name = "{0}.{1}" -f $Matches[0], $_

		if (Test-Connection $Name -count 1 -quiet)
		{
			$Color = "Green"
			$Name += " - Success"
		}
		else
		{
			$Color = "Red"
			$Name += " - Fail"
		}

		Write-host $Name -ForegroundColor $Color
	}
}

Test-MultipleConnections1.ps1

컬러풀 하고 보기 좋게 나온다. 하지만 PSObject 출력이 필요 할 때도 있다.

Test-MultipleConnections2.ps1

param (
    [string]$Gateway,
    [int]$StartPosition = 1,
    [int]$EndPosition = 255
    )

if ($Gateway -match "(d{1,3}.){2}d{1,3}")
{
	$ResultObject = New-Object -TypeName PSObject
	Add-Member -InputObject $ResultObject -MemberType NoteProperty -Name Address -Value $null
	Add-Member -InputObject $ResultObject -MemberType NoteProperty -Name IsSuccess -Value $false

    $StartPosition..$EndPosition |
    Foreach-Object {
        $ResultObject.Address = "{0}.{1}" -f $Matches[0], $_

		$ResultObject.IsSuccess = Test-Connection $ResultObject.Address -count 1 -quiet

		$ResultObject
    }
}

Test-MultipleConnections2.ps1



Add-Member가 부담되고 좀더 쉽게 가려면

Test-MultipleConnections3.ps1

param (
    [string]$Gateway,
    [int]$StartPosition = 1,
    [int]$EndPosition = 255
    )

if ($Gateway -match "(d{1,3}.){2}d{1,3}")
{
    $StartPosition..$EndPosition |
    Foreach-Object {
		$ResultHash = @{}
        $ResultHash.Address = "{0}.{1}" -f $Matches[0], $_
		$ResultHash.IsSuccess = Test-Connection $ResultHash.Address -count 1 -quiet

		New-Object PSObject -Property $ResultHash
    }
}

출력은 Test-MultipleConnections2.ps1 와 유사하다.

답글 남기기

이메일 주소는 공개되지 않습니다.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.