pwsh 获取类似 telent的返回内容
js的tcp服务
const net = require('net');
const server = net.createServer((c) => {
// 'connection' listener.
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.on('error', (err) => {
throw err;
});
server.listen(8124, () => {
console.log('server bound');
});
powershell获取tcp返回内容
Function Get-TCPResponse {
<# Author:fuhj(powershell#live.cn ,http://fuhaijun.com)
.SYNOPSIS
Tests TCP port of remote or local system and returns a response header
if applicable
.DESCRIPTION
Tests TCP port of remote or local system and returns a response header
if applicable
If server has no default response, then Response property will be NULL
.PARAMETER Computername
Local or remote system to test connection
.PARAMETER Port
TCP Port to connect to
.PARAMETER TCPTimeout
Time until connection should abort
.EXAMPLE
Get-TCPResponse -Computername pop.126.com -Port 110
Computername : pop.126.com
Port : 110
IsOpen : True
Response : +OK Welcome to coremail Mail Pop3 Server (126coms[75c606d72bf436dfbce6.....])
Description
-----------
Checks port 110 of an mail server and displays header response.
#>
[OutputType('Net.TCPResponse')]
[cmdletbinding()]
Param (
[parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('__Server', 'IPAddress', 'IP', 'domain')]
[string[]]$Computername = $env:Computername,
[int[]]$Port = 25,
[int]$TCPTimeout = 1000
)
Process {
ForEach ($Computer in $Computername) {
ForEach ($_port in $Port) {
$stringBuilder = New-Object Text.StringBuilder
$tcpClient = New-Object System.Net.Sockets.TCPClient
$connect = $tcpClient.BeginConnect($Computer, $_port, $null, $null)
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout, $false)
If (-NOT $wait) {
$object = [pscustomobject] @{
Computername = $Computer
Port = $_Port
IsOpen = $False
Response = $Null
}
}
Else {
While ($True) {
#Let buffer
Start-Sleep -Milliseconds 1000
Write-Verbose "Bytes available: $($tcpClient.Available)"
If ([int64]$tcpClient.Available -gt 0) {
$stream = $TcpClient.GetStream()
$bindResponseBuffer = New-Object Byte[] -ArgumentList $tcpClient.Available
[Int]$response = $stream.Read($bindResponseBuffer, 0, $bindResponseBuffer.count)
$Null = $stringBuilder.Append(($bindResponseBuffer | ForEach { [char][int]$_ }) -join '')
}
Else {
Break
}
}
$object = [pscustomobject] @{
Computername = $Computer
Port = $_Port
IsOpen = $True
Response = $stringBuilder.Tostring()
}
}
$object.pstypenames.insert(0, 'Net.TCPResponse')
Write-Output $object
If ($Stream) {
$stream.Close()
$stream.Dispose()
}
$tcpClient.Close()
$tcpClient.Dispose()
}
}
}
}
Get-TCPResponse -Port 8124