Useful Netcat Examples
In this netcat tutorial you can see useful netcat examples to help you use this powerful tool.
Netcat (nc – in short) can be called “Swiss army of knife” in Linux network terminal utilities. Netcat can be used for just about anything. It can scan ports, listen on arbitrary TCP and UDP ports, also open TCP connections, send UDP packets, network daemon testing and much more.
How to Install Netcat on Linux
Install netcat on CentOS or RedHat
# yum install nc
Install Netcat on Ubuntu or Debian
# apt-get install netcat
Example output:
NETCAT SIMPLE CHAT BETWEEN 2 HOSTS
Lets build basic client/server model.
On server side run:
$ nc -l 5555
Now your server starts listening 5555 port and ready accept incoming connections.
On client machine (or on same machine) run:
$ nc localhost 5555
Instead of localhost you can put remote machine name or IP address. After establish connection between machines you can start typing on any machine and will see that text on other side. To terminate connection press CTRL-c.
NETCAT FILE TRANSFER
Netcat can be used for transfer files between. Let’s try send file inputfile.txt form host1 to host2.
Run on receiver host2 side:
$ nc -l 5555 > output.txt
On sender host1 run:
nc host2 5555 < inputfile.txt
NETCAT PORT SCAN
Netcat can can be used for scanning open ports and running services on target machine.
In example below you see how to scan for open ports on SERVER in range from 20 to 23. Where is options:
-z – Specifies that nc should just scan for listening daemons, without sending any data to them
-v – Netcat will give more verbose output.
$ nc -zv SERVER 20-23
Netcat also can scan ports with given ports list:
$ nc -zv SERVER 22 25 80
CHECK WHICH SERVICE IS RUNNING ON PORT
$ nc -vn SERVER_IP port
Example output testing localhost 22 port:
In previous example was used -n option which is disable DNS or service lookups. So if you going to put instead of IP server name DON’T use -n flag:
NETCAT REMOTE SHELL
You can connect to remote server and execute commands en remote host.
On remote host run:
$ nc -lp 5555 -e /bin/bash
On local host:
$ nc SERVER_IP 5555
After executing you will have terminal shell from remote host without authorization, and can execute any command from local host.
Some netcat versions comes without -e flag, as result you will have error:
nc: invalid option -- 'e'
In that case on remote host run:
$ rm -f /tmp/f; mkfifo /tmp/f $ cat /tmp/f | /bin/sh -i 2>&1 | nc -lp 5555 > /tmp/f
On local host:
$ nc -lp 5555 -e /bin/bash
NETCAT UDP PORT SCANNING
Scan UDP 4950-5010 port range:
$ nc -vnzu 10.110.10.52 4950-5010
In this tutorial I explained some netcat usage examples. Of course you always can find more information in netcat man pages:
$ man netcat
or
$ info netcat