How to Check Open Ports in Linux?

General Linux Topic

March 16, 2023 by Liosa F

how to check open ports in linux

One of the tasks of Linux users or administrators is to know the open ports of the Linux system to avoid security problems. Open ports are network ports that are ready to receive packets from outside connections. Open ports are vulnerable to infiltration and attacks by attackers; therefore, it is very useful to check port use Linux constantly. Linux administrators in different situations should be aware of the ports in use or assigned to different services such as Nginx web servers or SSH or firewalls so that they can quickly detect intrusions and potential security holes and prevent Linux server security problems and unwanted traffic by closing ports. In addition to troubleshooting server problems, it makes it easier for administrators to check open ports in Linux and assign ports to new services.

Checking ports in Linux is one of the other security measures after buying a Linux VPS to secure your Linux server. Linux VPS administrators should be familiar with check port is open or not in Linux. This article aims to teach you how to check open ports in Linux through the command line to familiarize you with the commands that you can use to identify the open ports. In this article, you will learn about the following commands to view and check open ports in Linux:

  • ss  command to display open TCP and UDP ports
  • lsof command to list open ports Linux
  • netstat command to display a list of all ports on Linux
  • nmap command to display UDP and TCP ports
  • netcat command to check open Linux ports

Read this article to the end to secure your Linux server.

What is an open port?

The port consists of a string of numbers between 0 and 65535. A listening port is a network port where a program listens and this port is ready to receive remote packets. For example, when you use a web server such as Nginx or Apache, the web server is obliged to handle the request of the user who is looking for a specific website in the browser.

As a result, to handle the user request, a port (eg port 80) is opened for the web server service and the Internet, and anyone (except blocked IPSs) can access websites hosted on a web server using their browser, therefore, port 80 is the open port that the Linux system administrator must be aware of when these ports are open. Open ports are potential security holes that can be attacked by attackers. The Linux system administrator should identify the ports needed for critical services and close other ports.

You can use theCatandgrepcommands to view the port numbers of programs and the mapping of different services:

cat /etc/services

grep -w '80/tcp' /etc/services

grep -w '443/tcp' /etc/services

grep -E -w '22/(tcp|udp)' /etc/services

You can get a list of Linux listening ports on your system by querying the network stack with commands such as ss, netstat or lsof.

1. Finding open ports in Linux using ss command

The ss command is one of the commands that Linux show listening ports information along with their connection networks. To find listening ports in Linux and get more information about them, you can use the ss command with different options. The basic syntax of thesscommand is as follows:

sudo ss -tulpn

If you want your output to be organized and provide more relevant but concise information, you should run thesscommand with the-ltnflag:

sudo ss -ltn

Output:

State      Recv-Q     Send-Q         Local Address:Port            Peer Address:Port     Process
LISTEN     0          4096           127.0.0.53%lo:53                   0.0.0.0:*
LISTEN     0          5                  127.0.0.1:631                  0.0.0.0:*
LISTEN     0          70                 127.0.0.1:33060                0.0.0.0:*
LISTEN     0          151                127.0.0.1:3306                 0.0.0.0:*
LISTEN     0          5                      [::1]:631                     [::]:*
LISTEN     0          511                        *:80                         *:*

In the sample output that you see, ports number 80, 3306, and 33060 are ports that HTTP and MySQL services use, and most Linux users are familiar with these ports.

Other connections on the server are in listening status on the designated ports. If this information is not enough for you and you need to know which open ports belong to which processes, you can run the -p option along with the ss command:

sudo ss -ltnp

Output:

State    Recv-Q   Send-Q      Local Address:Port        Peer Address:Port   Process
LISTEN   0        4096        127.0.0.53%lo:53               0.0.0.0:*       users:(("systemd-resolve",pid=530,fd=13))
LISTEN   0        5               127.0.0.1:631              0.0.0.0:*       users:(("cupsd",pid=572,fd=7))
LISTEN   0        70              127.0.0.1:33060            0.0.0.0:*       users:(("mysqld",pid=2320,fd=32))
LISTEN   0        151             127.0.0.1:3306             0.0.0.0:*       users:(("mysqld",pid=2320,fd=34))
LISTEN   0        5                   [::1]:631                 [::]:*       users:(("cupsd",pid=572,fd=6))
LISTEN   0        511                     *:80                     *:*       users:(("apache2",pid=2728,fd=4),("apache2",pid=2727,fd=4),("apache2",pid=2725,fd=4))

