Port commands in linux

How to check if port is in use on Linux or Unix

H ow do I determine if a port is in use under Linux or Unix-like system? How can I verify which ports are listening on Linux server? How do I check if port is in use on Linux operating system using the CLI?

It is important you verify which ports are listening on the server’s network interfaces. You need to pay attention to open ports to detect an intrusion. Apart from an intrusion, for troubleshooting purposes, it may be necessary to check if a port is already in use by a different application on your servers. For example, you may install Apache and Nginx server on the same system. So it is necessary to know if Apache or Nginx is using TCP port # 80/443. This quick tutorial provides steps to use the netstat, nmap and lsof command to check the ports in use and view the application that is utilizing the port.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements lsof, ss, and netstat on Linux
Est. reading time 3 minutes

How to check if port is in use in

To check the listening ports and applications on Linux:

  1. Open a terminal application i.e. shell prompt.
  2. Run any one of the following command on Linux to see open ports:
    sudo lsof -i -P -n | grep LISTEN
    sudo netstat -tulpn | grep LISTEN
    sudo ss -tulpn | grep LISTEN
    sudo lsof -i:22 ## see a specific port such as 22 ##
    sudo nmap -sTU -O IP-address-Here
  3. For the latest version of Linux use the ss command. For example, ss -tulw

Let us see commands and its output in details.

Option #1: lsof command

The syntax is:
$ sudo lsof -i -P -n
$ sudo lsof -i -P -n | grep LISTEN
$ doas lsof -i -P -n | grep LISTEN ### [OpenBSD] ###
Sample outputs:

Fig.01: Check the listening ports and applications with lsof command

Option #2: netstat command

You can check the listening ports and applications with netstat as follows.

Linux netstat syntax

Run netstat command along with grep command to filter out port in LISTEN state:
$ netstat -tulpn | grep LISTEN
The netstat command deprecated for some time on Linux. Therefore, you need to use the ss command as follows:
sudo ss -tulw
sudo ss -tulwn
sudo ss -tulwn | grep LISTEN

Where, ss command options are as follows:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

  • -t : Show only TCP sockets on Linux
  • -u : Display only UDP sockets on Linux
  • -l : Show listening sockets. For example, TCP port 22 is opened by SSHD server.
  • -p : List process name that opened sockets
  • -n : Don’t resolve service names i.e. don’t use DNS

FreeBSD/MacOS X netstat syntax

$ netstat -anp tcp | grep LISTEN
$ netstat -anp udp | grep LISTEN

OpenBSD netstat syntax

$ netstat -na -f inet | grep LISTEN
$ netstat -nat | grep LISTEN

Option #3: nmap command

The syntax is:
$ sudo nmap -sT -O localhost
$ sudo nmap -sU -O 192.168.2.13 ##[ list open UDP ports ]##
$ sudo nmap -sT -O 192.168.2.13 ##[ list open TCP ports ]##
Sample outputs:

Fig.02: Determines which ports are listening for TCP connections using nmap

A note about Windows users

You can check port usage from Windows operating system using following command:
netstat -bano | more
netstat -bano | grep LISTENING
netstat -bano | findstr /R /C:»[LISTEING]»

Conclusion

This page explained command to determining if a port is in use on Linux or Unix-like server. For more information see the nmap command and lsof command page online here

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Linux Find Out Which Process Is Listening Upon a Port

Linux Find Out Which Process Is Listening Upon a Port

You can the following programs to find out about port numbers and its associated process:

  1. netstat command or ss command – a command-line tool that displays network connections, routing tables, and a number of network interface statistics.
  2. fuser command – a command line tool to identify processes using files or sockets.
  3. lsof command – a command line tool to list open files under Linux / UNIX to report a list of all open files and the processes that opened them.
  4. /proc/$pid/ file system – Under Linux /proc includes a directory for each running process (including kernel processes) at /proc/PID, containing information about that process, notably including the processes name that opened port.

You must run above command(s) as the root user.

Linux netstat command find out which process is listing upon a port

Type the following command:
# netstat -tulpn
Sample outputs:

