一般状况下,为了检测指定的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!^_^网站
做者: 付海军
出处:http://fuhj02.cnblogs.com
版权:本文版权归做者和博客园共有
转载:欢迎转载,为了保存做者的创做热情,请按要求【转载】,谢谢
要求:未经做者赞成,必须保留此段声明;必须在文章中给出原文链接;不然必究法律责任
我的网站: http://www.fuhaijun.com/ui