Ncat - Testing Network Connections

Linux
Network
Published

March 27, 2024

Modified

March 27, 2024

Ncat 1 …re-implementation of netcat:

# install required RPM package
sudo dnf install -y nmap-ncat

General syntax:

# attempt to initiate a TCP connection to the defined host on the port number 
ncat ${host:-localhost} ${port:-22}

# listen on port for incomming connections
ncat -v -l ${port:1234}
# …connection
ncat ${host:-localhost} ${port:-1234}

Response

Command execution…

  • --exec command without shell interpreter
  • --sh-exec pass command to a system shell
  • --lua-exec run a Lua program
# execute a command for response
ncat -l -p ${port:-1234} --send-only --exec "/bin/date"

# execute shell-script for response & keep connection alive
ncat -l --keep-open -p ${port:-1234} --sh-exec "echo -e hello from $(hostname -i)"

Dummy HTTP Server…

cat > response.txt <<EOF
HTTP/1.0 200 OK

<html>
  <body>
    <h1>Hello, world!</h1>
  </body>
</html>
EOF

ncat -l -p 8080 < response.txt

Connect mode vs listen mode:

  • Listen mode …accept connection …run command …exit
  • Connect mode …with option --keep-open
    • …accept multiple connections …one handler per connection
    • …exit with ctrl+C

Receive

Print incoming data to stdout:

ncat -l -p ${port:-1234} --keep-open --verbose --recv-only

Data transfer…

# Write incomming data to a file
ncat -l -p ${port:-1234} > receive.txt

# Send data from stdin
echo Hello | ncat --send-only ${host:-localhost} ${port:-1234} 

# Send data from a file
echo "Hello from $(hostname -i)" > input.txt
ncat --send-only ${host:-localhost} ${port:-1234} < input.txt

Footnotes

  1. Nact User Guide, Nmap Project
    https://nmap.org/ncat/guide/index.html↩︎