TCP port 3306 was opened by mysqld process having PID # 1138. You can verify this using /proc, enter:
# ls -l /proc/1138/exe
Sample outputs:

You can use grep command or egrep command to filter out information:
# netstat -tulpn | grep :80
Sample outputs:

A note about ss command

Some Linux distro considered the nestat command as deprecated and therefore should be phased out in favor of more modern replacements such as ss command. The syntax is:
$ sudo ss -tulpn
$ sudo ss -tulpn | grep :3306

Click to enlarge image

Video demo

fuser command

Find out the processes PID that opened tcp port 7000, enter:
# fuser 7000/tcp
Sample outputs:

Finally, find out process name associated with PID # 3813, enter:
# ls -l /proc/3813/exe
Sample outputs:

/usr/bin/transmission is a bittorrent client, enter:
# man transmission
OR
# whatis transmission
Sample outputs:

Find Out Current Working Directory Of a Process

To find out current working directory of a process called bittorrent or pid 3813, enter:
# ls -l /proc/3813/cwd
Sample outputs:

OR use pwdx command, enter:
# pwdx 3813
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Find Out Owner Of a Process on Linux

Use the following command to find out the owner of a process PID called 3813:
# ps aux | grep 3813
OR
# ps aux | grep ‘[3]813’
Sample outputs:

OR try the following ps command:
# ps -eo pid,user,group,args,etime,lstart | grep ‘[3]813’
Sample outputs:

Another option is /proc/$PID/environ, enter:
# cat /proc/3813/environ
OR
# grep —color -w -a USER /proc/3813/environ
Sample outputs (note –colour option):

Fig.01: grep output

lsof Command Example

Type the command as follows:

Now, you get more information about pid # 1607 or 1616 and so on:
# ps aux | grep ‘[1]616’
Sample outputs:
www-data 1616 0.0 0.0 35816 3880 ? S 10:20 0:00 /usr/sbin/apache2 -k start
I recommend the following command to grab info about pid # 1616:
# ps -eo pid,user,group,args,etime,lstart | grep ‘[1]616’
Sample outputs:

  • 1616 : PID
  • www-date : User name (owner – EUID)
  • www-date : Group name (group – EGID)
  • /usr/sbin/apache2 -k start : The command name and its args
  • 03:16:22 : Elapsed time since the process was started, in the form [[dd-]hh:]mm:ss.
  • Fri Oct 29 10:20:17 2010 : Time the command started.

Help: I Discover an Open Port Which I Don’t Recognize At All

The file /etc/services is used to map port numbers and protocols to service names. Try matching port numbers:
$ grep port /etc/services
$ grep 443 /etc/services
Sample outputs:

Check For rootkit

I strongly recommend that you find out which processes are really running, especially servers connected to the high speed Internet access. You can look for rootkit which is a program designed to take fundamental control (in Linux / UNIX terms “root” access, in Windows terms “Administrator” access) of a computer system, without authorization by the system’s owners and legitimate managers. See how to detecting / checking rootkits under Linux.

Keep an Eye On Your Bandwidth Graphs

Usually, rooted servers are used to send a large number of spam or malware or DoS style attacks on other computers.

Conlcusion

You learned various Linux commands to find information about running process and their ports. See the following man pages for more information:
$ man ps
$ man grep
$ man lsof
$ man netstat
$ man fuser

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Linux find out which port is open using the command line

Linux find out which port is open using the command line

The procedure to list open ports in Linux is as follows:

  1. Open the terminal application
  2. Use command netstat -tulpn to open ports
  3. Another option is to run ss -tulpn to open ports on modern Linux distros

Let us see all commands in details.

Linux find port open command

One can use the netstat command or ss command find out which process is listing upon a port:
$ sudo netstat -tulpn
$ sudo netstat -tulpn | more
$ sudo netstat -tulpn | grep ‘:port’
$ sudo netstat -tulpn | grep ‘:22’
OR
$ sudo ss -tulpn
$ sudo ss -tulpn | more
$ sudo ss -tulpn | grep ‘:port’
$ sudo ss -tulpn | grep ‘:22’

Click to enlarge image

How to find out and list of all open TCP/UDP ports in Linux

Other commands that you can use are as follows.

