首页 > 开发 > PowerShell > 正文

PowerShell脚本开发之收发TCP消息包

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

在上篇文章中,我们在PSNet包中创建了Test-TCPPort函数用于探测指定IP的指定端口是否开放,检测端口之后大多数人想到的可能就是需要通过PowerShell收发TCP消息包了,这篇文章里将会描述如何在PSNet包中创建针对TCP消息包的函数Receive-和TCPMessageSend-TCPMessage。为了承接上篇中我们创建的PSNet工具集的思路,在确定了函数的命名之后,创建上述两个函数对应的.ps1文件放置在$env:PSSpace/PSNet/TCPOp/中。

接下来在$env:PSSpace/PSNet/PSNet.psm1中添加以下两条语句用于在工具集中引入上述两个函数文件:

代码如下:
. $env:PSSpace/PSNet/TCPOp/Receive-TCPMessage.ps1
. $env:PSSpace/PSNet/TCPOp/Send-TCPMessage.ps1

然后分别在创建的.ps1文件中添加以下代码:

代码如下:
 =====文件名:Receive-TCPMessage.ps1=====
Function Receive-TCPMessage
{
    param ( [ValidateNotNullOrEmpty()]
    [int] $Port )
    try
    {
        $EndPoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Loopback,$Port)
        $Socket = New-Object System.Net.Sockets.TCPListener($EndPoint)
        $Socket.Start()
        $Socket = $Socket.AcceptTCPClient()
        $EncodedText = New-Object System.Text.ASCIIEncoding
        $Stream = $Socket.GetStream()
        $Buffer = New-Object System.Byte[] $Socket.ReceiveBufferSize
        while( $Bytes = $Stream.Read($Buffer,0,$Buffer.Length) )
        {
            $Stream.Write($Buffer,0,$Bytes)
            Write-Output $EncodedText.GetString($Buffer,0,$Bytes)
        }
        $Socket.Close()
        $Socket.Stop()
    }
    catch{}
}

代码如下:
        =====文件名:Send-TCPMessage.ps1=====
Function Send-TCPMessage
{
    param ( [ValidateNotNullOrEmpty()]
    [string] $EndPoint,
    [int] $Port,
    [string] $Message )

    $IP = [System.Net.Dns]::GetHostAddresses($EndPoint)
    $Address = [System.Net.IPAddress]::Parse($IP)
    $Socket = New-Object System.Net.Sockets.TCPClient($Address,$Port)
    $Stream = $Socket.GetStream()

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