Monday, April 20, 2020

nc command examples in linux?

Netcat or nc is a networking utility for debugging and investigating the network.

This utility can be used for creating TCP/UDP connections and investigating them.
The biggest use of this utility is in the scripts where we need to deal with TCP/UDP sockets.

How to Install and Use Netcat in Linux
To install the netcat package on your system, use the default package manager for your
Linux distribution.

[On CentOS/RHEL]

$ yum install nc                  

 [On Fedora 22+ and RHEL 8]
$ dnf install nc                 

 [On Debian/Ubuntu]
$ sudo apt-get install Netcat    

Port Scanning

Netcat can be used for port scanning: to know which ports are open and running services on
a target machine. It can scan a single or multiple or a range of open ports.

 It may be useful to know which ports are open and running services on a target machine.
  The -z flag can be used to tell nc to report open ports, rather than initiate a connection.
Usually it's useful to turn on verbose output to stderr by use this option in conjunction with -
v    option.


    -v      Have nc give more verbose output.
    -w    timeout      Connections which cannot be established or are idle timeout after timeout
seconds.   The -w flag has no effect on the -l option, i.e. nc will listen forever for a connection, with or without the -w flag.  The default is no timeout.

    -z      Specifies that nc should just scan for listening daemons, without sending any data
to them.  It is an error to use this option in con‐junction with the -l option.

  -n      Do not do any DNS or service lookups on any specified addresses, hostnames or

  #scan a single port
$ nc -v -w 2 z 22   

 nc -v -w 2 -z 22 
 Connection to 22 port [tcp/ssh] succeeded!

#scan multiple ports

$ nc -v -w 2 z 22 80  

 #scan range of ports

$ nc -v -w 2 z 20-22 

nc -v -w 2 -z 20-22
nc: connect to port 20 (tcp) failed: Connection refused
nc: connect to port 21 (tcp) failed: Connection refused
Connection to 22 port [tcp/ssh] succeeded!

Find a Service Running on Port

You can also use Netcat to obtain port banners. In this case, it will tell you what service is
running behind a certain port. For example to know what type of service is running behind
port 22 on a specific server, run the following command

nc -v -n 22
Connection to 22 port [tcp/*] succeeded!
SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.7

No comments:

Post a Comment