fuser command examples to find out which port is open

One can list the processes PID that opened tcp port 22, enter:
$ sudo fuser 22/tcp
Sample outputs:

Let us see process name associated with PID # 1462, execute:
$ sudo ls -l /proc/1462/exe
Outputs:

/usr/sbin/sshd has opened tcp port 22. But, what is sshd? Let us find out:
$ whatis sshd
Example outputs:

How to use lsof command to display open port on Linux

$ sudo lsof -i :portNumber
$ sudo lsof -i tcp:portNumber
$ sudo lsof -i udp:portNumber
$ sudo lsof -i :22
$ sudo lsof -i :22 | grep LISTEN

Click to enlarge file

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Conclusion

You just learned how to list open ports on a Linux based system. For more info see man pages.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

14 Useful Linux Networking Commands

Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.

Configuring, monitoring, and securing networks form an essential part of a Sysadmin’s job. When it comes to managing Linux networks, there are many commands and utilities available.

At times networked systems fail. You as an administrator are required to diagnose and resolve issues. Monitoring helps in detecting problems and fixing them before things get out of hand. Monitoring for security and performance also forms an essential part of an admin’s activities.

Here we discuss some commonly used commands to manage Linux networks.

The iproute2 package includes the IP command which is used for network and routing configuration. This replaces the traditional ifconfig and route commands.

ip takes a second argument that specifies the object on which you wish to execute a command and an action like add, delete, or show.

ip link is for configuring, adding, and deleting network interfaces. Use ip link show command to display all network interfaces on the system :

You can see the man page for ip link with:

ip address

Use ip address command to display addresses, bind new address or delete old ones. The man page ip address command is named as ip-address.

For example, the following command shows the IP address assigned to the network interface enp0s8:

ip route

Use the IP route to print or display the routing table. The following command displays the contents of the routing table:

While Nmap had been used in many movies, The Matrix Reloaded ( Wikipedia , IMDB , Amazon ) turned Nmap into a movie star!.

Nmap (“Network Mapper”) is a powerful utility used for network discovery, security auditing, and administration. Many system admins use it to determine which of their systems are online, and also for OS detection and service detection.

The default Nmap scan shows the ports, their state (open/closed), and protocols. It sends a packet to 1000 most common ports and checks for the response.

To check which hosts on your network are up:

Use -O flag to identify which operating system a host is running.

A word of caution: Nobody appreciates their systems being scanned over the internet. So before you do so, seek permission.

You can also use Nmap on Windows, check out this installation guide.

Use ping to see if a host is alive. This super simple command helps you check the status of a host or a network segment. Ping command sends an ICMP ECHO_REQUEST packet to the target host and waits to see if it replies.

However, some hosts block ICMP echo requests with a firewall. Some sites on the internet may also do the same.

By default, ping runs in an infinite loop. To send a defined number of packets, use -c flag.

With -o flag ping exits successfully after receiving one reply packet.

You can use -n flag to avoid reverse DNS lookups. The ICMP sequence number is particularly important. A Break in sequence numbers indicates lost packets.

A failed ping could be due to

  • network failure
  • host being not alive
  • firewall blocking ICMP ECHO requests

You can also perform an online ping test to check the connectivity from different parts of the world.

iPerf

While ping verifies the availability of a host, iPerf helps analyze and measure network performance between two hosts. With iPerf, you open a connection between two hosts and send some data. iPerf then shows the bandwidth available between the two hosts.

You can install an iPerf using your distribution package manager. For example on Ubuntu-based distributions you can install like this:

Once you have installed iPerf on both the machines, start the iPerf server on one of them. The following example starts the iPerf server on a host with IP address 10.0.0.51.

On the second machine start iPerf with the -c flag. This connects with the server and sends some data.

iPerf returns with the bandwidth results in a few seconds.

traceroute

If ping shows missing packets, you should use traceroute to see what route the packets are taking. Traceroute shows the sequence of gateways through which the packets travel to reach their destination. For example, traceroute from my machine to google.com shows the following:

