PowerShell脚本开发之收发TCP消息包
在上篇文章中,我们在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===== FunctionReceive-TCPMessage { param([ValidateNotNullOrEmpty()] [int]$Port) try { $EndPoint=New-ObjectSystem.Net.IPEndPoint([System.Net.IPAddress]::Loopback,$Port) $Socket=New-ObjectSystem.Net.Sockets.TCPListener($EndPoint) $Socket.Start() $Socket=$Socket.AcceptTCPClient() $EncodedText=New-ObjectSystem.Text.ASCIIEncoding $Stream=$Socket.GetStream() $Buffer=New-ObjectSystem.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===== FunctionSend-TCPMessage { param([ValidateNotNullOrEmpty()] [string]$EndPoint, [int]$Port, [string]$Message)
$IP=[System.Net.Dns]::GetHostAddresses($EndPoint) $Address=[System.Net.IPAddress]::Parse($IP) $Socket=New-ObjectSystem.Net.Sockets.TCPClient($Address,$Port) $Stream=$Socket.GetStream() $Writer=New-ObjectSystem.IO.StreamWriter($Stream) $Writer.AutoFlush=$true $Writer.NewLine=$true $Writer.Write($Message) $Socket.Close() }