- How to check if port is in use on Linux or Unix
- How to check if port is in use in
- Option #1: lsof command
- Option #2: netstat command
- Linux netstat syntax
- FreeBSD/MacOS X netstat syntax
- OpenBSD netstat syntax
- Option #3: nmap command
- A note about Windows users
- Conclusion
- Как посмотреть все открытые и свободные порты в Linux ssh?
- Мне нужно узнать ОТКРЫТЫЕ и СВОБОДНЫЕ порты на линуксе, чего не понятного?
- Отвечаю
- Freeing up a TCP/IP port?
- 11 Answers 11
- What’s the easiest way to find an unused local port?
- 17 Answers 17
- One-liner
- Line by line
- Example
- Easy Steps to List All Open Linux Ports
- Linux System Ports
- Linux User Ports
- Linux Private Ports
- The netstat or network statistics command
- Retrieving a list of all TCP and UDP ports which are currently listening
- To list all the connections that are listening
- Display ports that are open, alongside current TCP connections
- A list of open UDP ports
- Get a list of your Linux services which are listening on TCP and UDP, a list of the open ports on your machine which are free, alongside the name and the PID of the service or program
- nmap – the Network Mapper command
- Scanning for open ports on a domain
- List of ports that are listening for connections via TCP
- List of ports that are listening for connections via UDP
- Look at a specific port (instead of all ports)
- Scan every open port on both TCP and UDP
- The lsof (List Open Files) command
- Listing all active network connections
- Find a process that is using a specified port
- Get a list of all the UDP and TCP connections
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:
- Open a terminal application i.e. shell prompt.
- 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 - 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 ssh?
Как посмотреть все открытые и свободные порты в Linux ssh?
Как посмотреть все открытые и свободные порты в Linux ssh?
переформулируй вопрос используя русский язык.
Мне нужно узнать ОТКРЫТЫЕ и СВОБОДНЫЕ порты на линуксе, чего не понятного?
Мне нужно узнать ОТКРЫТЫЕ и СВОБОДНЫЕ порты на линуксе, чего не понятного?
Отвечаю
У меня на машине много занятых портов, есть ли такая команда которая выводит все ОТКРЫТЫЕ и СВОБОДНЫЕ(т.е порт не занет не какие приложение) порты!
Выражайтесь яснее, сударь.
Причём здесь этот протокол?
sudo apt-get install nmap ; nmap localhost
Команда netstat — список портов, на которых кто-то «висит». Ну а диапазон портов которые могут использоваться очень большой, так что не думаю, что вы его весь использовали.
У меня на машине много занятых портов, есть ли такая команда которая выводит все ОТКРЫТЫЕ и СВОБОДНЫЕ(т.е порт не занет не какие приложение) порты!
выводит все ЗАНЯТЫЕ. Остальные свободные. А открытые см. в iptables-save или iptables -L.
Ну а диапазон портов которые могут использоваться очень большой
Это сколько? Хотя бы порядок назови. Сотни? Тысячи? Десятки тысяч?
Мне нужно узнать ОТКРЫТЫЕ и СВОБОДНЫЕ порты на линуксе, чего не понятного?
Просто посмотри лицензию на каждый порт и сравни со списками открытых и свободных лицензий.
как уже советовали netstat -at4np список открытых TCP портов в данный момент с указанием приложения
все остальные из диапазона 0-65535 свободны
Источник
Freeing up a TCP/IP port?
netstat -tulnap shows me what ports are in use. How to free up a port in Linux?
11 Answers 11
As the others have said, you’ll have to kill all processes that are listening on that port. The easiest way to do that would be to use the fuser(1) command. For example, to see all of the processes listening for http requests on port 80 (run as root or use sudo):
If you want to kill them, then just add the -k option.
To a kill a specific port in Linux use below command
replace Port_Number with your occupied port.
In terminal type :
netstat -anp|grep «port_number»
It will show the port details. Go to last column. It will be in this format . For example :- PID/java
kill -9 PID. Worked on Centos5
and then execute :
Worked on Macbook
You can use tcpkill (part of the dsniff package) to kill the connection that’s on the port you need:
To check all ports:
To close an open port:
In both cases you can use the sudo command if needed.
The «netstat —programs» command will give you the process information, assuming you’re the root user. Then you will have to kill the «offending» process which may well start up again just to annoy you.
Depending on what you’re actually trying to achieve, solutions to that problem will vary based on the processes holding those ports. For example, you may need to disable services (assuming they’re unneeded) or configure them to use a different port (if you do need them but you need that port more).
Kill the process that is listening to the port in question. I believe netstat shows you process ids.
the last column has the process
If you really want to kill a process immediately, you send it a KILL signal instead of a TERM signal (the latter a request to stop, the first will take effect immediately without any cleanup). It is easy to do:
Be aware however that depending on the program you are stopping, its state may get badly corrupted when doing so. You normally only want to send a KILL signal when normal termination does not work. I’m wondering what the underlying problem is that you try to solve and whether killing is the right solution.
I think the only way will be to stop the process which has opened the port.
sudo killall -9 «process name»
Shutting down the computer always kills the process for me.
Источник
What’s the easiest way to find an unused local port?
What’s the easiest way to find an unused local port?
Currently I’m using something similar to this:
It feels awfully roundabout, so I’m wondering if there’s a more simple path such as a builtin that I’ve missed.
17 Answers 17
My solution is to bind to port 0, which asks the kernel to allocate a port from it’s ip_local_port_range. Then, close the socket and use that port number in your configuration.
This works because the kernel doesn’t seem to reuse port numbers until it absolutely has to. Subsequent binds to port 0 will allocate a different port number. Python code:
This gives just a number of a port, eg. 60123 .
Run this program 10 000 times (you should run these concurrently), and you’ll get 10 000 different port numbers. Therefore, I think it’s pretty safe to use the ports.
If your application supports it, you can try passing port 0 to the application. If your application passes this to the kernel, the port will be dynamically allocated at request time, and is guaranteed not to be in use (allocation will fail if all ports are already in use).
Otherwise, you can do this manually. The script in your answer has a race condition, the only way to avoid it is to atomically check if it is open by trying to open it. If the port is in use, the program should quit with a failure to open the port.
For example, say you’re trying to listen with GNU netcat.
One-liner
I’ve put together a nice one-liner that quickly serves the purpose, allowing to grab an arbitrary number of ports in an arbitrary range (here it’s divided in 4 lines for readability):
Line by line
comm is a utility that compares lines in two files that must appear sorted alphabetically. It outputs three columns: lines that appear only in the first file, lines that only appear in the second one and common lines. By specifying -23 we suppress the latter columns and only keep the first one. We can use this to obtain the difference of two sets, expressed as a sequence of text lines. I learned about comm here.
The first file is the range of ports that we can select from. seq produces a sorted sequence of numbers from $FROM to $TO . The result is sorted alphabetically (instead of numerically, in order to comply with comm s requirement) and piped to comm as the first file using process substitution.
The second file is the sorted list of ports, that we obtain by calling the ss command (with -t meaning TCP ports, -a meaning all — established and listening — and -n numeric — don’t try to resolve, say, 22 to ssh ). We then pick only the fourth column with awk , which contains the local address and port. We use cut to split address and port with the : delimiter and keep only the latter ( -f2 ). We then comply with comm ‘s requirement by sort ing without duplicates -u .
Now we have a sorted list of open ports, that we can shuf fle to then grab the first «$HOWMANY» ones with head -n .
Example
Grab the three random open ports in the private range (49152-65535)
Источник
Easy Steps to List All Open Linux Ports
If you wanted to know what you need to do to list all of the open ports in a Linux instance you’ve come to the right place. But, what is a port and why would you want to have a list of all the open ports?
In short, a port is an access point that an operating system makes available so that it can facilitate network traffic with other devices or servers, while also differentiating the traffic in order to understand what service or app the traffic is being sent to.
There are two common protocols when it comes to ports: TCP, or the transmission control protocol; and of course, UDP – the user datagram protocol. Each of these protocols have a range of port numbers which is commonly classified into three groups:
Linux System Ports
Also known as “well-known” ports. These are port numbers from 0 to 1023 which are considered important for typical system use, commonly these ports are considered quite critical for ensuring ongoing communications services.
Linux User Ports
Also know as “registered ports” which range from 1024 to 49151. It is possible to send a request to the Internet Assigned Numbers Authority (IANA) to request retention of one of these ports for your application.
Linux Private Ports
Also known as “dynamic ports” range from 49152 to 65535. These ports are open for whatever use case you deem privately necessary and so are dynamic in nature – they are not fixed to specific applications.
Now, even though many ports have specific uses, it is important to keep an eye on ports which are “open” without the need for that port to be open. This is because ports that are unnecessarily left open can be a security risk – and also a sign that an intrusion is actively occurring.
Understanding which ports are open and “listening” for communications is therefore absolutely crucial to ensuring that you block efforts to break into your systems. Of course, some common ports need to be left open in order to facilitate ordinary internet communications. For example:
- FTP (the file transfer protocol) uses port 20 for data transfers
- Likewise, FTP uses port 21 to issue commands and to control the FTP session
- Port 22 is dedicated to SSH, or secure shell login
- Telnet uses port 23 to facilitate remote logins but this port entails unencrypted messaging which is not secure so it’s not really recommended for use
- E-mail routing via SMTP (the simple mail transfer protocol) is achieved on port 25
- Port 43 is dedicated to the WHOIS system which can check who owns a domain
- The domain name service (DNS) makes use of port 53
- DHCP uses port 67 as the server port, and port 68 as the client port
- HTTP, the hypertext transfer protocol, uses port 80 to deliver web pages
- POP3, the e-mail centric “post office protocol” uses port 110
- Port 119 is used by the news transfer protocol, NNTP
- The network time protocol, NTP, uses port 123
- IMAP, another email protocol, makes use of port 143 to retrieve email messages
- SNP or the simple network management protocol uses port 161
- Port 194 is dedicated to IRC, the internet relay chat app
- Port 443 is dedicated to HTTPS, the secure version of HTTP delivered over TLS/SSL
- SMTP, the simple mail transfer protocol, uses port 587 to submit emails
It is often possible to configure a specific service to use a port which is not the standard port, but this configuration needs to be made on both the sender and recipient side – in other words, on both client and server. Otherwise if only one side uses a non-standard port configuration communication won’t be possible.
How do you get a simple list of common ports that are open? Use this command:
Alternatively, you can modify the size of the list you get by adding “less” to your command
$ cat /etc/services | less
However, you can use a range of other commands on a Linux machine which will give you all the TCP and the UDP ports which are open and ready to receive communication from other machines. We will cover three in the following section – Isof, netstat and nmap.
The netstat or network statistics command
Most Linux distributions will include netstat by default, in their installations. It’s a really capable tool which can display all the TCP/IDP network connections that are active – both for incoming connections, and outgoing connections. It also displays routing tables plus the number of the network interface alongside comprehensive statistics for network protocols.
So, you can use netstat to troubleshoot and to measure the performance of your network. While basic, it is a useful and essential too for finding faults in network services. It clearly tells you which ports are open, and where a program or service is listening on a specific port. We will now give you some examples on how to make use of netstat.
Retrieving a list of all TCP and UDP ports which are currently listening
It’s simple really, just use the -a flag alongside a pipe that specifies less, this will give you TCP and UDP ports which are currently listening
$ netstat -a | less
To list all the connections that are listening
Make use of the -l flag in the netstat command to get a list of every port connection which is actively listening
Display ports that are open, alongside current TCP connections
Here, we combine a couple of flags in order to show a list of ports which are open and the established (TCP) connections.
A list of open UDP ports
You might only want to see the UDP ports which are open, excluding the open TCP ports. The command you need is this:
Get a list of your Linux services which are listening on TCP and UDP, a list of the open ports on your machine which are free, alongside the name and the PID of the service or program
This command gives you all the services and apps which listen on either TCP or UDP. It also gives you the open ports on your Linux instance which are free, plus the program name and process ID that is associated with every open socket.
So you can see how the different commands you can use with netstat makes it very versatile, allowing you to see what the status quo is on your Linux machine. But what exactly does these individual flags mean? It’s simple really:
- -a will show all sockets that are listening and all non-listening sockets too
- -l only shows ports which are actively listening
- -v means “verbose” and tells netstat to include additional information about any address families that are not currently configured
- -t restricts the listing to TCP connections only
- -u restricts the listing to UDP connections only
- -n tells netstat to display the numerical addresses too
- -p adds the process ID (PID) as well as the name of the program
Keep in mind that the seven flags we’ve shown above are just a couple of the many flags you can specify for netstat. Check out the help file by triggering
You’ll get a full listing of all the options and features you can make use of with netstat.
nmap – the Network Mapper command
An open source tool, nmap is great for exploring your network, scanning it for security vulnerabilities and to audit your network. That said, new users might find nmap challenging to use because it is so feature-rich: nmap comes with so many options that you might find it difficult to figure out, even if it does mean it is a very robust tool.
It’s worth remembering that nmap will deliver very extensive information about the network that it is scanning. So, do not use nmap on a network unless you have permission to examine it – permission to scan it, basically. You need to have a reason to use nmap, in other words, and the permission of the network owner.
We will now give you a basic overview of nmap including typical usage of the map command. To start off with, here is the instructions you need to install nmap if you have Ubuntu or Debian server:
$ sudo apt-get install nmap
The command is slightly different if you’re using RHEL or CentOS:
$ sudo yum install nmap
There’s a file you can view for a wider picture of ports and services. Use this command:
It’s an example of exactly how extensive the details are when you use nmap as a tool. If you want to experiment with nmap you could try to check out your own virtual private server, but you could also give nmap a go on the official nmap test server – located at scanme.nmap.org.
In order to try out some basic nmap commands we will make use of sudo privileges to ensure that the queries give complete results – not partial results. Remember, some nmap commands will take a little bit longer to execute.
Throughout these examples we will make use of mywebsite.com as the example domain; replace your actual domain in place of mywebsite.com when you run this command.
Scanning for open ports on a domain
$ sudo nmap -vv mywebsite.com
Here you can see we have used the -vv flag, which has a specific function. When you use -vv it means “verbose”, in other words it will show you extensive output, including the process as nmap scans for open ports. Leave out the -vv flag and you will quickly see the difference.
List of ports that are listening for connections via TCP
$ sudo nmap -sT mywebsite.com
You’ll note the -sT flag, this is usually what you’d specify to scan for TCP connections when a SYN scan cannot be performed.
List of ports that are listening for connections via UDP
$ sudo nmap -sU mywebsite.com
So, -sU is what you use to get a UDP scan. However you can scan for both UDP and TCP connections by using another flag, -sS. You’ll get a list covering both UDP and TCP.
Look at a specific port (instead of all ports)
$ sudo nmap -p port_number mywebsite.com
In this case, -p means that you only look at the port number specified in place of “port_number”.
Scan every open port on both TCP and UDP
$ sudo nmap -n -Pn -sT -sU -p- mywebsite.com
We use two flags here: first -n which specified to nmap that it must not make a reverse domain resolution for an active IP address, where it finds one. -Pn disables pinging, treating all of the hosts as if they are online.
It’s just a few examples but nmap is a really fantastic tool than can help you a lot. Remember, typing $ man nmap will give you a full list of all the tools at your disposal; many of these are very useful for exploring the security of your network and to find potentially vulnerable points.
The lsof (List Open Files) command
It’s easy to remember what lsof means – the list open files command – just take ls as “list” and of as “open files” and you’ll clearly see why lsof means “list open files”.
Listing all active network connections
Use the -i flag with lsof in order to get a full list of every network connection which is both listening and established.
Find a process that is using a specified port
As an example, for all processes which are currently operating on port 22, you’ll run this command:
$ sudo lsof -i TCP:22
Get a list of all the UDP and TCP connections
To list every single UDP and TCP connection just use this command:
$ sudo lsof -i tcp; sudo lsof -i udp;
Just like with nmap, you can check the manual for lsof in order to get a full view of all the options you have when you are using lsof.
So, to wrap up, Linux fans must understand at least a little bit about ports – particularly if they plan on managing Linux servers. We’ve given three examples of great tools – nmap, lsof and netstat – which will help you on the way to understanding which ports are open on your machine, and which services are active on your server.
We suggest that you take a look at the man pages for each of these commands so that you can get a better idea of what they do. While these tools are great for checking the exposure on your own network, never abuse any of these tools by scanning networks that do not belong to you.
Источник