一般狀況下,爲了檢測指定的TCP端口是否存活,咱們都是經過telnet指定的端口看是否有響應來肯定,然而默認狀況下win8之後的系統默認是不安裝telnet的。設想一下若是你黑進了一個服務器,上面沒裝telnet,可是爲了進一步***進內網,須要探測內部服務器特定端口是否打開,同時你還不肯意安裝telnet,擔憂引發管理員注意。那麼好吧,在這個狀況下你須要個人這個腳本。因爲它是原生態的PowerShell語句完成,木有telnet你也照樣能檢測TCP端口的狀況了。shell
下面首先上代碼,後面進行講解:服務器
=====文件名:Get-TCPResponse.ps1=====
Function Get-TCPResponse {
<# Author:fuhj(powershell#live.cn ,http://fuhaijun.com)
.SYNOPSIS
Tests TCP port of remote or local system and returns a response header
if applicable
.DESCRIPTION
Tests TCP port of remote or local system and returns a response header
if applicable
If server has no default response, then Response property will be NULL
.PARAMETER Computername
Local or remote system to test connection
.PARAMETER Port
TCP Port to connect to
.PARAMETER TCPTimeout
Time until connection should abort
.EXAMPLE
Get-TCPResponse -Computername pop.126.com -Port 110
Computername : pop.126.com
Port : 110
IsOpen : True
Response : +OK Welcome to coremail Mail Pop3 Server (126coms[75c606d72bf436dfbce6.....])
Description
-----------
Checks port 110 of an mail server and displays header response.
#>
[OutputType('Net.TCPResponse')]
[cmdletbinding()]
Param (
[parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
[Alias('__Server','IPAddress','IP','domain')]
[string[]]$Computername = $env:Computername,
[int[]]$Port = 25,
[int]$TCPTimeout = 1000
)
Process {
ForEach ($Computer in $Computername) {
ForEach ($_port in $Port) {
$stringBuilder = New-Object Text.StringBuilder
$tcpClient = New-Object System.Net.Sockets.TCPClient
$connect = $tcpClient.BeginConnect($Computer,$_port,$null,$null)
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
If (-NOT $wait) {
$object = [pscustomobject] @{
Computername = $Computer
Port = $_Port
IsOpen = $False
Response = $Null
}
} Else {
While ($True) {
#Let buffer
Start-Sleep -Milliseconds 1000
Write-Verbose "Bytes available: $($tcpClient.Available)"
If ([int64]$tcpClient.Available -gt 0) {
$stream = $TcpClient.GetStream()
$bindResponseBuffer = New-Object Byte[] -ArgumentList $tcpClient.Available
[Int]$response = $stream.Read($bindResponseBuffer, 0, $bindResponseBuffer.count)
$Null = $stringBuilder.Append(($bindResponseBuffer | ForEach {[char][int]$_}) -join '')
} Else {
Break
}
}
$object = [pscustomobject] @{
Computername = $Computer
Port = $_Port
IsOpen = $True
Response = $stringBuilder.Tostring()
}
}
$object.pstypenames.insert(0,'Net.TCPResponse')
Write-Output $object
If ($Stream) {
$stream.Close()
$stream.Dispose()
}
$tcpClient.Close()
$tcpClient.Dispose()
}
}
}
}
首先建立一個System.Net.Sockets.TCPClient對象,去鏈接指定的域名和端口,瞬間斷開的那是服務器沒開那個端口,直接被拒絕了,若是沒拒絕,那就等着服務器端給你響應,而後讀取字節流拼接起來進行解析。
最後須要強調的是須要對打開的流和TCP鏈接進行關閉,以便釋放資源
調用方法以下:app
Get-TCPResponse -Computername pop.126.com -Port 110dom
再對比一下telnet的結果tcp
結果是同樣的,之後沒有telnet也難不住你們了,have fun!^_^ide
做者: 付海軍
出處:http://fuhj02.blog.51cto.com
版權:本文版權歸做者和51cto共有
轉載:歡迎轉載,爲了保存做者的創做熱情,請按要求【轉載】,謝謝
要求:未經做者贊成,必須保留此段聲明;必須在文章中給出原文鏈接;不然必究法律責任
我的網站: http://www.fuhaijun.com/網站