很多時(shí)候我們需要通過Socket發(fā)送特定的TCP請求給服務(wù)器的特定端口來實(shí)現(xiàn)探測服務(wù)器的指定端口所開啟的服務(wù)。很多語言都有相應(yīng)的方法實(shí)現(xiàn)上述需求,當(dāng)然,PowerShell也不例外,比如我們要發(fā)送一個(gè)簡單的http請求到指定的web服務(wù)器:
GET / HTTP/1.1
Host:cn.bing.com
這里我們想請求微軟必應(yīng)的中文首頁,如果需要通過PowerShell向cn.bing.com服務(wù)器發(fā)送get請求,就需要?jiǎng)?chuàng)建一個(gè)System.Net.Sockets.TcpClient對象,向指定的服務(wù)器和端口發(fā)送請求。
具體代碼如下:
代碼如下:
=====文件名: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)
新聞熱點(diǎn)
疑難解答
圖片精選