首页 > 开发 > PowerShell > 正文

PowerShell小技巧之发送TCP请求

2020-05-30 20:17:08
字体:
来源:转载
供稿:网友

很多时候我们需要通过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)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表