Check busy ports linux

Linux command get unused port

I’m looking for a command or script which returns an unused port on my ubuntu linux system. I have look on internet and the only thing I find is about the used/Listen port with the nestat command. Apparently something with the netstat command will work but don’t know what exactly. Any idea how? Thanks.

Why do you need to do that exactly? If you are developing a server, you can bind to port 0 and the OS will allocate a free port for you, you have nothing to search. Otherwise searching and then binding is prone to race conditions. See for example stackoverflow.com/questions/1365265/… or stackoverflow.com/questions/1075399/…

10 Answers 10

netstat -lat gives the complete list of listening and established ports.

When a port is not on any of those states doesn’t exist for the system, so you won’t find a command that shows the list of unused ports.

Keep in mind that there are 65535 ports, so anything that isn’t on netstat -lat is an unused port.

The following bash script will do a simple scan of tcp ports, and let you know which are open and which are closed :

#!/bin/bash IP=$1 first_port=$2 last_port=$3 function scanner < for ((port=$first_port; port/dev/tcp/$IP/$port)> /dev/null 2>&1 && echo $port open || echo "$port closed" done > scanner 

If you save it as portscan.sh then it must be run as ./portscan.sh IP first_port last_port, for example: ./portscan.sh 127.0.0.1 20 135 will scan the local equipment from ports 20 to 135. Remember to make it executable with chmod +x portscan.sh .

ruby -e ‘require «socket»; puts Addrinfo.tcp(«», 0).bind <|s| s.local_address.ip_port >‘

On my machine right now that printed:

A subsequent invocation printed:

This technique causes the current user to request an unused port (bind to port «0»), and then prints out the port number that the operating system provided. And since the current user is the one asking, ports below 1024 will not be returned (unless current user = root).

Credit where credit’s due — this solution comes from a comment by Franklin Yu on unix.stackexchange.com’s What’s the easiest way to find an unused local port?

Short bash script that randomly generates a number between 1025 and 60000 and loops until that number isn’t found in the list of used ports. This is a quick ‘n dirty solution that has a bias to larger ports:

CHECK="do while" while [[ ! -z $CHECK ]]; do PORT=$(( ( RANDOM % 60000 ) + 1025 )) CHECK=$(sudo netstat -ap | grep $PORT) done echo $PORT 

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):

comm -23 \ <(seq "$FROM" "$TO") \ <(ss -tan | awk '' | cut -d':' -f2 | grep '2\' | sort -n | uniq) \ | shuf | head -n "$HOWMANY" 

Line by line

comm is a utility that compares sorted lines in two files. 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 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 ). ss also output an header, that we get rid of by grep ping for non-empty sequences of numbers that are no longer than 5. We then comply with comm ‘s requirement by sort ing numerically ( -n ) and getting rid of duplicates with uniq .

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)

