Проверить порт 3306 linux

How to test which port MySQL is running on and whether it can be connected to?

Neither works. Not sure if both are supposed to work, but at least one of them should 🙂 How can I make sure that the port is indeed 3306? Is there a linux command to see it somehow? Also, is there a more correct way to try it via a url?

14 Answers 14

To find a listener on a port, do this:

You should see a line that looks like this if mysql is indeed listening on that port.

tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 

Port 3306 is MySql’s default port.

To connect, you just have to use whatever client you require, such as the basic mysql client.

mysql -h localhost -u user database

Or a url that is interpreted by your library code.

@mbmast the 127. means listen on local host only (not externally accessible). The 0.0.0.0 means «all interfaces», and therefore is (usually) externally visible.

I thought to be externally visible, it had to be the machine’s own IP address and that 0.0.0.0 means the service is not available from anywhere. Do I have that wrong? I have a box running MySQL, the firewall has 3306 open from any IP address but MySQL is refusing the connection, I thought because currently MySQL is listening on 0.0.0.0.

Should merge this with @bortunac’s answer, which references the -p parameter. Adding the process(es) really helps make this information more useful.

mysql> SHOW GLOBAL VARIABLES LIKE 'PORT'; 

grep port /etc/mysql/my.cnf ( at least in debian/ubuntu works )

mysql -u user_name -puser_pass -e "SHOW variables LIKE 'port';" 

in /etc/mysql/my.cnf to see possible restrictions

It will show the list something like below:

Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1393/sshd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1859/master tcp 0 0 123.189.192.64:7654 0.0.0.0:* LISTEN 2463/monit tcp 0 0 127.0.0.1:24135 0.0.0.0:* LISTEN 21450/memcached tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 16781/mysqld 

Use as root for all details. The -t option limits the output to TCP connections, -l for listening ports, -p lists the program name and -n shows the numeric version of the port instead of a named version.

In this way you can see the process name and the port.

Try only using -e ( —execute ) option:

$ mysql -u root -proot -e "SHOW GLOBAL VARIABLES LIKE 'PORT';" (8s 26ms) +---------------+-------+ | Variable_name | Value | +---------------+-------+ | port | 3306 | +---------------+-------+ 

Replace root by your «username» and «password»

A simpler approach for some : If you just want to check if MySQL is on a certain port, you can use the following command in terminal. Tested on mac. 3306 is the default port.

mysql —host=127.0.0.1 —port=3306

Читайте также:  Создать таблица разделов mbr linux

If you successfully log in to the MySQL shell terminal, you’re good! This is the output that I get on a successful login.

Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 9559 Server version: 5.6.21 Homebrew Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> 

Источник

Как посмотреть открытые порты в 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 что означают любой доступный адрес:

2. ss

Утилита ss — это современная альтернатива для команды netstat. В отличие от netstat, которая берет информацию из каталога /proc, утилита ss напрямую связывается со специальной подсистемой ядра Linux, поэтому работает быстрее и её данные более точные, если вы хотите выполнить просмотр открытых портов это не имеет большого значения. Опции у неё такие же:

Можно вывести только процессы, работающие на 80-том порту:

3. lsof

Утилита lsof позволяет посмотреть все открытые в системе соединения, в том числе и сетевые, для этого нужно использовать опцию -i, а чтобы отображались именно порты, а не названия сетевых служб следует использовать опцию -P:

Ещё один пример, смотрим какие процессы работают с портом 80:

4. Nmap

Программа Nmap — мощный сетевой сканер, разработанный для сканирования и тестирования на проникновение удаленных узлов, но ничего не мешает направить его на локальный компьютер. Утилита позволяет не только посмотреть открытые порты, но и примерно определить какие сервисы их слушают и какие уязвимости у них есть. Программу надо установить:

Для простого сканирования можно запускать утилиту без опций. Детальнее о её опциях можно узнать в статье про сканирование сети в Nmap. Эта утилита ещё будет полезна если вы хотите посмотреть какие порты на компьютере доступны из интернета.

Читайте также:  Astra linux неправильный пароль

Если это публичный сервер, то результат скорее всего не будет отличатся от локального сканирования, но на домашнем компьютере все немного по другому. Первый вариант — используется роутер и в сеть будут видны только порты роутера, еще одним порогом защиты может стать NAT-сервер провайдера. Технология NAT позволяет нескольким пользователям использовать один внешний IP адрес. И так для просмотра открытых внешних портов сначала узнаем внешний ip адрес, для надежности воспользуемся онлайн сервисом:

