通過PowerShell獲取TCP響應(類Telnet)

@天行健中國元素發表於2014-10-10

通常情況下,為了檢測指定的TCP埠是否存活,我們都是通過telnet指定的埠看是否有響應來確定,然而預設情況下win8以後的系統預設是不安裝telnet的。設想一下如果你黑進了一個伺服器,上面沒裝telnet,但是為了進一步滲透進內網,需要探測內部伺服器特定埠是否開啟,同時你還不願意安裝telnet,擔心引起管理員注意。那麼好吧,在這個情況下你需要我的這個指令碼。由於它是原生態的PowerShell語句完成,木有telnet你也照樣能檢測TCP埠的情況了。

下面首先上程式碼,後面進行講解:

        =====檔名: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連線進行關閉,以便釋放資源

呼叫方法如下:

Get-TCPResponse -Computername pop.126.com -Port 110

 

image

再對比一下telnet的結果

image

結果是一樣的,以後沒有telnet也難不住大家了,have fun!^_^

 

作者: 付海軍
出處:http://fuhj02.cnblogs.com
版權:本文版權歸作者和部落格園共有
轉載:歡迎轉載,為了儲存作者的創作熱情,請按要求【轉載】,謝謝
要求:未經作者同意,必須保留此段宣告;必須在文章中給出原文連線;否則必究法律責任
個人網站: http://www.fuhaijun.com/

相關文章