comm -23 <(seq 49152 65535) <(ss -tan | awk '' | cut -d':' -f2 | grep "8\" | sort | uniq) | shuf | head -n 3 

Notes

  • switch -t with -u in ss to get free UDP ports instead.
  • drop shuf if you’re not interested in grabbing a random port

Источник

Проверка занятости порта сервисом в Linux

Oct 4, 2018 06:09 · 637 words · 3 minute read lsof netstat fuser tips

Однажды вам обязательно понадобится проверить используемый порт определенного сервиса (или наоборот, найти сервисы, слушающие конкретный порт) — в Linux существует несколько утилит командной строки, которые могут с этим помочь. Давайте разберемся!

Первым делом на ум приходит утилита netstat , с помощью которой можно проверить сетевые соединения, статистику сетевых интерфейсов, таблицу маршрутизации и т. д.

Устанавливается данная утилита в разных дистрибутивах по-разному, например, для RedHat и CentOS:

sudo yum install net-tools 
sudo apt-get install net-tools 

Для вывода детальной информации о всех TCP и UDP ендпоинтах можно воспользоваться следующей командой:

Вывод будет примерно следующим:

Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 1323/systemd-resolv tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1661/sshd tcp 0 0 127.0.0.1:17123 0.0.0.0:* LISTEN 1753/python tcp6 0 0 . 31341 . * LISTEN 30068/java tcp6 0 0 . 22222 . * LISTEN 30068/java tcp6 0 0 . 80 . * LISTEN 30068/java tcp6 0 0 . 10769 . * LISTEN 126755/docker-proxy tcp6 0 0 . 10770 . * LISTEN 129459/docker-proxy tcp6 0 0 . 10771 . * LISTEN 129540/docker-proxy tcp6 0 0 . 10772 . * LISTEN 130172/docker-proxy tcp6 0 0 . 10773 . * LISTEN 130187/docker-proxy tcp6 0 0 . 10774 . * LISTEN 130545/docker-proxy tcp6 0 0 . 22 . * LISTEN 1661/sshd tcp6 0 0 . 10775 . * LISTEN 7406/docker-proxy 
  • -p — вывод ID процесса и его имени;
  • -n — вывод адресов;
  • -l — вывод сокетов;
  • -t — вывод TCP соединений;
  • -u — вывод UDP соединений.

Найти сервис, запущенный на определенном порту можно так:

Аналогично можно найти на каком порту запущен определенный сервис:

netstat -pnltu | grep -i "sshd" 

Также для наших целей подойдет утилита командной строки fuser . По умолчанию она не установлена в большинстве операционных систем, чтобы установить ее в Centos/RedHat делаем так:

Например, чтобы найти идентификаторы процессов (PIDs), запущенных на 80-м порту, выполняем команду:

Результат выполнения будет примерно следующим:

Далее можем найти имя процесса по его идентификатору (PID):

Еще один способ — использование утилиты lsof . Установка ее в RedHat/CentOS выглядит так:

Вывод всех активных TCP и UPD соединений:

Результатом будет примерно следующее:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd-r 1323 systemd-resolve 12u IPv4 20197 0t0 UDP 127.0.0.53:domain systemd-r 1323 systemd-resolve 13u IPv4 20198 0t0 TCP 127.0.0.53:domain (LISTEN) sshd 1661 root 3u IPv4 29741 0t0 TCP *:ssh (LISTEN) sshd 1661 root 4u IPv6 29743 0t0 TCP *:ssh (LISTEN) python 1754 dd-agent 4u IPv6 39499 0t0 UDP localhost.localdomain:8125 docker-pr 7406 root 4u IPv6 287933991 0t0 TCP *:10775 (LISTEN) docker-pr 7459 root 4u IPv6 287906596 0t0 TCP *:10776 (LISTEN) docker-pr 7792 root 4u IPv6 287937795 0t0 TCP *:10777 (LISTEN) docker-pr 8435 root 4u IPv6 287955267 0t0 TCP *:10778 (LISTEN) docker-pr 8447 root 4u IPv6 287915222 0t0 TCP *:10779 (LISTEN) docker-pr 9060 root 4u IPv6 287891442 0t0 TCP *:10780 (LISTEN) docker-pr 9429 root 4u IPv6 287957044 0t0 TCP *:10781 (LISTEN) docker-pr 9463 root 4u IPv6 287921075 0t0 TCP *:10782 (LISTEN) ntpd 10594 ntp 16u IPv6 35365570 0t0 UDP *:ntp 

Проверить использование конкретного порта можно так:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME sshd 1661 root 3u IPv4 29741 0t0 TCP *:ssh (LISTEN) sshd 1661 root 4u IPv6 29743 0t0 TCP *:ssh (LISTEN) 

Напоследок можно также воспользоваться утилитой whatportis . Ее установка в RedHat/Centos требует чуть больше действий:

yum install python34-setuptools 

В Debian/Ubuntu все гораздо проще:

В общем виде использование утилиты выглядит так:

whatportis [номер_порта | имя_сервиса] 

Если вам неизвестно точное имя сервиса, можно воспользоваться опцией —like , например:

Также доступен вывод информации в json-формате:

Источник

How check port is busy in Linux?

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.
  3. For the latest version of Linux use the ss command. For example, ss -tulw.

How do I find unused ports in Linux?

How to check if a port is in use on Linux

  1. Open the terminal application on Linux.
  2. Type any one of the following command to check if a port is in use on Linux. sudo lsof -i -P -n | grep LISTEN.
  3. Search for the TCP or UDP port description in /etc/services file on Linux: grep -E -w ‘PORT_NUMBER_HERE/(tcp|udp)’ /etc/services.

How do I know if port 8080 is busy?

1. Before starting the Kernel and WebRunner open the Command Prompt and execute the command: netstat -aon | find /i “listening” . It lists all the busy TCP ports on your local machine.

How can I tell if port 8080 is listening Linux?

“linux check if port 8080 is open” Code Answer’s

  1. # Any of the following.
  2. sudo lsof -i -P -n | grep LISTEN.
  3. sudo netstat -tulpn | grep LISTEN.
  4. sudo lsof -i:22 # see a specific port such as 22.
  5. sudo nmap -sTU -O IP-address-Here.

How can I tell if a port is busy?

You can use “netstat” to check whether a port is available or not. Use the netstat -anp | find “port number” command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

How do I enable 443 port on Linux?

Individual commands method

  1. Run the following command to allow traffic on port 80: sudo iptables -I INPUT -p tcp -m tcp –dport 80 -j ACCEPT.
  2. Run the following command to allow traffic on port 443: sudo iptables -I INPUT -p tcp -m tcp –dport 443 -j ACCEPT.

How do I find out what ports are unused?

How do I know if port 4444 is open?

Running netstat -a -n or ss -a -n from a command prompt will show all of the network connections open and the listening ports on your machine.

What is my localhost port?

All you have to do is type “netstat -a” on Command Prompt and hit the Enter button. This will populate a list of your active TCP connections. The port numbers will be shown after the IP address and the two are separated by a colon.

What does netstat do in Linux?

The network statistics ( netstat ) command is a networking tool used for troubleshooting and configuration, that can also serve as a monitoring tool for connections over the network. Both incoming and outgoing connections, routing tables, port listening, and usage statistics are common uses for this command.

What is the port 80?

On a Web server or Hypertext Transfer Protocol daemon, port 80 is the port that the server “listens to” or expects to receive from a Web client, assuming that the default was taken when the server was configured or set up. By default, the port number for a Web server is 80.

Источник

How can I check if a port is busy or closed?

I need help to check where the problem is. Can I check if the port are busy or closed? If yes, how ? Here is my /etc/hosts :

127.0.0.1 localhost 127.0.1.1 ubuntu # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters 

2 Answers 2

Note: Really read man lsof ! I’m not sitting at a linux box right now.

You can check if the port is in use by running this command.

sudo lsof -i : i am useing 8080 as an example because i have nothing running on port 6700 change 8080 to your port number

sudo lsof -i :8080 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME havp 1331 havp 3u IPv4 3434363 0t0 TCP 192.168.1.127:http-alt (LISTEN) havp 25061 havp 3u IPv4 3434363 0t0 TCP 192.168.1.127:http-alt (LISTEN) havp 25062 havp 3u IPv4 3434363 0t0 TCP 192.168.1.127:http-alt (LISTEN) havp 25067 havp 3u IPv4 3434363 0t0 TCP 192.168.1.127:http-alt (LISTEN) havp 25068 havp 3u IPv4 3434363 0t0 TCP 192.168.1.127:http-alt (LISTEN) havp 25086 havp 3u IPv4 3434363 0t0 TCP 192.168.1.127:http-alt (LISTEN) 

or useing this command sudo netstat -tulnp | grep

neil@AVP:~$ netstat -tulnp | grep 8080 (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) tcp 0 0 192.168.1.127:8080 0.0.0.0:* LISTEN - 

If the Port has (LISTEN) is indicated that the port is opened. Any port that are not shown in the output indicated that it’s closed

Moved from (unformatted) comment by @waltinator:

i tried to use sudo lsof -i :6702 before using it it was empty then when i used it i got this

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME java 3143 st 71u IPv6 12097 0t0 TCP *:6702 (LISTEN) 

Источник

Читайте также:  Linux не разворачиваются окна
Оцените статью
Adblock
detector