Как посмотреть открытые порты в Linux
Сетевые порты — это механизм, с помощью которого операционная система определяет какой именно программе необходимо передать сетевой пакет. Здесь можно привести пример с домом. Например, почтальону необходимо доставить посылку. Он доставляет посылку к дому, это IP адрес компьютера. А дальше в самом доме уже должны разобраться в какую квартиру направить эту посылку. Номер квартиры — это уже порт.
Если порт открыт это означает, что какая либо программа, обычно сервис, использует его для связи с другой программой через интернет или в локальной системе. Чтобы посмотреть какие порты открыты в вашей системе Linux можно использовать множество различных утилит. В этой статье мы рассмотрим самые популярные способы посмотреть открытые порты Linux.
Как посмотреть открытые порты linux
1. netstat
Утилита netstat позволяет увидеть открытые в системе порты, а также открытые на данный момент сетевые соединения. Для отображения максимально подробной информации надо использовать опции:
- -l или —listening — посмотреть только прослушиваемые порты;
- -p или —program — показать имя программы и ее PID;
- -t или —tcp — показать tcp порты;
- -u или —udp показать udp порты;
- -n или —numeric показывать ip адреса в числовом виде.
Открытые порты Linux, которые ожидают соединений имеют тип LISTEN, а перед портом отображается IP адрес на котором сервис ожидает подключений. Это может быть определенный IP адрес или */0.0.0.0 что означают любой доступный адрес:
sudo netstat -tulpn
Утилита ss — это современная альтернатива для команды netstat. В отличие от netstat, которая берет информацию из каталога /proc, утилита ss напрямую связывается со специальной подсистемой ядра Linux, поэтому работает быстрее и её данные более точные, если вы хотите выполнить просмотр открытых портов это не имеет большого значения. Опции у неё такие же:
Можно вывести только процессы, работающие на 80-том порту:
sudo ss -tulpn | grep :80
3. lsof
Утилита lsof позволяет посмотреть все открытые в системе соединения, в том числе и сетевые, для этого нужно использовать опцию -i, а чтобы отображались именно порты, а не названия сетевых служб следует использовать опцию -P:
Ещё один пример, смотрим какие процессы работают с портом 80:
sudo lsof -i -P | grep :80
4. Nmap
Программа Nmap — мощный сетевой сканер, разработанный для сканирования и тестирования на проникновение удаленных узлов, но ничего не мешает направить его на локальный компьютер. Утилита позволяет не только посмотреть открытые порты, но и примерно определить какие сервисы их слушают и какие уязвимости у них есть. Программу надо установить:
sudo apt install nmap
Затем можно использовать:
Для простого сканирования можно запускать утилиту без опций. Детальнее о её опциях можно узнать в статье про сканирование сети в Nmap. Эта утилита ещё будет полезна если вы хотите посмотреть какие порты на компьютере доступны из интернета.
Если это публичный сервер, то результат скорее всего не будет отличатся от локального сканирования, но на домашнем компьютере все немного по другому. Первый вариант — используется роутер и в сеть будут видны только порты роутера, еще одним порогом защиты может стать NAT-сервер провайдера. Технология NAT позволяет нескольким пользователям использовать один внешний IP адрес. И так для просмотра открытых внешних портов сначала узнаем внешний ip адрес, для надежности воспользуемся онлайн сервисом:
wget -O — -q eth0.me
Дальше запускаем сканирование:
В результате мы видим, что открыт порт 80 веб-сервера и 22 — порт службы ssh, я их не открывал, эти порты открыты роутером, 80 — для веб-интерфейса, а 22 для может использоваться для обновления прошивки. А еще можно вообще не получить результатов, это будет означать что все порты закрыты, или на сервере установлена система защиты от вторжений IDS. Такая проверка портов может оказаться полезной для того, чтобы понять находится ли ваш компьютер в безопасности и нет ли там лишних открытых портов, доступных всем.
5. Zenmap
Программа Zenmap — это графический интерфейс для nmap. Она не делает ничего нового кроме того, что может делать nmap, просто предоставляет ко всему этому удобный интерфейс. Для её установки выполните:
sudo apt install zenmap
Запустить программу можно из главного меню или командой:
Затем введите адрес localhost в поле Цель и нажмите кнопку Сканирование:
После завершения сканирования утилита вывела список открытых портов Linux.
Выводы
В этой статье мы рассмотрели инструменты, которые вы можете использовать для того чтобы узнать узнать открытые порты linux. Инструментов не так много как для просмотра информации об оперативной памяти или процессоре, но их вполне хватает. А какими программами пользуетесь вы? Напишите в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Проверка доступности TCP/UDP- порта в Linux-server
Приветствую тебя, читатель! Если ты попал сюда, видимо, ты находишься в поиске информации, как проверять сетевые доступы в командной строке Linux. Постараюсь ответить на этот вопрос.
Проверка доступности TCP-порта
Для проверки доступности TCP-порта в командной строке Linux идеально подходит утилита telnet. Ниже я приведу несколько примеров:
Вместо telnet можно воспользоваться утилитой nc (NetCat), команды у нее очень простые. Ниже приведу аналогичную проверку доступности порта MySQL:
С полным списком доступных ключей утилиты nc и их описанием можно ознакомиться тут.
Проверка доступности UDP-порта
Для проверки UDP-портов выбор утилит меньше. Я использую в основном nc (NetCat). Ниже приведу несколько примеров проверки UDP-порта:
6 ways to Check a remote port is open in Linux
Checking remote port status is a common task for Linux admin. Now we collect 6 different ways for this task. We don’t need to install any package if we use the following two python commands. We need to install the package if we choose nc, nmap,telnet.
Methods to check if a remote port is open in Linux
The following commands can be used to check if a port is open on the remote server in Linux.
- Use nc command nc -zvw10 192.168.0.1 22
- Use nmap command nmap 192.168.0.1 -p 22
- Use telnet command telnet 192.168.0.1 22
- Use python telnet module
- Use python socket module
- Use curl command
Use nc command to check the remote port is open in Linux
$ nc [-options] [HostName or IP] [PortNumber]
$ nc -zvw10 192.168.0.1 22
- z: zero-I/O mode which is used for scanning
- v: for verbose output
- w10: timeout wait 10 seconds
The “nc” command stands for “netcat”. The “nc” command is a very versatile command that can be used for a variety of purposes, including network administration and data transmission.
For example, the “nc” command can be used to create a simple TCP connection between two computers. The “nc” command can be used to connect to a remote server on a given port and send/receive data.
For example, if you want to connect to a remote server on port xx, you would use the following command: nc -zv <remote server> port
In this example, “<remote server>” is the IP address or hostname of the remote server, and “<port>” is the port that you want to connect to.
I needed to see if the port 22 (SSH) on a remote machine was open, so I opened a terminal and ran the following command:
$ nc -vz hostname.com 22
The -v option enabled verbose output, and the -z option instructed nc to only scan for open ports, without actually establishing a connection.
The output showed me the results of the port scan:
Connection to hostname.com 22 port [tcp/ssh] succeeded!
This told me that the port 22 was open and that I could connect to the remote machine using SSH.
In another scenario, if the port was not open, the output would look something like this:
nc: connect to hostname.com port 22 (tcp) failed: Connection refused
You can also use the “nc” command to open a port in Linux. To do this, you would use the following command: nc -l -p 1234
In this example, “-l” is used to listen for a connection on port 1234
Use nmap to check the remote port is open in Linux
$ nmap [-options] [HostName or IP] [-p] [PortNumber]
nmap 192.168.0.1 -p 22
The “nmap” command is a command-line tool used for network exploration and security auditing. The “nmap” command can be used to scan for open ports on a remote server, as well as to identify the operating system and services running on that server.
For example, if you want to scan for open ports on a remote server, you would use the following command:
nmap <remote server> -p port
In this example, “<remote server>” is the IP address or hostname of the remote server, and “<port>” is the port that you want to scan.
Use telnet to check the remote port is open in Linux
$ telnet [HostName or IP] [PortNumber]
telnet 192.168.0.1 22
The telnet command is a command-line tool used for network communication. The telnet command can be used to connect to a remote server on a given port.
For example, if you want to connect to a remote server on port, you would use the following command: telnet <remote server> port
In this example, “<remote server>” is the IP address or hostname of the remote server, and “<port>” is the port that you want to connect to.
Use python telnet to check remote port is open in Linux
python -c «import telnetlib; tel=telnetlib.Telnet(‘192.168.0.1′,’22’,10); print tel; tel.close()»
If you are using Python3, using the following command:
python3 -c «import telnetlib; tel=telnetlib.Telnet(‘10.248.169.140′,’5432’,10); print(tel); tel.close()»
Telnetlib is a module in Python that allows you to communicate with remote servers using the Telnet protocol. The Telnet protocol is a text-based protocol used for communicating with remote servers.
To use the Telnetlib module, you first need to import it into your Python program: import telnetlib
Next, you need to create an instance of the Telnet object: telnet = telnetlib.Telnet()
The Telnet object has a number of methods that allow you to send and receive data. For example, the send() method allows you to send text data to the remote server, and the recv() method allows you to receive text data from the remote server.
Use python socket to check remote port is open in Linux
Python -c «import socket; s = socket.socket(); s.settimeout(10); s.connect((‘192.168.0.1’, 22)); «
The “socket” module is a module in Python that allows you to create and use sockets. A socket is a communication channel that allows two processes to connect and send/receive data.
The “socket” module has a number of functions that allow you to do a variety of things, including creating sockets, binding sockets to addresses, and sending/receiving data.
In order to use the “socket” module, you first need to import it into your Python program. You can do this by using the following command: import socket
Once you have imported the “socket” module, you can then use its functions to create sockets and communicate with other processes.
Use curl to check remote port is open in Linux
We have another solution for this with the curl command. curl -v telnet://192.168.0.1:22
The “curl” command is a tool used for transferring data with URL syntax. The “curl” command can be used to send data to a remote server, or it can be used to download data from a remote server.
If you want to download data from a remote server, you can use the following command: curl <remote server> port -o filename.txt
In this example, “<remote server>” is the IP address or hostname of the remote server, and “<port>” is the port that you want to download data from.
The “curl” command can also be used to check whether a port is open or not. To do this, you would use the following command:
curl -v telnet://<remote server>:port
In this example, “<remote server>” is the IP address or hostname of the remote server, and “<port>” is the port that you want to check.
Test if a port on a remote system is reachable (without telnet)
In the old days, we used telnet to see if a port on a remote host was open: telnet hostname port would attempt to connect to any port on any host and give you access to the raw TCP stream.
These days, the systems I work on do not have telnet installed (for security reasons), and all outbound connections to all hosts are blocked by default. Over time, it’s easy to lose track of which ports are open to which hosts.
Is there another way to test if a port on a remote system is open – using a Linux system with a limited number of packages installed, and telnet is not available?
14 Answers 14
Bash has been able to access TCP and UDP ports for a while. From the man page:
So you could use something like this:
Nice and verbose! From the man pages.
Single port:
Netcat is a useful tool:
nc 127.0.0.1 123 &> /dev/null; echo $?
Will output 0 if port 123 is open, and 1 if it’s closed.
The simplest method, without making use of another tool, such as socat , is as described in @lornix’s answer above. This is just to add an actual example of how one would make use of the psuedo-device /dev/tcp/. within Bash if you wanted to, say, test if another server had a given port accessible via the command line.
Examples
Say I have a host on my network named skinner .
The reason you want to wrap the echo > /dev/. in parentheses like this, (echo > /dev/. ) is because if you don’t, then with tests of connections that are down, you’ll get these types of messages showing up.
These can’t simply be redirected to /dev/null since they’re coming from the attempt to write out data to the device /dev/tcp . So we capture all that output within a sub-command, i.e. (. cmds. ) and redirect the output of the sub-command.
I found that curl may get the job done in a similar way to telnet , and curl will even tell you which protocol the listener expects.
Construct an HTTP URI from the hostname and port as the first argument to curl . If curl can connect, it will report a protocol mismatch and exit (if the listener isn’t a web service). If curl cannot connect, it will time out.
For example, port 5672 on host 10.0.0.99 is either closed or blocked by a firewall:
However, from a different system, port 5672 on host 10.0.0.99 can be reached, and appears to be running an AMQP listener.
It’s important to distinguish between the different messages: the first failure was because curl could not connect to the port. The second failure is a success test, though curl expected an HTTP listener instead of an AMQP listener.