In the output of this command, it is determined which ports belong to mysqld, systemd-resolve, cupsd, and apache2 processes.

You can also use other options along with the ss command, such as:

  • -l option: show listening ports
  • -lt option: show listening TCP ports
  • -tul option: Access a list of TCP and UDP listening ports
  • -n option: to access the listening port of the specified service

It should be noted that you can also use the following command to get more detailed information about the ports that are listening for incoming connections:

ss -tuln | grep LISTEN

2. Checking open ports in Linux using nmap command

Nmap is an open-source network scanning and security auditing program. Using the nmap tool, you can search the network and identify the open ports on the remote local host. Previously, we taught in detail how to use the nmap command to scan open ports in another article. We will also mention it in this article.

To scan the open ports in the Local Host using thenmapcommand, you can enter the IP address of the remote system and you can also specify your system as the LocalHost. Pay attention to the following example:

sudo nmap -sT -O localhost

sudo nmap -sU -O 192.168.2.254 ##[ list open UDP ports ]##

sudo nmap -sT -O 127.0.0.1 ##[ list open TCP ports ]##

sudo nmap -sTU -O 192.168.2.24

Sample output:

Starting Nmap 7.70 ( https://nmap.org ) at 2023-03-09 23:49 IST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00024s latency).
Other addresses for localhost (not scanned): ::1
Not shown: 998 closed ports
PORT    STATE SERVICE
22/tcp  open  ssh
631/tcp open  ipp
Device type: general purpose
Running: Linux 2.6.X
OS CPE: cpe:/o:linux:linux_kernel:2.6.32
OS details: Linux 2.6.32
Network Distance: 0 hops

OS detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 2.31 seconds

3. Linux list open ports using lsof command

you can use thelsofcommand to find processes that users have run and access open TCP and UDP ports by runninglsofcommand.

Along with thelsofcommand, you can also run different options for different purposes, as follows:

  • -i option: If you don’t have access to the IP address, this command will help you to view information about all network files.
  • -p option: If you have a problem searching for the port name, you can use this option because it prevents the conversion of the port number of the network files into the port name.
  • -n option: This option is useful when you don’t want to use the DNS name and it prevents the network number from converting the hostname of the network files.
  • | grep LISTEN: organizes the output to show ports in LISTEN state.

The main syntax of this command is as follows:

sudo lsof -i -P -n

In the output of this command, you will see a list of open ports in Linux. But this command has a drawback in that sometimes it displays ports that are not actually open. To access the ports that are currently actively listening on your Linux system, we suggest the following command:

sudo lsof -i -P -n | grep LISTEN

4. Linux check open ports using netstat command

One of the useful commands for finding open ports is thenetstatcommand, which displays the open ports in a list format. The basic syntax of this command to list open ports is as follows:

sudo netstat -tulpn | grep LISTEN

Other options for different purposes can be executed with thenetstatcommand, including the following:

  • -t: Display all TCP ports
  • -u: Display all UDP ports
  • -I: providing listening server sockets
  • -P: Show PID and names of sockets programs
  • -n: It is executed so that the names are not resolved
  • | grep LISTEN: Filter the output to display open ports in LISTEN status using the grep command

5. Finding Open Ports in Linux using netcat command

By executing thenetcatcommand with the help of TCP and UDP protocols, the user is able to write and read data between computers, the main syntax of this command is as follows:

nc [options] host port

The netcat command, along with other options, will have different meanings. We will explain how to find open ports through its options below:

  • nifty -z: finding listening daemons without sending data to the port
  • -v: getting more information and activating verbosity

You can also use the following command to scan open ports:

nc -z -v <IP-ADDRESS> 1-65535 2>&1 | grep -v 'Connection refused'

Replace the IP-ADDRESS in the above command with the IP Address of the Linux system you want to find open ports.

As a result, by running the previous command, you will see open and accessible ports on your Linux system.

Show open ports linux using Powershell

Powershell provides the ability to test network connections (Test-NetConnection) using the built-in cmdlet, but Powershell is a command line shell that is used in the Windows environment because other operating systems do not support this cmdlet. Powershell usually does not support built-in commands for Linux-specific operations. But by using TcpClient class, you can also use PowerShell features in Linux to check the listening ports and open connections.

The “Get-NetTCPConnection” cmdlet is a method with the same functionality as the netstat command in Linux to get a list of open TCP ports in Powershell, which supports various parameters to make accessing open ports easier using Powershell.

To access a list of listening ports using the “Get-NetTCPConnection” command, run the following command:

Get-NetTCPConnection -State Listen

As a result, all listening ports are displayed.

In addition, you can run Powershell by running the following command:

Pwsh

Then create a file with your favorite text editor (we prefer the nano editor):

nano Test-Port.ps1

We created a file called Test-port.ps1.

Then add the following commands in the file you just created using the editor of your choice:

<#
                .SYNOPSIS
                                This function tests for open TCP/UDP ports.
                .DESCRIPTION
                                This function tests any TCP/UDP port to see if it's open or closed.
                .NOTES
                .PARAMETER Computername
                                One or more remote, comma-separated computer names
                .PARAMETER Port
                                One or more comma-separated port numbers you'd like to test.
                .PARAMETER TcpTimeout
                                The number of milliseconds that the function will wait until declaring
                                the TCP port closed. Default is 1000.
                .EXAMPLE
                                PS> Test-Port -Computername 'LABDC','LABDC2' -Protocol TCP 80,443
                               
                                This example tests the TCP network ports 80 and 443 on both the LABDC
                                and LABDC2 servers.
                #>
[CmdletBinding()]
[OutputType([System.Management.Automation.PSCustomObject])]
param (
    [Parameter(Mandatory)]
    [string[]]$ComputerName,
    [Parameter(Mandatory)]
    [int[]]$Port,
    [Parameter()]
    [int]$TcpTimeout = 1000
)
begin {
    $Protocol = 'TCP'
}
process {
    foreach ($Computer in $ComputerName) {
        foreach ($Portx in $Port) {           
            $Output = @{ 'Computername' = $Computer; 'Port' = $Portx; 'Protocol' = $Protocol; 'Result' = '' }
            Write-Verbose "$($MyInvocation.MyCommand.Name) - Beginning port test on '$Computer' on port '$Protocol<code>:$Portx'"
            $TcpClient = New-Object System.Net.Sockets.TcpClient
            $Connect = $TcpClient.BeginConnect($Computer, $Portx, $null, $null)
            $Wait = $Connect.AsyncWaitHandle.WaitOne($TcpTimeout, $false)
            if (!$Wait -or !($TcpClient.Connected)) {
                $TcpClient.Close()
                Write-Verbose "$($MyInvocation.MyCommand.Name) - '$Computer' failed port test on port '$Protocol</code>:$Portx'"
                $Output.Result = $false
            }
            else {
                $TcpClient.EndConnect($Connect)
                $TcpClient.Close()
                Write-Verbose "$($MyInvocation.MyCommand.Name) - '$Computer' passed port test on port '$Protocol<code>:$Portx'"
                $Output.Result = $true
                $TcpClient.Close()
                $TcpClient.Dispose()
            }
            [pscustomobject]$Output
        }
    }
}

Finally, save your changes to the Test-Port.ps1 scrip and exit the editor.

To check whether the ports you want are open, for example, checking ports 80, 22, and 443, use the following example:

./Test-Port.ps1 -ComputerName localhost -Port 22,80,443

The output of the previous command will list the status of your specified ports.

How to check open ports in Linux through UFW Linux firewall

Up to this part of the article, you learned how to access a list of open ports in the Linux system using various commands, but some ports in your system may be blocked by the firewall and other software, and all the open ports you see in the list may not be open to the Internet.

Therefore, you must know the rules of the firewall in order to correctly identify the open and blocked ports. You can use the following command to find out about the state of the firewall regarding the blocking of input and output access:

 sudo ufw status verbose

Sample OutPut:

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

In this output, you can see that incoming connections are blocked by the firewall, and Incoming MySQL and HTTP connections with ports 80 and 3306 are not allowed in the firewall rules, while these ports may be displayed as open ports by executing the 5 commands we taught.

You can also access the list of configured firewall rules on the Linux server by running the following command:

sudo iptables -S
# IPv6 #
sudo ip6tables -S

How to block open ports in Linux

After checking the open ports, you can close the vulnerable ports. For this purpose, you should identify the services that allowed the ports to listen on the Linux server and stop them. To find the service name, enter the following command:

sudo ss -tulnp | grep LISTEN

After seeing the service name and the open port that you receive in the output, you can stop the desired service by executing the following command (for example, if the apache service is active):

sudo systemctl stop apache

This service may be activated automatically with every boot, so you can disable the Apache service by running the following command:

sudo systemctl disable apache

In addition to stopping the desired service, you must make changes in the firewall rules and block the port used by the Apache service in the UFW firewall. To configure the firewall to block ports, first find out about the firewall status:

sudo ufw status

Sample Output:

Status: active
To                                  Action              From
--                                ------------      ---------
Apache HTTP                         Allow                Anywhere
1                                   DENY                 Anywhere
2                                   DENY                 Anywhere
Apache HTTP(v6)                     ALLOW                Anywhere(v6)
1(v6)                               DENY                 Anywhere(v6)
2(v6)                               DENY                 Anywhere(v6)

In this output, you can see the status of the firewall as Active. If the firewall status was inactive, you can activate it by running the following command:

sudo ufw enable

Then, in the list that you received in the output of thesudo ufw statuscommand, you must set the Deny option for the desired port that you intend to block. In our example, Apache uses port 80, therefore, to set rules in the firewall based on denying port 80, enter the following command:

sudo ufw deny 80

Output:

Rule added
Rule added(v6)

finally, port 80 is blocked in the firewall.

FAQ

A port is a string of numbers between 0 and 65535, which the Linux operating system usually uses a port in the range of 0 to 1023.

By executing the commandsudo netstat -ano -p tcp, you can check the status of the port and find the TCP port and write down its PID number.

By executing the command "netstat -a -n -o | find "8080" you will get a list of processes that use port 8080.

You can scan the port using the free and open-source Nmap tool.

The netstat and ss commands are two common commands for checking open ports, including UDP and TCP ports, which will display port numbers, listening sockets, PIDs, and application socket names using various parameters.

Conclusion

In this article, you have learned about different commands for checking open ports in Linux and learned how to check listening ports in the UFW firewall. Viewing and checking open ports is helpful for identifying vulnerable ports in Linux server protection.

The listening and authorized port in the firewall provides access to your Linux system, so the Linux server administrator has to learn to check the open ports on the Linux system to improve security. After checking the open ports in Linux, the Linux system administrator should be able to close the unwanted and vulnerable ports and configure the firewall to block the ports to prevent security risks.

In this tutorial, we provided the desired commands to check the open ports and taught how to close the open ports. The most efficient and fastest way to check open ports is to use the lsof command, but you must have a user account with sudo privileges and log in to your system to be able to see open ports through this command. We hope this article has made you an expert in improving Linux security.

Thank you for reading this article to the end.

Rate this docs

Helpful

​ ​ ​ ​

About the Author Liosa F

Love, life, peace and technology are all for the wise man

Leave a Reply

Your email address will not be published. Required fields are marked *

Logan July 24, 2023 at 6:14 am

Is there a graphical port checker Linux?

    Liosa F July 24, 2023 at 6:14 am

    Yes, "nmap" is one popular and powerful network scanning and port checking tool with both command line and graphical interfaces.

Dylan July 20, 2023 at 4:28 am

how can we achieve linux list open ports?

    Liosa F July 20, 2023 at 4:29 am

    As we taught in the article, you can get a list of open Linux ports using netstat, ss, lsof, nmap and iptables commands.

Carol June 24, 2023 at 3:55 am

how to check which ports are open in linux

    Liosa F June 24, 2023 at 4:04 am

    There are various commands, including netstat, ss, lsof, etc., to check ports in use Linux, but the nmap command is one of the most common and powerful tools for network scanning that identifies open ports in a Linux system. By reading this article, you will get to know the valuable commands for checking open ports in Linux.