Дальше запускаем сканирование:

В результате мы видим, что открыт порт 80 веб-сервера и 22 — порт службы ssh, я их не открывал, эти порты открыты роутером, 80 — для веб-интерфейса, а 22 для может использоваться для обновления прошивки. А еще можно вообще не получить результатов, это будет означать что все порты закрыты, или на сервере установлена система защиты от вторжений IDS. Такая проверка портов может оказаться полезной для того, чтобы понять находится ли ваш компьютер в безопасности и нет ли там лишних открытых портов, доступных всем.

5. Zenmap

Программа Zenmap — это графический интерфейс для nmap. Она не делает ничего нового кроме того, что может делать nmap, просто предоставляет ко всему этому удобный интерфейс. Для её установки выполните:

Запустить программу можно из главного меню или командой:

Затем введите адрес localhost в поле Цель и нажмите кнопку Сканирование:

После завершения сканирования утилита вывела список открытых портов Linux.

Выводы

В этой статье мы рассмотрели инструменты, которые вы можете использовать для того чтобы узнать узнать открытые порты linux. Инструментов не так много как для просмотра информации об оперативной памяти или процессоре, но их вполне хватает. А какими программами пользуетесь вы? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Check if port is open or closed on a Linux server?

It’s not quite clear what you’re asking. What do you mean by «open»? Do you mean some server is listening on that port? Or do you mean it’s allowed by the system firewall? Or what?

nc -w5 -z -v , you should get something like Connection to 127.0.0.1 9000 port [tcp/*] succeeded! , otherwise port is closed.

A topic that contains an answer also for kernel level services and programs serverfault.com/questions/1078483/…

8 Answers 8

You can check if a process listens on a TCP or UDP port with netstat -tuplen .

To check whether some ports are accessible from the outside (this is probably what you want) you can use a port scanner like Nmap from another system. Running Nmap on the same host you want to check is quite useless for your purpose.

GNU netstat knows the parameters -t , -u , -p , -l , -e , and -n . Thanks to the options parser it can be expressed as -tuplen . linux.die.net/man/8/netstat

Also, the telnet command usually does only supports TCP, so you’re out of luck if the service you want to check runs on another protocol.

Читайте также:  Как на линуксе открыть биос

According to article: computingforgeeks.com/netstat-vs-ss-usage-guide-linux netstat is deprecated, and ss is it’s replacement, so you can do ss -an , ss -tuplen or for tcp listening sockets ss -ntlp .

Quickest way to test if a TCP port is open (including any hardware firewalls you may have), is to type, from a remote computer (e.g. your desktop):

Which will try to open a connection to port 80 on that server. If you get a time out or deny, the port is not open 🙂

OK, in summary, you have a server that you can log into. You want to see if something is listening on some port. As root, run:

this will show a listing of processes listening on TCP and UDP ports. You can scan (or grep) it for the process you’re interest in,and/or the port numbers you expect to see.

If the process you expect isn’t there, you should start up that process and check netstat again. If the process is there, but it’s listening on a interface and port that you did not expect, then there’s a configuration issue (e.g., it could be listening, but only on the loopback interface, so you would see 127.0.0.1:3306 and no other lines for port 3306, in the case of the default configuration for MySQL).

If the process is up, and it’s listening on the port you expect, you can try running a «telnet» to that port from your Macbook in your office/home, e.g.,

 telnet xxxxxxxxxxxx.co.uk 443 

That will test if (assuming standard ports) that there’s a web server configured for SSL. Note that this test using telnet is only going to work if the process is listening on a TCP port. If it’s a UDP port, you may as well try with whatever client you were going to use to connect to it. (I see that you used port 224. This is masqdialer, and I have no idea what that is).

If the service is there, but you can’t get to it externally, then there’s a firewall blocking you. In that case, run:

This will show all the firewall rules as defined on your system. You can post that, but, generally, if you’re not allowing everything on the INPUT chain, you probably will need to explicitly allow traffic on the port in question:

 iptables -I INPUT -p tcp --dport 224 -j ACCEPT 

or something along those lines. Do not run your firewall commands blindly based on what some stranger has told you on the Internet. Consider what you’re doing.

If your firewall on the box is allowing the traffic you want, then your hosting company may be running a firewall (e.g., they’re only allowing SSH (22/tcp), HTTP (80/tcp) and HTTPS (443/tcp) and denying all other incoming traffic). In this case, you will need to open a helpdesk ticket with them to resolve this issue, though I suppose there might be something in your cPanel that may allow it.

Источник

Оцените статью
Adblock
detector