1

I have a server that has an open socket that listens for a particular text string on it in order to perform an action.

Our linux machines send this data via:

echo "text_string" | nc -w 2 server-name port#

Is this possible on Windows (possibly in powershell or other builtin utilities)? If so, how?

2 Answers2

5

Here's a little Powershell for you... should be compatible with any version of PS... maybe PSv2 or better. Works with either host names or IP addresses.

Function Send-StringOverTcp ( 
    [Parameter(Mandatory=$True)][String]$DataToSend,
    [Parameter(Mandatory=$True)][String]$Hostname, 
    [Parameter(Mandatory=$True)][UInt16]$Port)
{
    Try
    {
        $ErrorActionPreference = "Stop"
        $TCPClient  = New-Object Net.Sockets.TcpClient
        $IPEndpoint = New-Object Net.IPEndPoint($([Net.Dns]::GetHostEntry($Hostname)).AddressList[0], $Port)
        $TCPClient.Connect($IPEndpoint)
        $NetStream  = $TCPClient.GetStream()
        [Byte[]]$Buffer = [Text.Encoding]::ASCII.GetBytes($DataToSend)
        $NetStream.Write($Buffer, 0, $Buffer.Length)
        $NetStream.Flush()
    }
    Finally
    {
        If ($NetStream) { $NetStream.Dispose() }
        If ($TCPClient) { $TCPClient.Dispose() }
    }
}

    Send-StringOverTcp -DataToSend 'foo!' -Hostname google.com -Port 80

I wrote this very hastily... you might want to put extra parameter validation and error trapping in there, but you get the idea. Also worth considering is that Windows uses UTF16 LE encoding by default, so characters are typically "wide," as opposed to many other systems which use narrow characters. So you may want to encode the string as Unicode instead of ASCII, etc. Depends on what you're using it for.

Or if you'd rather make it as simple as your Netcat example, just... download Netcat for Windows.

Ryan Ries
  • 55,481
  • 10
  • 142
  • 199
  • If I download netcat for windows. How do I "pipe" the output from powershell to the application? I can't really go write "output" | netcat.exe can I? – cheesesticksricepuck Sep 18 '14 at 23:12
  • Nevermind apparently pipelining works in Windows. I guess my Windows skills need some work. PS C:\Users\root> Write TPC-F11-21-021 | ncat.exe -w 2 10.128.0.20 2069 ERROR unrecognized command close: No error – cheesesticksricepuck Sep 19 '14 at 02:56
  • Ryan, thanks for the response I'll be attempting your method in a few days. For now I will be using netcat for windows but I would like to not have to. – cheesesticksricepuck Sep 19 '14 at 02:57
4

you can use PuTTY for this, select the raw connection option. Telnet may also work for you

telnet server port

HamishC
  • 66
  • 3