предыдущая глава | содержание | следующая глава
- 10.1 «The server’s host key is not cached in the registry»
- 10.2 «WARNING — POTENTIAL SECURITY BREACH!»
- 10.3 «SSH protocol version 2 required by our configuration but remote only provides (old, insecure) SSH-1»
- 10.4 «The first cipher supported by the server is … below the configured warning threshold»
- 10.5 «Remote side sent disconnect message type 2 (protocol error): «Too many authentication failures for root»»
- 10.6 «Out of memory»
- 10.7 «Internal error», «Internal fault», «Assertion failed»
- 10.8 «Unable to use key file», «Couldn’t load private key», «Couldn’t load this key»
- 10.9 «Server refused our key», «Server refused our public key», «Key refused»
- 10.10 «Access denied», «Authentication refused»
- 10.11 «No supported authentication methods available»
- 10.12 «Incorrect MAC received on packet» or «Incorrect CRC received on packet»
- 10.13 «Incoming packet was garbled on decryption»
- 10.14 «PuTTY X11 proxy: various errors»
- 10.15 «Network error: Software caused connection abort»
- 10.16 «Network error: Connection reset by peer»
- 10.17 «Network error: Connection refused»
- 10.18 «Network error: Connection timed out»
- 10.19 «Network error: Cannot assign requested address»
This chapter lists a number of common error messages which PuTTY and its associated tools can produce, and explains what they mean in more detail.
We do not attempt to list all error messages here: there are many which should never occur, and some which should be self-explanatory. If you get an error message which is not listed in this chapter and which you don’t understand, report it to us as a bug (see appendix B) and we will add documentation for it.
10.1 «The server’s host key is not cached in the registry»
This error message occurs when PuTTY connects to a new SSH server. Every server identifies itself by means of a host key; once PuTTY knows the host key for a server, it will be able to detect if a malicious attacker redirects your connection to another machine.
If you see this message, it means that PuTTY has not seen this host key before, and has no way of knowing whether it is correct or not. You should attempt to verify the host key by other means, such as asking the machine’s administrator.
If you see this message and you know that your installation of PuTTY has connected to the same server before, it may have been recently upgraded to SSH protocol version 2. SSH protocols 1 and 2 use separate host keys, so when you first use SSH-2 with a server you have only used SSH-1 with before, you will see this message again. You should verify the correctness of the key as before.
See section 2.2 for more information on host keys.
10.2 «WARNING — POTENTIAL SECURITY BREACH!»
This message, followed by «The server’s host key does not match the one PuTTY has cached in the registry», means that PuTTY has connected to the SSH server before, knows what its host key should be, but has found a different one.
This may mean that a malicious attacker has replaced your server with a different one, or has redirected your network connection to their own machine. On the other hand, it may simply mean that the administrator of your server has accidentally changed the key while upgrading the SSH software; this shouldn’t happen but it is unfortunately possible.
You should contact your server’s administrator and see whether they expect the host key to have changed. If so, verify the new host key in the same way as you would if it was new.
See section 2.2 for more information on host keys.
10.3 «SSH protocol version 2 required by our configuration but remote only provides (old, insecure) SSH-1»
By default, PuTTY only supports connecting to SSH servers that implement SSH protocol version 2. If you see this message, the server you’re trying to connect to only supports the older SSH-1 protocol.
If the server genuinely only supports SSH-1, then you need to either change the «SSH protocol version» setting (see section 4.19.4), or use the -1
command-line option; in any case, you should not treat the resulting connection as secure.
You might start seeing this message with new versions of PuTTY (from 0.68 onwards) where you didn’t before, because it used to be possible to configure PuTTY to automatically fall back from SSH-2 to SSH-1. This is no longer supported, to prevent the possibility of a downgrade attack.
10.4 «The first cipher supported by the server is … below the configured warning threshold»
This occurs when the SSH server does not offer any ciphers which you have configured PuTTY to consider strong enough. By default, PuTTY puts up this warning only for Blowfish, single-DES, and Arcfour encryption.
See section 4.22 for more information on this message.
(There are similar messages for other cryptographic primitives, such as host key algorithms.)
10.5 «Remote side sent disconnect message type 2 (protocol error): «Too many authentication failures for root»»
This message is produced by an OpenSSH (or Sun SSH) server if it receives more failed authentication attempts than it is willing to tolerate.
This can easily happen if you are using Pageant and have a large number of keys loaded into it, since these servers count each offer of a public key as an authentication attempt. This can be worked around by specifying the key that’s required for the authentication in the PuTTY configuration (see section 4.23.8); PuTTY will ignore any other keys Pageant may have, but will ask Pageant to do the authentication, so that you don’t have to type your passphrase.
On the server, this can be worked around by disabling public-key authentication or (for Sun SSH only) by increasing MaxAuthTries
in sshd_config
.
10.6 «Out of memory»
This occurs when PuTTY tries to allocate more memory than the system can give it. This may happen for genuine reasons: if the computer really has run out of memory, or if you have configured an extremely large number of lines of scrollback in your terminal. PuTTY is not able to recover from running out of memory; it will terminate immediately after giving this error.
However, this error can also occur when memory is not running out at all, because PuTTY receives data in the wrong format. In SSH-2 and also in SFTP, the server sends the length of each message before the message itself; so PuTTY will receive the length, try to allocate space for the message, and then receive the rest of the message. If the length PuTTY receives is garbage, it will try to allocate a ridiculous amount of memory, and will terminate with an «Out of memory» error.
This can happen in SSH-2, if PuTTY and the server have not enabled encryption in the same way (see question A.7.3 in the FAQ).
This can also happen in PSCP or PSFTP, if your login scripts on the server generate output: the client program will be expecting an SFTP message starting with a length, and if it receives some text from your login scripts instead it will try to interpret them as a message length. See question A.7.4 for details of this.
10.7 «Internal error», «Internal fault», «Assertion failed»
Any error beginning with the word «Internal» should never occur. If it does, there is a bug in PuTTY by definition; please see appendix B and report it to us.
Similarly, any error message starting with «Assertion failed» is a bug in PuTTY. Please report it to us, and include the exact text from the error message box.
10.8 «Unable to use key file», «Couldn’t load private key», «Couldn’t load this key»
Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see section 3.1.3.1) when trying public-key authentication, or given by Pageant when trying to load a private key.
If you see one of these messages, it often indicates that you’ve tried to load a key of an inappropriate type into PuTTY, Plink, PSCP, PSFTP, or Pageant.
You may have tried to load an SSH-2 key in a «foreign» format (OpenSSH or ssh.com
) directly into one of the PuTTY tools, in which case you need to import it into PuTTY’s native format (*.PPK
) using PuTTYgen – see section 8.2.12.
Alternatively, you may have specified a key that’s inappropriate for the connection you’re making. The SSH-2 and the old SSH-1 protocols require different private key formats, and a SSH-1 key can’t be used for a SSH-2 connection (or vice versa).
10.9 «Server refused our key», «Server refused our public key», «Key refused»
Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see section 3.1.3.1) when trying public-key authentication.
If you see one of these messages, it means that PuTTY has sent a public key to the server and offered to authenticate with it, and the server has refused to accept authentication. This usually means that the server is not configured to accept this key to authenticate this user.
This is almost certainly not a problem with PuTTY. If you see this type of message, the first thing you should do is check your server configuration carefully. Common errors include having the wrong permissions or ownership set on the public key or the user’s home directory on the server. Also, read the PuTTY Event Log; the server may have sent diagnostic messages explaining exactly what problem it had with your setup.
Section 8.3 has some hints on server-side public key setup.
10.10 «Access denied», «Authentication refused»
Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see section 3.1.3.1) during authentication.
If you see one of these messages, it means that the server has refused all the forms of authentication PuTTY has tried and it has no further ideas.
It may be worth checking the Event Log for diagnostic messages from the server giving more detail.
This error can be caused by buggy SSH-1 servers that fail to cope with the various strategies we use for camouflaging passwords in transit. Upgrade your server, or use the workarounds described in section 4.28.11 and possibly section 4.28.12.
10.11 «No supported authentication methods available»
This error indicates that PuTTY has run out of ways to authenticate you to an SSH server. This may be because PuTTY has TIS or keyboard-interactive authentication disabled, in which case see section 4.23.4 and section 4.23.5.
10.12 «Incorrect MAC received on packet» or «Incorrect CRC received on packet»
This error occurs when PuTTY decrypts an SSH packet and its checksum is not correct. This probably means something has gone wrong in the encryption or decryption process. It’s difficult to tell from this error message whether the problem is in the client, in the server, or in between.
In particular, if the network is corrupting data at the TCP level, it may only be obvious with cryptographic protocols such as SSH, which explicitly check the integrity of the transferred data and complain loudly if the checks fail. Corruption of protocols without integrity protection (such as HTTP) will manifest in more subtle failures (such as misdisplayed text or images in a web browser) which may not be noticed.
Occasionally this has been caused by server bugs. An example is the bug described at section 4.28.8, although you’re very unlikely to encounter that one these days.
In this context MAC stands for Message Authentication Code. It’s a cryptographic term, and it has nothing at all to do with Ethernet MAC (Media Access Control) addresses, or with the Apple computer.
10.13 «Incoming packet was garbled on decryption»
This error occurs when PuTTY decrypts an SSH packet and the decrypted data makes no sense. This probably means something has gone wrong in the encryption or decryption process. It’s difficult to tell from this error message whether the problem is in the client, in the server, or in between.
If you get this error, one thing you could try would be to fiddle with the setting of «Miscomputes SSH-2 encryption keys» (see section 4.28.10) or «Ignores SSH-2 maximum packet size» (see section 4.28.5) on the Bugs panel.
10.14 «PuTTY X11 proxy: various errors»
This family of errors are reported when PuTTY is doing X forwarding. They are sent back to the X application running on the SSH server, which will usually report the error to the user.
When PuTTY enables X forwarding (see section 3.4) it creates a virtual X display running on the SSH server. This display requires authentication to connect to it (this is how PuTTY prevents other users on your server machine from connecting through the PuTTY proxy to your real X display). PuTTY also sends the server the details it needs to enable clients to connect, and the server should put this mechanism in place automatically, so your X applications should just work.
A common reason why people see one of these messages is because they used SSH to log in as one user (let’s say «fred»), and then used the Unix su
command to become another user (typically «root»). The original user, «fred», has access to the X authentication data provided by the SSH server, and can run X applications which are forwarded over the SSH connection. However, the second user («root») does not automatically have the authentication data passed on to it, so attempting to run an X application as that user often fails with this error.
If this happens, it is not a problem with PuTTY. You need to arrange for your X authentication data to be passed from the user you logged in as to the user you used su
to become. How you do this depends on your particular system; in fact many modern versions of su
do it automatically.
10.15 «Network error: Software caused connection abort»
This is a generic error produced by the Windows network code when it kills an established connection for some reason. For example, it might happen if you pull the network cable out of the back of an Ethernet-connected computer, or if Windows has any other similar reason to believe the entire network has become unreachable.
Windows also generates this error if it has given up on the machine at the other end of the connection ever responding to it. If the network between your client and server goes down and your client then tries to send some data, Windows will make several attempts to send the data and will then give up and kill the connection. In particular, this can occur even if you didn’t type anything, if you are using SSH-2 and PuTTY attempts a key re-exchange. (See section 4.20.2 for more about key re-exchange.)
(It can also occur if you are using keepalives in your connection. Other people have reported that keepalives fix this error for them. See section 4.14.1 for a discussion of the pros and cons of keepalives.)
We are not aware of any reason why this error might occur that would represent a bug in PuTTY. The problem is between you, your Windows system, your network and the remote system.
10.16 «Network error: Connection reset by peer»
This error occurs when the machines at each end of a network connection lose track of the state of the connection between them. For example, you might see it if your SSH server crashes, and manages to reboot fully before you next attempt to send data to it.
However, the most common reason to see this message is if you are connecting through a firewall or a NAT router which has timed the connection out. See question A.7.8 in the FAQ for more details. You may be able to improve the situation by using keepalives; see section 4.14.1 for details on this.
Note that Windows can produce this error in some circumstances without seeing a connection reset from the server, for instance if the connection to the network is lost.
10.17 «Network error: Connection refused»
This error means that the network connection PuTTY tried to make to your server was rejected by the server. Usually this happens because the server does not provide the service which PuTTY is trying to access.
Check that you are connecting with the correct protocol (SSH, Telnet or Rlogin), and check that the port number is correct. If that fails, consult the administrator of your server.
10.18 «Network error: Connection timed out»
This error means that the network connection PuTTY tried to make to your server received no response at all from the server. Usually this happens because the server machine is completely isolated from the network, or because it is turned off.
Check that you have correctly entered the host name or IP address of your server machine. If that fails, consult the administrator of your server.
Unix also generates this error when it tries to send data down a connection and contact with the server has been completely lost during a connection. (There is a delay of minutes before Unix gives up on receiving a reply from the server.) This can occur if you type things into PuTTY while the network is down, but it can also occur if PuTTY decides of its own accord to send data: due to a repeat key exchange in SSH-2 (see section 4.20.2) or due to keepalives (section 4.14.1).
10.19 «Network error: Cannot assign requested address»
This means that the operating system rejected the parameters of the network connection PuTTY tried to make, usually without actually trying to connect to anything, because they were simply invalid.
A common way to provoke this error is to accidentally try to connect to port 0, which is not a valid port number.
I installed SQL Server 2017 on Ubuntu server and tried to connect to this server using PuTTY from my local host. I failed to connect and received PuTTY fatal error ubuntu ssh connection refused. Read this tip to fix this PuTTY Network Error : Connection Refused.
Network error: Ubuntu ssh Connection Refused
I faced ubuntu connection refused error while establishing a connection to Ubuntu Linux virtual machine from host computer. I installed PuTTY on my host and tried to connect to Ubuntu Linux machine. Let’s check the IP of Ubuntu server that we had used to make connection from PuTTY terminal. Run ipconfig command to get these details.
#Check IP of Ubuntu Server
ipconfig
We can see the IP details of the Ubuntu server that is showing 192.168.209.134. We have used this IP to establish server connection and end up with this PuTTY fatal error.
I tried to connect to Ubuntu server post getting IP from above command but I got ubuntu ssh connection refused error during this operation. The details of PuTTY Fatal Error that caused ubuntu connection refused is given below.
PuTTY Fatal Error
Network error: Connection Refused
Solution
We faced ubuntu ssh connection refused error and failed to connect to Ubuntu Server remotely using PuTTY terminal because SSH, or Secure Shell is not installed on the Ubuntu server. SSH, or Secure Shell, is a protocol used to securely log onto remote systems. Our next step is to install SSH on the Ubuntu server. Run below command to start this installation.
#Install SSH on Ubuntu Server
sudo apt-get install openssh-server
It will check the dependencies and ask you to type y to proceed with the installation as shown in below image.
A series of all required packages will download and set up to install SSH. Once SSH will be installed on your Ubuntu server it will look like below image.
You can also reconfirm the installation by executing same command which you ran to install it. You can say, it is saying newest version is already installed on this server.
Now launch PuTTY terminal on your host computer or a computer from where you want to connect to the Ubuntu server and enter IP address of Ubuntu server to establish connection. Once you click on connect button, you will get a window for the very first time only. Click on Yes button of that window to proceed. Once you will click on Yes button you will be connected to your Ubuntu server remotely.
Now we can see putty connection refused error is fixed and we can connect to Ubuntu server remotely using PuTTY terminal. If you want to change configurations of SSH you can refer to attached document. This way you can fix ubuntu ssh connection refused error.
Here, we have fixed ubuntu putty connection refused error. I hope you like this article. Please follow us on our facebook page and on Twitter handle to get latest updates.
- Author
- Recent Posts
I am working as a Technical Architect in one of the top IT consulting firm. I have expertise on all versions of SQL Server since SQL Server 2000. I have lead multiple SQL Server projects like consolidation, upgrades, migrations, HA & DR. I love to share my knowledge. You can contact me on my social accounts for any consulting work.
Summary
Article Name
Fix PuTTY Network Error: Connection Refused while Connecting to Ubuntu Server
Description
I installed SQL Server 2017 on Ubuntu server and tried to connect to this server using PuTTY from my local host. I failed to connect and received PuTTY fatal error ubuntu ssh connection refused. Read this tip to fix such PuTTY Network error: Connection Refused.
Author
Manvendra Deo Singh
Publisher Name
Techyaz.com
When on windows you usually use putty to connect to remote SSH servers or terminal when on Linux. While connecting sometimes you can get error such as localhost connection refused on putty or your Linux terminal. Now, this can be very annoying as you can’t get to SSH of your remote server and perform your tasks.
This problem can be from the server or client-side. In this tutorial, we will see probable causes of this error and how to fix them. If you are using our managed vps, then you just have to contact us via ticket or live chat and we should fix this for you.
Let’s continue and see reasons for this error and how to resolve localhost connection refused.
Possible error messages on Putty or Linux Terminal
We will first see possible error messages that you will see.
In putty
Putty Fatal Error
Network Error: Connection Refused
On Linux Terminal
ssh: connect to host 51.xx.xx.xx port 22: Connection timed out
Now the connection to the server is properly routed, but the server is not accepting your connection for many reasons that we will discuss below.
Reasons and Fixes for localhost connection refused
We will now discuss reasons and fixes for this error one by one.
1. SSHD Daemon not running
It is possible that SSHD daemon on your remote server is not running. For SSH to work there is a daemon that works behind the scene and it is called SSHD. If this daemon is not running your server will not be able to accept SSH incoming connections. Check if this service is running or not:
systemctl status sshd
If it is not running you can turn it on:
systemctl start sshd
SSHD does not start?
Now for some reasons if your SSHD daemon still won’t start make sure you have enough disk space using:
df -h
If you have enough space you can see if your server is receiving heavy traffic or if the server is under heavy load. You can hire our managed vps service as well we offer 3 days free trial (no credit card required)
2. Firewall blocking SSH Port
Most of the time there is some firewall blocking the SSH port. First, see if you can telnet to SSH port 22
telnet 192.xx.xx.xx 22
Then check if you or user IP is blocked on IP Tables firewall
iptables -nL
If IP is listed, you need to unblock this IP to restore connectivity to SSH port 22. There is also a possibility that firewall has dropped or reject rule for SSH port 22, you need to remove that rule and add run following command:
iptables -A input -p tcp –dport 22 -j ACCEPT
If using CyberPanel
If you are using CyberPanel it comes with Firewalld by default unless you have installed CSF. You can go to :8090/firewall/ by default port 22 is opened, if not you can add port 22 there.
If you have installed CSF with CyberPanel, you can use csf.allow file to allow this IP. The file is located at
nano /etc/csf/csf.allow
Then turn off and turn on CSF again from CyberPanel interface.
3. Custom SSH Port
If you have defined a custom port for SSH (for security reasons, because standard SSH ports are prone to brute force attacks). Then you need to open that port on the firewall as well. Because firewall doesn’t know you choose a custom port for SSH.
First, confirm if you are using custom port using
cat /etc/sshd_sshd_config | grep Port
If you see something other then port 22, you need to fix it.
iptables -A input -p tcp –dport custom_port_here -j ACCEPT
Replace with custom port here.
If using CyberPanel
Go here :8090/firewall/secureSSH and see if you have set custom ssh port. Normally if you set custom SSH port, CyberPanel will open this port for you on the firewall. But if it still does not work, you can open this port manually by going to :8090/firewall/ or here :8090/firewall/csf if you are using CSF.
4. Incorrect IP, SSH Port or Key File
It is also possible that you did a human error and used incorrect IP or wrong SSH port. Make sure you are using right IP on putty or Linux terminal along with the correct SSH port.
Sometimes people also use key-based authentication, and they get issues while connecting to SSH if the wrong private key is used or there are wrong permissions on your SSH private key. On your local server make sure that your private key has the permission of 600.
Why use CyberPanel?
We’ve discussed many reasons and fixes for localhost connection refused error. But we recommend that you install CyberPanel on your VPS, it will help you solve many issues and if you are hosting sites then you will get super speed as well because CyberPanel is based on OpenLiteSpeed and LiteSpeed Enterprise.
You will get easy access to Firewalld (installed by default) where you can easily open/close any ports at your wish. Or you can also install CSF too.
If you are a very novice user you can also hire our managed vps service, we are super affordable and provide top-notch support to all our customers. You can start with 3 days trial (no credit card required at all).
25 мая, 2017 11:40 дп
86 521 views
| Комментариев нет
Linux, SSH
В первой статье этой серии вы узнали о том, как и в каких ситуациях вы можете попробовать исправить ошибки SSH. Остальные статьи расскажут, как определить и устранить ошибки:
- Ошибки протокола: в этой статье вы узнаете, что делать, если сбрасываются клиентские соединения, клиент жалуется на шифрование или возникают проблемы с неизвестным или измененным удаленным хостом.
- Ошибки аутентификации: поможет устранить проблемы с парольной аутентификацией или сбросом SSH-ключей.
- Ошибки оболочки: это руководство поможет исправить ошибки ветвления процессов, валидации оболочки и доступа к домашнему каталогу.
Для взаимодействия SSH-клиента с SSH-сервером необходимо установить базовое сетевое подключение. Это руководство поможет определить некоторые общие ошибки подключения, исправить их и предотвратить их возникновение в будущем.
Требования
- Убедитесь, что можете подключиться к виртуальному серверу через консоль.
- Проверьте панель на предмет текущих проблем, влияющих на работу и состояние сервера и гипервизора.
Основные ошибки
Разрешение имени хоста
Большинство ошибок подключения возникает тогда, когда ссылка на хост SSH не может быть сопоставлена с сетевым адресом. Это почти всегда связано с DNS, но первопричина часто бывает не связана с DNS.
На клиенте OpenSSH эта команда:
ssh user@example.com
может выдать ошибку:
ssh: Could not resolve hostname example.com: Name or service not known
В PuTTY может появиться такая ошибка:
Unable to open connection to example.com Host does not exist
Чтобы устранить эту ошибку, можно попробовать следующее:
- Проверьте правильность написания имени хоста.
- Убедитесь, что вы можете разрешить имя хоста на клиентской машине с помощью команды ping. Обратитесь к сторонним сайтам (WhatsMyDns.net, например), чтобы подтвердить результаты.
Если у вас возникают проблемы с разрешением DNS на любом уровне, в качестве промежуточного решения можно использовать IP-адрес сервера, например:
ssh user@111.111.111.111
# вместо
ssh user@example.com.
Истечение времени соединения
Эта ошибка значит, что клиент попытался установить соединение с SSH-сервером, но сервер не смог ответить в течение заданного периода ожидания.
На клиенте OpenSSH следующая команда:
ssh user@111.111.111.111
выдаст такую ошибку:
ssh: connect to host 111.111.111.111 port 22: Connection timed out
В PuTTY ошибка выглядит так:
Network error: Connection timed out
Чтобы исправить ошибку:
- Убедитесь, что IP-адрес хоста указан правильно.
- Убедитесь, что сеть поддерживает подключение через используемый порт SSH. Некоторые публичные сети могут блокировать порт 22 или пользовательские SSH-порты. Чтобы проверить работу порта, можно, например, попробовать подключиться к другим хостам через этот же порт. Это поможет вам определить, не связана ли проблема с самим сервером.
- Проверьте правила брандмауэра. Убедитесь, что политика по умолчанию – не DROP.
Отказ в соединении
Эта ошибка означает, что запрос передается на хост SSH, но хост не может успешно принять запрос.
На клиенте OpenSSH следующая команда выдаст ошибку:
ssh user@111.111.111.111
ssh: connect to host 111.111.111.111 port 22: Connection refused
В PuTTY ошибка появится в диалоговом окне:
Network error: Connection refused
Эта ошибка имеет общие с ошибкой Connection Timeout причины. Чтобы исправить её, можно сделать следующее:
- Убедиться, что IP-адрес хоста указан правильно.
- Убедиться, что сеть поддерживает подключение через используемый порт SSH. Некоторые публичные сети могут блокировать порт 22 или пользовательские SSH-порты. Чтобы проверить работу порта, можно, например, попробовать подключиться к другим хостам через этот же порт.
- Проверить правила брандмауэра. Убедитесь, что политика по умолчанию – не DROP, и что брандмауэр не блокирует этот порт.
- Убедиться, что сервис запущен и привязан к требуемому порту.
Рекомендации по исправлению ошибок подключения
Брандмауэр
Иногда проблемы с подключением возникают из-за брандмауэра. Он может блокировать отдельные порты или сервисы.
Читайте также: Что такое брандмауэр и как он работает?
В разных дистрибутивах используются разные брандмауэры. Вы должны научиться изменять правила и политики своего брандмауэра. В Ubuntu обычно используется UFW, в CentOS – FirewallD. Брандмауэр iptables используется независимо от системы.
Читайте также:
- Основы UFW: общие правила и команды фаервола
- Настройка брандмауэра FirewallD в CentOS 7
- Основы Iptables: общие правила и команды брандмауэра
Чтобы настроить брандмауэр, нужно знать порт сервиса SSH. По умолчанию это порт 22.
Чтобы запросить список правил iptables, введите:
iptables -nL
Такой вывод сообщает, что правил, блокирующих SSH, нет:
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Если в выводе вы видите правило или политику по умолчанию REJECT или DROP, убедитесь, что цепочка INPUT разрешает доступ к порту SSH.
Чтобы запросить список правил FirewallD, введите:
firewall-cmd --list-services
Список, появившийся на экране, содержит все сервисы, которые поддерживаются брандмауэром. В списке должно быть правило:
dhcpv6-client http ssh
Если вы настроили пользовательский порт SSH, используйте опцию –list-ports. Если вы создали пользовательское определение сервиса, добавьте опцию –list-services, чтобы найти SSH.
Чтобы проверить состояние UFW, введите:
ufw status
Команда вернёт доступные порты:
Status: active
To Action From
-- ------ ----
22 LIMIT Anywhere
443 ALLOW Anywhere
80 ALLOW Anywhere
Anywhere ALLOW 192.168.0.0
22 (v6) LIMIT Anywhere (v6)
443 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
В списке должен быть порт SSH.
Проверка состояния сервиса SSH
Если вы не можете подключиться к серверу по SSH, убедитесь, что сервис SSH запущен. Способ сделать это зависит от операционной системы сервера. В более старых версиях дистрибутивов (Ubuntu 14.04, CentOS 6, Debian используется команда service. Современные дистрибутивы на основе Systemd используют команду systemctl.
Метод проверки состояния сервиса может варьироваться от системы к системе. В более старых версиях (Ubuntu 14 и ниже, CentOS 6, Debian 6) используется команда service, поддерживаемая системой инициализации Upstart, а в более современных дистрибутивах для управления сервисом используется команда systemctl.
Примечание: В дистрибутивах Red Hat (CentOS и Fedora) сервис называется sshd, а в Debian и Ubuntu – ssh.
В более старых версия используйте команду:
service ssh status
Если процесс работает должным образом, вы увидите вывод, который содержит PID:
ssh start/running, process 1262
Если сервис не работает, вы увидите:
ssh stop/waiting
В системах на основе SystemD используйте:
systemctl status sshd
В выводе должна быть строка active:
sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled)
Active: active (running) since Mon 2017-03-20 11:00:22 EDT; 1 months 1 days ago
Process: 899 ExecStartPre=/usr/sbin/sshd-keygen (code=exited, status=0/SUCCESS)
Main PID: 906 (sshd)
CGroup: /system.slice/sshd.service
├─ 906 /usr/sbin/sshd -D
├─26941 sshd: [accepted]
└─26942 sshd: [net]
Если сервис не работает, вы увидите в выводе inactive:
sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled)
Active: inactive (dead) since Fri 2017-04-21 08:36:13 EDT; 2s ago
Process: 906 ExecStart=/usr/sbin/sshd -D $OPTIONS (code=exited, status=0/SUCCESS)
Process: 899 ExecStartPre=/usr/sbin/sshd-keygen (code=exited, status=0/SUCCESS)
Main PID: 906 (code=exited, status=0/SUCCESS)
Чтобы перезапустить сервис, введите соответственно:
service ssh start
systemctl start sshd
Проверка порта SSH
Существует два основных способа проверить порт SSH: проверить конфигурационный файл SSH или просмотреть запущенный процесс.
Как правило, конфигурационный файл SSH хранится в /etc/ssh/sshd_config. Стандартный порт 22 может переопределяться любой строкой в этом файле, определяющей директиву Port.
Запустите поиск по файлу с помощью команды:
grep Port /etc/ssh/sshd_config
Читайте также: Использование Grep и регулярных выражений для поиска текстовых шаблонов в Linux
Команда вернёт:
Port 22
Если вы уже убедились, что сервис работает, теперь вы можете узнать, работает ли он на требуемом порте. Для этого используйте команду ss. Команда netstat –plnt выдаст аналогичный результат, но команду ss рекомендуется использовать для запроса информации сокета из ядра.
ss -plnt
В выводе должно быть указано имя программы и порт, который она прослушивает. Например, следующий вывод сообщает, что сервис SSH прослушивает все интерфейсы и порт 22.
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:22 *:* users:(("sshd",pid=1493,fd=3))
LISTEN 0 128 :::22 :::* users:(("sshd",pid=1493,fd=4))
Символ * и 0.0.0.0 указывает, что все интерфейсы сервера прослушиваются. Строка 127.0.0.1 значит, что сервис не является общедоступным. В sshd_config директива ListenAddress должна быть закомментирована, чтобы прослушивать все интерфейсы, или должна содержать внешний IP-адрес сервера.
Если у вас не получается самостоятельно настроить соединение SSH, вы можете обратиться за помощью к службе поддержки своего хостинг-провайдера.
Tags: firewalld, Iptables, OpenSSH, PuTTY, SSH, UFW
Содержание
- Применение и возможности PuTTY
- Установка на Windows
- Работа с программой
- Распространенные ошибки
PuTTY — программа, которая позволяет установить соединение с удаленным сервером или компьютером. Программу можно также применять для реализации следующих целей:
- удаленного администрирования;
- взаимодействия с VPS-серверами.
- работы с Telnet-терминалами;
- настройки маршрутизаторов через RS-232;
Работать рекомендуется через SSH, поскольку он обеспечивает высокий уровень безопасности соединения с другим компьютером. PuTTY поддерживает Telnet, реализующий текстовый интерфейс в терминале (только для отображения текстовой информации в режиме консоли).
Возможности программы
- Сохранение информации и конфигурационных параметров для многократного применения.
- Работа с SSH-ключами.
- Поддержка разных версий SSH-протокола.
- Встроенные клиенты SCP и SFTP, используемые для различных операций с файлами. Возможности первого ограничиваются только функцией копирования.
- Перенаправление портов через протокол SSH.
- Поддержка xterm, ECMA-48 и VT-102.
- Возможность соединения по IPv6.
- Работа с алгоритмами шифрования.
- Аутентификация через ключ, который расположен на удаленной машине.
- Соединение через proxy.
- Использование порта RS-232.
Установка на Windows
- Программа PuTTY для Windows 10 скачивается с официального сайта.
- Далее нужно перейти по ссылке, скачать пакет для архитектуры x86 или x64, а затем запустить установку.
- После установки необходимо проверить программу на работоспособность, запустив исполняемый файл на Windows.
Работа с программой
Интерфейс
Пользоваться программой PuTTY удобно, т. к. она имеет понятный интерфейс. Чтобы ее настроить, нужно знать назначение основных ее вкладок.
- Session позволяет задать параметры соединения, чтобы подключиться к серверу (IP-адрес, протокол и порт), а также сохранить настройки для многократного использования.
- Terminal: режим активации или деактивации терминала.
- Window: установка кодировки и изменение интерфейса.
- Connection отвечает за выбор шифрования, аутентификацию без ввода пароля и т. д.
Соединение с удаленным сервером
Принцип подключения не зависит от операционной системы. Это могут быть разные версии Windows (7, 10) или популярные дистрибутивы на основе Linux — Ubuntu, CentOS, Debian.
Подключиться по SSH через PuTTY просто. Для этого нужно следовать приведенной ниже инструкции.
- Ввести IP-адрес или имя хоста, к которому необходимо подключиться.
- Указать порт (по умолчанию везде 22).
- Выбрать тип соединения SSH.
- Ввести название подключения и сохранить его, нажав кнопку «Save».
- Активировать соединение, нажав на «Open».
- Указать данные для авторизации (логин и пароль).
После этого работа с терминалом осуществляется, как на локальном компьютере. Чтобы узнать информацию о версии Ubuntu, нужно ввести команду:
sudo lsb_release -a.
Для удобства можно создать жесткую ссылку (ярлык) на программу для быстрого запуска.
Использование SSH-ключей
Чтобы постоянно не вводить данные авторизации для соединения с удаленным сервером, нужно установить ключ SSH-типа.
Для примера, продемонстрируем ниже, как подключиться через PuTTY, установленного в Windows 10, при помощи SSH-ключа к серверу на Ubuntu.
Шаг №1
Для начала, нужно выполнить ряд действий на компьютере с ОС Windows.
- Установить программу для генерации ключа «Putty Key Generator» и запустить ее.
- Задать параметр «RSA» и активировать процесс кнопкой «Generate». Нужно постоянно вводить указателем мыши в зоне окна выполнения операции для успешной генерации.
- Сохранить private key, для чего скопировать текст из консоли в документ. Предварительно нужно указать тип файла «.ppk».
- Затем сохраняем public key. Для этого необходимо скопировать и вставить текст из буфера обмена в любой пустой текстовый файл.
- Свернуть программу.
Шаг №2
Далее необходимо перенести SSH-ключ на сервер Ubuntu, выполнив перечисленные ниже действия.
- Запустить программу PuTTY.
- Подключиться к серверу, используя его параметры для доступа (хост, порт и SSH-протокол).
- Командой «mkdir .ssh» создаем папку «.ssh». Затем командой «ll» проверяем наличие папки.
- Прописываем права доступа для папки .ssh только для владельца, командой «сhmod 700 .ssh/».
- При помощи команды «cd .ssh» переходим в системную папку «./ssh».
- Создаем файл «authorized_keys», используя редактор nano, командой:
touch authorized_keys
- Прописываем права доступа для файла «authorized_keys», только для владельца, командой:
сhmod 600 authorized_keys
- Редактируем файл с помощью команды:
cat >> authorized_keys << EOF»
- Добавляем ваш public key и заканчиваем редактирование файла командой «EOF».
Шаг №3
Возвращаемся к программе PuTTY на Windows 10.
- Переходим в программу.
- Добавляем данные для подключения.
- Переходим во вкладку «Connection → SSH → Auth». Выбираем для аутентификации сохраненный файл «.ppk».
- Активируем соединение при помощи нажатия «Open».
Работа с файлами
Программа позволяет делать операции с файлами. Чтобы закачать файл на сервер, находящийся под управлением Linux Ubuntu (с компьютера на ОС Windows), нужно действовать по приведенной ниже инструкции.
- Сохранить тестовый файл «mydoc.txt» на диске C: вместе с исполняемым файлом для безопасного копирования — pscp.exe.
- Открыть командную строку Windows: «Win+R → cmd → Enter».
- Зайти в папку с программой pscp.exe, для чего ввести команду: «cd /d c:Puttypscp.exe»*, где «c:Putty» — путь к файлу pscp.exe.
* Путь к файлу «c:Puttypscp.exe» приведен в качестве примера.
- Далее можно приступать непосредственно к работе с файлом. Например, передать файл «mydoc.txt» на сервер «192.241.7.16»* со стандартным портом и пользователем Ubuntu74 в папку «root» можно командой:
* IP-адрес «192.241.7.16» приведен только в качестве примера.
pscp.exe mydoc.txt Ubuntu74@192.241.7.16:/root/
Если для соединения используется нестандартный порт (например, 25), то команда примет вид:
pscp.exe -P 25 mydoc.txt Ubuntu74@192.241.7.16:/root/
- Ввести пароль для Ubuntu74.
Скачать файл через PuTTY с сервера «192.241.7.16» в текущую папку можно с помощью команды:
pscp.exe Ubuntu@192.241.7.16:/root/mydoc.txt
Чтобы объединить файлы, нужно их загрузить на удаленную машину, а затем выполнить команду «sudo cat mydoc1.txt mydoc2.txt > mydoc.txt».
Распространенные ошибки
Проблемы с аутентификацией
PuTTY выдает при подключении сообщение: «Access denied». Это указывает на отказ в доступе, причиной которого являются ошибки при вводе логина или пароля.
Если соединение с удаленным сервером происходит при помощи SSH-ключа, то PuTTY выдаст в диалоговом окне такие строки:
Permission denied (publickey).
PuTTY Error output
Причины ошибки
Ошибка «Access denied» связана с некорректной аутентификацией на основе ключей. Вызвать ее может отсутствие соответствующих прав доступа к файлам или невозможность подтвердить права владельца.
Как решить
- Проверить параметры аутентификации (логин и пароль).
- Проверить наличие и правильность имени SSH-ключа в PuTTY.
- Выполнить проверку содержимого кода SSH-ключа в «authorized_keys».
Если ни один из вариантов не дал положительного результата, то нужно воспользоваться альтернативным графическим клиентом WinSCP. С его помощью нужно реализовать описанную ниже последовательность действий.
- Перейти в папку «/etc/ssh/», а затем открыть файл «sshd_config».
- Далее необходимо найти строки «PasswordAuthentication: YES» и «PermiRootLogin: NO». Значения переменных требуется поменять на противоположные значения, т. е. «PasswordAuthentication: NO» и «PermiRootLogin: YES».
- После сохранения изменений необходимо перезапустить PuTTY и соединиться с удаленным сервером.
Подробнее о том, как создать удаленное соединение для разных дистрибутивов Linux, можно узнать из отдельных руководств:
- Для Ubuntu;
- Для CentOS;
- Для Debian.
Ошибка подключения
Если программа PuTTY выдает ошибку «Unable to open connection to mysite.ru Host does not exist»*, то это свидетельствует о том, что ссылка на SSH-хост не соответствует сетевому адресу.
* Домен mysite.ru приведён для примера.
При истекшем времени подключения или отказе в соединении PuTTY выдаст сообщения «Network error: Connection timed out» и «Network error: Connection refused» соответственно.
Причины ошибки
- Отсутствие сетевого подключения.
- Неверно указан IP-адрес.
- Порт не поддерживается или его значение задано неверно.
- Блокировка исходящего подключения антивирусом или брандмауэром.
Как решить
Чтобы исправить ошибку, рекомендуется действовать по приведенной ниже инструкции.
- Проверить IP-адрес хоста.
- Убедиться, что порт не блокируется какой-либо программой. При необходимости внести его в список исключений.
- Проверить конфигурацию PuTTY во вкладках «Session» и «Connection».
- В список исключений антивируса или брандмауэра необходимо внести стандартный порт 22.
Secure Shell (SSH) is a key WordPress development tool. It grants advanced users access to key platforms and software that make coding and other tasks easier, faster, and more organized.
So if you attempt to use SSH only to see a “Connection refused” error, you may start to feel concerned. However, this is a common issue, and it’s entirely possible to fix it on your own with just a bit of troubleshooting. You’ll be back to running commands in no time flat.
In this post, we’ll discuss what SSH is and when to use it. Then we’ll explain some common reasons your connection may be refused, including in PuTTY. Finally, we’ll provide some troubleshooting tips.
Let’s dive in!
Prefer to watch the video version?
What Is SSH and When Should I Use It?
Secure Shell (SSH), also sometimes called Secure Socket Shell, is a protocol for securely accessing your site’s server over an unsecured network. In other words, it’s a way to safely log in to your server remotely using your preferred command-line interface:
Unlike File Transfer Protocol (FTP), which only enables you to upload, delete, and edit files on your server, SSH can accomplish a wide range of tasks. For instance, if an error locks you out of your WordPress site, you can use SSH to access it remotely.
This protocol also enables you to use several key developer tools, including:
- WP-CLI. The WordPress command line. You can use it for a variety of tasks, including new installations, bulk plugin updates, and media file imports.
- Composer. A PHP package manager. It enables you to implement several frameworks for use in your site’s code by pulling the necessary libraries and dependencies.
- Git. A version control system used to track changes in code. This is especially useful for teams of developers working together on a single project.
- npm. A JavaScript package manager. It includes a command-line and JavaScript software registry. Note: Kinsta customers will need an Enterprise plan in order to access this feature.
It’s important to note that using SSH is an advanced skill. Generally speaking, lay users of WordPress should contact their developers or hosting providers for help, rather than trying to resolve issues with SSH themselves.
Why Is My SSH Connection Refused? (5 Reasons for Connectivity Errors)
Unfortunately, there are many scenarios that could occur while you’re trying to connect to your server via SSH, which might result in an error reading “Connection refused”.
Below are some of the most common issues that might be causing problems for you.
1. Your SSH Service Is Down
In order to connect to your server with SSH, it must be running an SSH daemon – a program that runs in the background to listen for and accept connections.
If this service is down, you will not be able to successfully connect to your server and may receive a Connection refused error:
Your server’s SSH daemon may be down for a wide variety of reasons, including unexpected traffic spikes, resource outages, or even a Distributed Denial of Service (DDoS) attack. In addition to the troubleshooting steps we’ll mention below, you may want to contact your hosting provider to determine the root cause of the issue.
If you suspect that your SSH service might be down, you can run this command to find out:
sudo service ssh status
If the command line returns a status of down, then you’ve likely found the reason behind your connectivity error.
2. You Have the Wrong Credentials
Although it may seem too simple to be true, it’s possible that you’re just entering the wrong credentials when trying to connect to your server. There are four pieces of information needed to run SSH:
- Host name. The IP address of the server you’re trying to connect to or your domain name.
- Username. Your (S)FTP username.
- Password. Your (S)FTP password.
- Port. The default port is 22. However, some hosting providers (including Kinsta) change their SSH port number for security reasons. If this is the case, you should be able to find it by logging in to your MyKinsta dashboard.
You can also check to see which port is being used for SSH by running this command:
grep Port /etc/ssh/sshd_config
The command line should return the correct port.
Check to make sure you’re entering the right credentials and taking into account the possibility of typos or entering the wrong IP address or port.
3. The Port You’re Trying to Use Is Closed
A “port” is simply the endpoint to which you’re directed when connecting to your server. In addition to making sure you have the correct one, you’ll also want to check to see if the port you’re trying to use is open.
Any open port is a security vulnerability, as hackers can try to exploit it and gain access to the server. For this reason, unused ports are often closed to prevent attacks.
In the event that port 22, or the custom SSH port for your server, has been closed, you will likely see a Connection refused error. You can see all the ports listening on your server by running this command:
sudo lsof -i -n -P | grep LISTEN
This command should return a list of ports with the LISTEN state. Ideally, you want to see port 22 or your server’s custom SSH port listed here. If it’s not, you’ll need to reopen the port in order to connect to your server.
4. SSH Isn’t Installed on Your Server
As we briefly mentioned earlier, servers use SSH daemons to listen for and accept connections. Therefore, if the server you’re trying to connect to doesn’t have one installed, you won’t be able to access it using SSH.
Generally speaking, almost all hosting providers will have SSH daemons installed on their servers by default. This particular issue is more common on localhost or dedicated servers.
5. Firewall Settings Are Preventing an SSH Connection
Since open ports present a security risk, firewalls installed to protect servers from hackers sometimes block connections to them. Unfortunately, this means that even harmless users who are trying to SSH into their servers may receive a Connection refused error as a result of firewall settings.
If your setup appears to be in order and you still can’t connect, take a look at your firewall’s rules. You can display them in your command-line interface with the following commands:
sudo iptables-save # display IPv4 rules
sudo ip6tables-save # display IPv6 rules
Your results will vary, but you’ll want to look for these elements to determine if your firewall is blocking SSH connections:
- dport 22: This refers to the destination port, which for SSH is usually port 22 (reminder: Kinsta doesn’t use this port number).
- REJECT: This would indicate that connections are being refused from the specified destination.
- DROP: Like REJECT, this means that connections to the relevant port are being blocked.
If you search the results of the commands above for dport 22, you should be able to determine if your firewall is preventing an SSH connection. If so, you’ll have to change the rules to accept requests.
Why Does PuTTY Say Connection Refused?
PuTTY is an SSH client. If you’re familiar with FTP, this platform is the FileZilla equivalent to SSH on Windows machines. In other words, PuTTY enables users to input their credentials and launch an SSH connection:
If you’re a PuTTY user and see the Connection refused error, the cause is likely one of those listed above.
This is an SSH connectivity error like any other, and the troubleshooting tips below should work whether you’re using PuTTY, Terminal, or any other program for connecting to your server with SSH.
We’ve taken our knowledge of effective website management at scale, and turned it into an ebook and video course. Click to download The Guide to Managing 60+ WordPress Sites!
How Do I Troubleshoot SSH Connectivity Errors?
When you’re experiencing an SSH connectivity error, there are a few steps you can take to troubleshoot it depending on the cause. Here are some tips for troubleshooting the reasons for a Connection refused error that we covered above:
- If your SSH service is down. Contact your hosting provider to see why your SSH service isn’t running. For localhost or dedicated servers, you can use the command
sudo service ssh restart
to try to get it running again. - If you entered the wrong credentials. Once you’ve double-checked the SSH port using the
grep Port /etc/ssh/sshd_config
command, try connecting again with the correct details. - If your SSH port is closed. This is usually a side effect of one of the two reasons listed below. Either install an SSH daemon on the server you want to connect to or change your firewall rules to accept connections to your SSH port.
- If SSH isn’t installed on your server. Install an SSH tool such as OpenSSH on the server you want to connect to using the
sudo apt install openssh-server
command. - If your firewall is blocking your SSH connection. Disable the firewall rules blocking your SSH connection by changing the destination port’s settings to ACCEPT.
If you’re attempting to connect to your hosting provider’s server, it may be wiser to contact support than to try troubleshooting the problem yourself. Users on localhost or dedicated servers may be able to find further support on more advanced forums if none of the above solutions works.
Are you getting the ‘Connection refused’ error over SSH? Learn why that’s happening and how to troubleshoot SSH connectivity errors thanks to this guide 🙅 ✋Click to Tweet
Summary
Being able to connect to your server with SSH is convenient in a wide range of situations. It can enable you to access your site when you’re locked out of your WordPress dashboard, run commands via WP-CLI, track changes in your site’s code with Git, and more.
Although there are several causes that could be behind your SSH connectivity error, these are a few of the most common:
- Your SSH service is down.
- You have the wrong credentials.
- The port you’re trying to use is closed.
- SSH isn’t installed on your server.
- Firewall settings are preventing an SSH connection.
Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
- Easy setup and management in the MyKinsta dashboard
- 24/7 expert support
- The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
- An enterprise-level Cloudflare integration for speed and security
- Global audience reach with up to 35 data centers and 275 PoPs worldwide
Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.