Line 4 in this output shows a * in the round trip times. This indicates no response was received. This can be due to many reasons – as the traceroute ICMP packets are low-priority, these may be dropped by a router. Or there could be simply congestion. If you see a * in all the time fields for a given gateway, then possibly the gateway is down.

Many web-based route tracing tools allow you to do a reverse traceroute, that is, from a website to your host. You can check these at traceroute.org or Geekflare Traceroute.

tcpdump

tcpdump is a packet sniffing tool and can be of great help when resolving network issues. It listens to the network traffic and prints packet information based on the criteria you define.

For example, you can examine all packets sent to or from a particular host, Ubuntu18 in this example:

By default, tcpdump resolves IP addresses to hostnames. Use -n flag, if you do not want tcpdump to perform name lookups.

tcpdump output prints one line for each packet. Use -c flag to limit output, 5 in the example above.

tcpdump is useful for solving network problems and also identifying potential problems. It is a good idea to run a tcpdump on your network occasionally to verify everything is in order.

netstat

Netstat command is used to examine network connections, routing tables, and various network settings and statistics.

Use -i flag to list the network interfaces on your system.

Here is an example:

Using -r flag will display the routing table. This shows the path configured for sending network packets.

An asterisk in the last two lines indicates that no gateway is required to send packets to any host on these networks. This host is directly connected to the networks 10.0.0.0 and 10.0.2.0.

In the first line, the destination is the default, which means any packet destined for a network not listed in this table is handled by the router 10.0.2,2.

netstat command without any options displays a list of open sockets. Use -l flag to show only listening sockets, which by default, are not shown. You can use -a flag to show listening and non-listening sockets. Here is an example:

More Netstat command example here

Linux installations have a lot of services running by default. These should be disabled or preferably removed, as this helps in reducing the attack surface. You can see what services are running with the netstat command. While netstat is still available, most Linux distributions are transitioning to ss command.

use ss command with -t and -a flags to list all TCP sockets. This displays both listening and non-listening sockets.

To display only TCP connections with state established:

ssh enables you to connect securely with remote hosts over the internet. Earlier rlogin and telnet were used to connect to and administer remote hosts. However, both suffer from a fundamental flaw, that is, they send all information including login names and passwords in cleartext.

ssh enables secure communication over the internet with the following two features :

  • It confirms that the remote host is, who it says it is.
  • It encrypts all communication between the hosts.

To connect to a remote host you need to have an OpenSSH server running on the remote host. You can install it using your distribution package manager. For example on Ubuntu you can install it like this:

Here is an example showing how you can connect to the remote host 10.0.0.50 using the ssh command:

You get a message saying that the authenticity of the host 10.0.0.50 cannot be established, this is because it’s the first time a connection is being made with 10.0.0.50 (server) and the ssh client has never seen this remote host before. Enter yes to continue connecting. Once the connection has been established, you are prompted for a password:

After you enter the correct password, you are logged into the remote host.

You can exit this remote shell with the exit command.

Also, you can easily execute a single command on the remote host using ssh. For example, to run df -h on the remote host:

scp and sftp

scp (secure copy) is very similar to cp command for copying files, with an addition – you can include remote hostnames in the source or destination pathnames. The hostname and the directory path are separated by a colon. This enables you to copy files securely over the network in an encrypted form. The following command copies a.txt from the local machine to 10.0.0.50 :

sftp (secure ftp) is also a file copy program similar to ftp . However, it uses an SSH encrypted tunnel to copy files, instead of sending everything in cleartext. Also, you do not need an FTP server running on the remote host. You only need an ssh server. Here is an example session:

Ifconfig

Mostly we use ifconfig command to check the IP address assigned to the system.

dig (Domain Information Groper) is a flexible tool for interrogating DNS name servers.

It performs DNS lookups and displays the answers that are returned from the name servers.

telnet

telnet connect destination’s host and port via a telnet protocol if a connection establishes means connectivity between two hosts is working fine.

nslookup

nslookup is a program to query domain name servers and resolving IP.

Summary

Networking in Linux is a vast subject, with a large number of commands and utilities. In this article, we have discussed some commonly used commands which hopefully, will help you in managing and securing your network.

Источник

Читайте также:  Windows 10 fall creators update rtm
Оцените статью