정성태님 블로그 포스트 를 보다가, 파워쉘로도 써봤습니다. 어차피 닷넷을 실행하는 것이니까 같은 일을 합니다. 물론 퍼포먼스는 차이가 있겠지요.
간단한 소켓프로그램이므로 설명은 없어도 될 것 같습니다.
server
1
2
3
4
5
6
7
8
9
10
| $port=9900
$endpoint = new-object System.Net.IPEndPoint ([system.net.ipaddress]::any, $port)
$listener = new-object System.Net.Sockets.TcpListener $endpoint
$listener.start()
$client = $listener.AcceptTcpClient()
$stream = $client.GetStream()
[byte[]]$bytes = New-Object byte[] 1024
$bytesReceived = $stream.Read($bytes, 0, $bytes.Length)
[System.Text.Encoding]::ASCII.GetString($bytes)
|
client
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| Function Invoke-NetCat {
[CmdletBinding()]
Param (
[Parameter(Position = 0, ValueFromPipeline=$True)]
[string] $targethost = $(throw "no host"),
[Parameter(Position = 1, ValueFromPipeline=$True)]
[int] $port = $(throw "no port"),
[Parameter(ValueFromPipeline=$True)]
[string] $item
)
$client = [System.Net.Sockets.TcpClient]::new($targethost, $port)
[System.Net.Sockets.NetworkStream]$ns = $client.GetStream()
$enc = [system.Text.Encoding]::UTF8
$stream= [System.IO.MemoryStream]::new( $enc.GetBytes($item) )
$br = [System.IO.BinaryReader]::new($stream)
While($true) {
$buffer = $br.ReadBytes(512)
if (!$buffer) {
break;
}
$ns.Write($buffer, 0, $buffer.Length)
}
}
|
이 코드는 ubuntu pwsh에서도 동작합니다.
주의
파이프로 받는 파라메터는 다음과 같이 Key Validation을 넣어버리면, 값을 fetch하는 것보다 evaluate 판정이 먼저 일어나서 정상적으로 처리되지 않습니다.
NG
1
2
| [Parameter(ValueFromPipeline=$True)]
[string] $item = $(throw "no item")
|
레퍼런스