很多時候我們需要通過Socket發送特定的TCP請求給服務器的特定端口來實現探測服務器的指定端口所開啟的服務。很多語言都有相應的方法實現上述需求,當然,PowerShell也不例外,比如我們要發送一個簡單的http請求到指定的web服務器:
GET / HTTP/1.1
Host:cn.bing.com
這里我們想請求微軟必應的中文首頁,如果需要通過PowerShell向cn.bing.com服務器發送get請求,就需要創建一個System.Net.Sockets.TcpClient對象,向指定的服務器和端口發送請求。
具體代碼如下:
代碼如下:
=====文件名:Send-TcpRequest.ps1=====
########################################
# Send-TcpRequest.ps1
## Send a TCP request to a remote computer, and return the response.
## If you do not supply input to this script (via either the pipeline, or the
## -InputObject parameter,) the script operates in interactive mode.
##
## Example:
##
## $http = @"
## GET / HTTP/1.1
## Host:cn.bing.com
## `n`n
## "@
##
## $http | ./Send-TcpRequest cn.bing.com 80
########################################
param(
[string] $remoteHost = "localhost",
[int] $port = 80,
[switch] $UseSSL,
[string] $inputObject,
[int] $commandDelay = 100
)
[string] $output = ""
## Store the input into an array that we can scan over. If there was no input,
## then we will be in interactive mode.
$currentInput = $inputObject
if(-not $currentInput)
{
$SCRIPT:currentInput = @($input)
}
$scriptedMode = [bool] $currentInput
function Main
{
## Open the socket, and connect to the computer on the specified port
if(-not $scriptedMode)
{
write-host "Connecting to $remoteHost on port $port"
}
trap { Write-Error "Could not connect to remote computer: $_"; exit }
$socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)
if(-not $scriptedMode)
{
write-host "Connected. Press ^D followed by [ENTER] to exit.`n"
}
$stream = $socket.GetStream()
if($UseSSL)
{
$sslStream = New-Object System.Net.Security.SslStream $stream,$false
$sslStream.AuthenticateAsClient($remoteHost)
新聞熱點
疑難解答