Ssh connect to host localhost port 22 connection refused windows

I want to try ssh myself (windows) so I open cmd and type: ssh 127.0.0.1. But I got this error: ssh: connect to host 127.0.0.1 port 22: Connection refused. I tried to use Putty but I got the same ...

Microsoft does not currently provide SSH server software for its Windows operating system. However, if you haven’t already installed SSH server software on your Windows system, there are quite a few commercial SSH server packages available for Windows and there is also free SSH server software. Some companies that provide commercial versions will allow you to use their software for free for noncommercial use. Some free versions that I’ve used:

Bitvise SSH Server — free for personal use

Copssh — the name is from «Cygwin» + «OpenSSH»

freeSSHd

OpenSSH for Windows — the software hasn’t been updated since, 2004. I found it worked well under Windows XP, but I experienced problems with it on later operating systems and wouldn’t recommend it.

PowerShell SSH Server for Windows — the Personal Edition is free; it limits you to one SSH connection to the server at a time.

SilverSHield — free for personal use version limited to one concurrent SSH connection

If you’ve got Cygwin installed already, you can install OpenSSH server software for Cygwin.

Microsoft has, apparently, «seen the light» and has announced that it intends to provide SSH server software for its Windows operating systems, e.g., see the June 2, 2015 Ars Technica article Microsoft bringing SSH to Windows and PowerShell.

While installing hadoop in my local machine , i got following error

ssh -vvv localhost 
OpenSSH_5.5p1, OpenSSL 1.0.0e-fips 6 Sep 2011 
debug1: Reading configuration data /etc/ssh/ssh_config    
debug1: Applying options for * 
debug2: ssh_connect: needpriv 0 
debug1: Connecting to localhost [127.0.0.1] port 22. 
debug1: connect to address 127.0.0.1 port 22: Connection refused 
ssh: connect to host localhost port 22: Connection refused

can some one help me to resolve this error , than changing port number

guntbert's user avatar

guntbert

5166 silver badges19 bronze badges

asked Jun 27, 2013 at 6:10

Surya's user avatar

If install Hadoop on Mac OSX, make sure turn on Remote Login under System Preferences then File Sharing. This worked on my machine.

Remote Login

answered Mar 7, 2014 at 16:15

vladof81's user avatar

vladof81vladof81

25.5k9 gold badges37 silver badges41 bronze badges

1

  1. Remove SSH with the following command:

    sudo apt-get remove openssh-client openssh-server
    
  2. Install SSH again with:

    sudo apt-get install openssh-client openssh-server
    

It will solve your problem.

Ronan Boiteau's user avatar

answered Aug 9, 2014 at 16:58

Divyang Shah's user avatar

Divyang ShahDivyang Shah

1,5281 gold badge11 silver badges22 bronze badges

12

Do you have sshd installed? You can verify that with:

which ssh
which sshd

For detailed information you can visit this link.

Ronan Boiteau's user avatar

answered Jun 27, 2013 at 6:27

Tariq's user avatar

TariqTariq

33.9k8 gold badges56 silver badges79 bronze badges

3

Try installing whole SSH package pack:

sudo apt-get install ssh

I had ssh command on my Ubuntu but got the error as you have. After full installation all was resolved.

Ronan Boiteau's user avatar

answered Apr 25, 2015 at 17:17

Michael Z's user avatar

Michael ZMichael Z

3,7639 gold badges41 silver badges56 bronze badges

3

I use a Mac, this worked for me:

Open System Preferences, then search for ‘sharing’.

Choose Remote Login, make sure it is on and remember to add required users.enter image description here

Got it from here

answered May 4, 2020 at 9:07

Dami's user avatar

DamiDami

6476 silver badges12 bronze badges

1

I did all the suggestion above and it did not work. Then I restart the ssh service and it works. This is what I do:

service sshd restart

Then I redo

ssh localhost

Now I can connect to my localhost. Hope it helps

beedell.rokejulianlockhart's user avatar

answered Jun 8, 2016 at 22:24

Arwan Khoiruddin's user avatar

1

Check if this port is open. Maybe your SSH demon is not running. See if sshd is running. If not, then start it.

Ronan Boiteau's user avatar

answered Jun 27, 2013 at 6:25

abhinav's user avatar

abhinavabhinav

1,23210 silver badges27 bronze badges

6

I used:

sudo service ssh start

Then:

ssh localhost

answered Apr 1, 2018 at 12:00

Linh's user avatar

LinhLinh

1432 silver badges8 bronze badges

0

If you restart service then it will work

$ service sshd restart

then check

$ ssh localhost

It will work

Boiethios's user avatar

Boiethios

35.7k16 gold badges129 silver badges177 bronze badges

answered Oct 19, 2016 at 10:49

Rushikesh's user avatar

RushikeshRushikesh

811 silver badge1 bronze badge

0

Make sure that /etc/hosts.allow contains:

ssh:ALL:allow
sshd:ALL:allow

OR

ssh:localhost:allow
sshd:localhost:allow

OR — some other variant

ssh:{host1,host2,host3...}:allow
sshd{host1,host2,host3...}:allow

INSURE that the first line in the file DOES NOT begin with ALL:ALL:DENY

NOTHING will be able to communicate with the host… on any port.

j0k's user avatar

j0k

22.4k28 gold badges80 silver badges88 bronze badges

answered Oct 4, 2013 at 18:30

Larry Helms's user avatar

1

For my case(ubuntu 14.04, fresh installed), I just run the following command and it works!

sudo apt-get install ssh

answered May 30, 2016 at 2:52

Shiqing Fan's user avatar

Shiqing FanShiqing Fan

6782 gold badges7 silver badges14 bronze badges

For what its worth I got the following error trying to ssh into my local machine, running Ubuntu 16.04 Xenial, from a vm.

 ssh: connect to host 192.168.144.18 port 22: Connection refused

It got immediately fixed with:

sudo apt-get install ssh

Take note, Before fix: ‘which sshd’ returned nothing and ‘which ssh’ returned

/usr/bin/ssh

And After the fix: ‘which sshd’ returned

/usr/sbin/sshd

answered May 31, 2017 at 10:23

IskandarG's user avatar

IskandarGIskandarG

3131 gold badge3 silver badges9 bronze badges

It might be caused by some of the following:

  1. SSH Server is not installed (only SSH Client), try: apt-get install ssh openssh-client openssh-server
  2. Connection is blocked by iptables (Firewall), try: ufw allow ssh

answered Jun 23, 2016 at 10:19

damian1baran's user avatar

damian1barandamian1baran

1,2871 gold badge14 silver badges13 bronze badges

1

On mac go to system settings->network->sharing and allow remote login.

try ssh localhost

You should be good.

answered Mar 3, 2017 at 16:16

user2498105's user avatar

What worked for me is:

sudo mkdir /var/run/sshd
sudo apt-get install --reinstall openssh-server

I tried all the above mentioned solutions but somehow this directory /var/run/sshd was still missing for me. I have Ubuntu 16.04.4 LTS. Hope my answer helps if someone has the same issue.
ubuntu sshxenial

answered Feb 21, 2019 at 17:48

Frida Schenker's user avatar

Frida SchenkerFrida Schenker

1,1411 gold badge8 silver badges14 bronze badges

  1. Before installing/reinstalling anything check the status of sshd . . .
sudo systemctl status sshd
  1. You should see something like . . .
● sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; disabled; vendor prese>
   Active: inactive (dead)
     Docs: man:sshd(8)
           man:sshd_config(5)
  1. Just enable and start sshd
sudo systemctl enable sshd
sudo systemctl start sshd

answered Jul 30, 2020 at 1:04

0p3r4t0r's user avatar

0p3r4t0r0p3r4t0r

5634 silver badges11 bronze badges

1

Actually i solved this,
I just installed shh daemon.

in terminal :

sudo apt-get install openssh-server

answered Sep 25, 2016 at 17:04

User Learning's user avatar

User LearningUser Learning

3,0055 gold badges30 silver badges51 bronze badges

If you’re certain that you have installed ssh, then it’s possible that ssh and/or sshd has been terminated or the server service hasn’t been started. To check whether these processes are running use:

//this tells you whether your ssh instance is active/inactive
sudo service ssh status

OR

//this list all running processes whose names contain the string "ssh"
sudo ps -A | grep ssh

It’s likely that ssh would be active and running but sshd would not.
To enable them:

sudo service ssh start

NB;
— some systems have a restart option but mine didn’t

answered Mar 7, 2018 at 21:32

Kwaku Sarpong Manu's user avatar

try sudo vi /etc/ssh/sshd_config

in first few lies you’ll find

Package generated configuration file

See the sshd_config(5) manpage for details

What ports, IPs and protocols we listen for

Port xxxxx

change Port xxxxx to «Port 22» and exit vi by saving changes.

restart ssh sudo service ssh restart

answered Jun 2, 2020 at 9:33

Himanshu Singh's user avatar

My port number is different. i tried using

ssh localhost -p 8088

this worked for me

If you still face problems, try the following:

sudo ufw enable    
sudo apt-get install openssh-server

This might work too.

OhBeWise's user avatar

OhBeWise

5,2803 gold badges34 silver badges58 bronze badges

answered Jul 14, 2015 at 17:52

Dinesh's user avatar

A way to do is to go to terminal

$ sudo gedit /etc/hosts

***enter your ip address ipaddress of your pc  localhost 
    ipaddress of your pc  localhost(Edit your pc name with localhost) **

and again restart your ssh service using:

$ service ssh restart

Problem will be resolve.
Thanks

answered Jan 11, 2017 at 14:01

Sanyog Tiwari's user avatar

0

if you are using centOS or Red Hat, you should first update SElinux.
Execute the following statement

ausearch -c 'sshd' --raw | audit2allow -M my-sshd

then you need to execute

semodule -i my-sshd.pp

good luck

answered Nov 9, 2017 at 18:33

Berk CELEBI's user avatar

You may should edit your /etc/hosts. For example if my hostname is ub0, but the hostname in /etc/hosts is localhost, it may occur

connect to host ub0 port 22: Connection refused

Because the hostname in /etc/hosts is localhost not ub0.

So, you should be careful the hostname when building up distributed clusters.

answered Apr 28, 2016 at 9:43

GoingMyWay's user avatar

GoingMyWayGoingMyWay

16.3k30 gold badges95 silver badges141 bronze badges

For Linux:

  1. Remove SSH with the following command:

    sudo apt-get remove openssh-client openssh-server
    
  2. Install SSH again with:

    sudo apt-get install openssh-client openssh-server
    

finefoot's user avatar

finefoot

9,1577 gold badges52 silver badges86 bronze badges

answered Dec 16, 2018 at 22:11

Nehal Pawar's user avatar

you need to check the configuration in sshd_config ListenAddress 0.0.0.0 update this and restart the sshd service that will resolve the issue.

answered Jan 16, 2019 at 16:49

Rupeshrams's user avatar

Check file /etc/ssh/sshd_config for Port number. Make sure it is 22.

answered May 13, 2020 at 11:15

hiruna72's user avatar

What worked for me was modifying the ssh config file to the following:

Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa

answered Jan 13 at 11:59

Mariusz Szymoniak's user avatar

if youre apache server is not running your local host wont run check that out
there are some articles if you dont get it i will leave a link here ;)

check this

I had same error got it done rn

answered Nov 26, 2021 at 10:21

peqhv2's user avatar

1

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:

ssh login example

Using SSH to remotely access a WordPress site hosted on Kinsta

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:

connection refused error

Connection Refused error in Terminal

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:

download putty

The PuTTY website

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 here to download the The 2020 Guide to Managing 40+ 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:

  1. Your SSH service is down.
  2. You have the wrong credentials.
  3. The port you’re trying to use is closed.
  4. SSH isn’t installed on your server.
  5. 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.

25 мая, 2017 11:40 дп
86 046 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 8) используется команда 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

  • Remove From My Forums
  • Question

  • Hi

    Im trying to get SSH working from PowerShell and using ‘ssh localhost’ as a test but i get the following:

    «ssh: connect to host localhost port 22: Connection refused»

    It looks like port 22 is closed. I have tried adding inbound and outbound rules to allow ssh but no luck, then disabled windows firewall but also no luck. On both accounts iv used wf.msc to make the changes.

    Is there anything i could possibly be missing?

    Thanks.

    • Edited by

      Friday, January 25, 2019 4:42 PM
      text amendment

Answers

  • Hi all

    Thanks so much for getting back to you me, only just had the chance to jump back on to this issue.

    As mentioned by EckiS and momominta from Calgary, i had indeed only installed OpenSSH Client and not OpenSSH Server!

    After installing OpenSSH Server i was able to use SSH.

    Thanks very much for helping.

    • Marked as answer by
      anthui
      Friday, February 8, 2019 8:54 AM

Содержание

  1. Введение
  2. Клиент SSH не установлен
  3. Решение: Установите SSH-клиент
  4. Демон SSH не установлен на сервере
  5. Решение: Установите SSH на удаленном сервере
  6. Неверные учетные данные
  7. Служба SSH не работает
  8. Решение: Включите службу SSH
  9. Брандмауэр препятствует подключению SSH
  10. Решение: Разрешить SSH-соединения через брандмауэр
  11. Порт SSH закрыт
  12. Решение: Открыть порт SSH
  13. Отладка и логирование SSH
  14. Заключение

Введение

У вас возникли проблемы с доступом к удаленному серверу по SSH?

Если SSH отвечает сообщением “Connection refused“, вам может потребоваться изменить запрос или проверить настройку.

В этом руководстве вы найдете наиболее распространенные причины ошибки отказа в подключении SSH.

Почему происходит отказ в подключении при SSH?

Существует множество причин, по которым вы можете получить ошибку “Connection refused” при попытке подключиться по SSH к вашему серверу. Чтобы решить эту проблему, сначала нужно определить, почему система отказала вам в подключении по SSH.

Ниже приведены некоторые из наиболее распространенных причин, которые могут вызвать отказ в подключении по SSH.

Клиент SSH не установлен

Прежде чем приступать к устранению других проблем, необходимо проверить, установлен ли у вас SSH.

На машине, с которой вы получаете доступ к серверу, должен быть установлен клиент SSH.

Без правильной установки клиента вы не сможете удаленно подключиться к серверу.

Чтобы проверить, установлен ли в вашей системе клиент SSH, введите в окне терминала следующее:

ssh

Если терминал выдает список опций команды ssh, клиент SSH установлен в системе.

Однако если он отвечает “command not found“, необходимо установить клиент OpenSSH.

Решение: Установите SSH-клиент

Чтобы установить SSH-клиент на вашу машину, откройте терминал и выполните одну из перечисленных ниже команд.

Для систем Ubuntu/Debian:

sudo apt install openssh-client

Для систем CentOS/RHEL:

sudo yum install openssh-client

Демон SSH не установлен на сервере

Точно так же, как вам нужна клиентская версия SSH для доступа к удаленному серверу, вам нужна серверная версия для прослушивания и приема соединений.

Поэтому сервер может отклонить входящее соединение, если SSH-сервер отсутствует или его установка недействительна.

Чтобы проверить доступен ли SSH на удаленном сервере, выполните команду:

ssh localhost

Если в выводе появится ответ “Connection refused”, переходите к установке SSH на сервере.

Решение: Установите SSH на удаленном сервере

Чтобы решить проблему отсутствия сервера SSH, обратитесь к разделу о том, как установить сервер OpenSSH.

Как установить OpenSSH-сервер из исходников в Linux

🛡️ Как обезопасить и защитить сервер OpenSSH

Неверные учетные данные

Неправильные учетные данные являются распространенными причинами отказа в SSH-соединении.

Убедитесь, что вы не вводите имя пользователя или пароль неправильно.

Затем проверьте, правильно ли вы используете IP-адрес сервера.

Наконец, убедитесь, что у вас открыт правильный порт SSH.

Проверить это можно, выполнив следующие действия:

grep Port /etc/ssh/sshd_config

На выводе отображается номер порта, как показано на рисунке ниже.

Примечание: Вы можете подключиться к удаленной системе по SSH, используя аутентификацию с помощью пароля или открытого ключа (беспарольный вход по SSH). Если вы хотите настроить аутентификацию с открытым ключом, обратитесь к разделу  🔬 Как обменяться ключом SSH для аутентификации без пароля между серверами Linux

Служба SSH не работает

Служба SSH должна быть включена и работать в фоновом режиме.

Если служба не работает, демон SSH не сможет принимать соединения.

Чтобы проверить состояние службы, введите эту команду:

sudo service ssh status

Решение: Включите службу SSH

Если система показывает, что демон SSH не активен, вы можете запустить службу, выполнив следующие действия:

systemctl start sshd

Чтобы включить запуск службы при загрузке системы, выполните команду:

sudo systemctl enable sshd

Брандмауэр препятствует подключению SSH

SSH может отказывать в подключении из-за ограничений брандмауэра.

Брандмауэр защищает сервер от потенциально опасных соединений.

Однако если в системе настроен SSH, необходимо настроить брандмауэр так, чтобы он разрешал SSH-соединения.

Убедитесь, что брандмауэр не блокирует SSH-соединения, так как это может привести к ошибке “connection refused“.

Решение: Разрешить SSH-соединения через брандмауэр

Чтобы решить проблему, о которой мы говорили выше, вы можете использовать ufw (Uncomplicated Firewall), инструмент интерфейса командной строки для управления конфигурацией брандмауэра.

Введите следующую команду в окне терминала, чтобы разрешить SSH-соединения:

sudo ufw allow ssh

Порт SSH закрыт

Когда вы пытаетесь подключиться к удаленному серверу, SSH отправляет запрос на определенный порт.

Чтобы принять этот запрос, на сервере должен быть открыт порт SSH.

Если порт закрыт, сервер отказывает в подключении.

По умолчанию SSH использует порт 22.

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

Чтобы перечислить все прослушиваемые порты, выполните команду:

sudo lsof -i -n -P | grep LISTEN

Найдите порт 22 в выводе и проверьте, установлено ли значение STATE в LISTEN.

Также вы можете проверить, открыт ли определенный порт, в данном случае порт 22:

sudo lsof -i:22


Решение: Открыть порт SSH

Чтобы включить порт 22 для прослушивания запросов, используйте команду iptables:

sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT

Вы также можете открыть порты через графический интерфейс, изменив настройки брандмауэра.

Отладка и логирование SSH

Для анализа проблем с SSH в Linux можно включить режим verbose или режим отладки.

Когда вы включаете этот режим, SSH выводит отладочные сообщения, которые помогают устранить проблемы с подключением, конфигурацией и аутентификацией.

Существует три уровня :

  • уровень 1 (-v)
  • уровень 2 (-vv)
  • уровень 3 (-vvv)

Поэтому вместо доступа к удаленному серверу с помощью синтаксиса ssh [server_ip] добавьте опцию -v и выполните команду:

ssh -v [server_ip]

В качестве альтернативы вы можете использовать:

ssh -vv [server_ip] или
ssh -vvv [server_ip]

Заключение

В этой статье перечислены некоторые из наиболее распространенных причин ошибки SSH “Connection refused”.

Чтобы устранить проблему, просмотрите список и убедитесь, что все параметры настроены правильно.

> В Windows Firewoll порты 21 и 22 открыл
вообще-то openssh server и windows — вещи трудно совместимые. вы уверены, что установили именно серверную часть и именно на windows?
> с чем еще может быть связана ошибка?
с тем, что вы установили не то, что надо.

порт закрыт, проверить можете через telnet

Проверьте что он запущен далее призываем консоль cmd в режиме ADmin, и вкарячиваем netstat — aon и ищем ваш сервер, там есть пиды по ним вы можете сравнить в диспетчере приложений что запущено на порту.

По вашей изначальной проблеме, либо порт не открыт, либо сервис не установлен, либо висит на другом порту, либо ещё что, не знаю -v покажет или нет, как вариант можете wireshark’ом посмотреть содержание почему именно connection refused. По проблеме которой вы поделились в комментариях — не указан алгоритм ключа в конфиге.
Попробуйте ssh -v юзер@сервер и напишите вывод.

Introduction

Are you having problems accessing a remote server over SSH? If SSH responds with a «Connection refused» message, you may need to modify the request or check the setup.

In this tutorial, you will find the most common reasons for the SSH connection refused error.

How to fix the ssh connection refused error.

Why is Connection Refused When I SSH?

There are many reasons why you might get the «Connection refused» error when trying to SSH into your server. To solve this problem, you first need to identify why the system refused your connection via SSH.

Below you will find some of the most common reasons that may cause an SSH connection denial.

SSH Client Not Installed

Before troubleshooting other issues, the first step is to check whether you have SSH properly installed. The machine you are accessing the server from should have the SSH client set up. Without the correct client set up, you cannot remote into a server.

To can check if you have the SSH client on your system, type the following in the terminal window:

ssh
Check if SSH client is installed on system.

If the terminal provides a list of ssh command options, the SSH client is installed on the system. However, if it responds with command not found, you need to install the OpenSSH Client.

Solution: Install SSH Client

To install the SSH Client on your machine, open the terminal, and run one of the commands listed below.

For Ubuntu/Debian systems:

sudo apt install openssh-client

For CentOS/RHEL systems:

sudo yum install openssh-client

SSH Daemon Not Installed on Server

Just like you need the client version of SSH to access a remote server, you need the server version to listen for and accept connections. Therefore, a server may refuse an incoming connection if the SSH server is missing or the setup is not valid.

To check whether SSH is available on the remote server, run the command:

ssh localhost

If the output responds with «Connection refused«, move on to installing SSH on the server.

Solution: Install SSH on Remote Server

To fix the issue of a missing SSH server, refer to how to install the OpenSSH server.

Credentials are Wrong

Typos or incorrect credentials are common reasons for a refused SSH connection. Make sure you are not mistyping the username or password.

Then, check whether you are using the correct IP address of the server.

Finally, verify you have the correct SSH port open. You can check by running:

grep Port /etc/ssh/sshd_config

The output displays the port number, as in the image below.

Check SSH port number.

Note: You can SSH into a remote system using password authentication or public key authentication (passwordless SSH login). If you want to set up public key authentication, refer to How To Set Up Passwordless SSH Login.

SSH Service is Down

The SSH service needs to be enabled and running in the background. If the service is down, the SSH daemon cannot accept connections.

To check the status of the service, enter this command:

sudo service ssh status

The output should respond that the service is active. If the terminal responds that the service is down, enable it to resolve the issue.

Check if SSH service is running.

Solution: Enable SSH Service

If the system shows the SSH daemon isn’t active, you can start the service by running:

systemctl start sshd

To enable the service to run at boot, run the command:

sudo systemctl enable sshd

Firewall is Preventing SSH Connection

SSH can refuse a connection due to firewall restrictions. The firewall protects the server from potentially harmful connections. However, if you have SSH set up on the system, you must configure the firewall to allow SSH connections.

Ensure the firewall does not block SSH connections as this may cause the «connection refused» error.

Solution: Allow SSH Connections Through Firewall

To fix the issue we mentioned above, you can use ufw (Uncomplicated Firewall), the command-line interface tool for managing firewall configuration.

Type the following command in the terminal window to allow SSH connections:

sudo ufw allow ssh
Configure UFW to allow SSH.

SSH Port is Closed

When you attempt a connection to a remote server, SSH sends a request to a specific port. To accept this request, a server needs to have the SSH port open.

If the port is closed, the server refuses the connection.

By default, SSH uses port 22. If you haven’t made any configuration changes to the port, you can check if the server is listening for incoming requests.

To list all ports that are listening, run:

sudo lsof -i -n -P | grep LISTEN

Find port 22 in the output and check whether its STATE is set to LISTEN.

Alternatively, you can check whether a specific port is open, in this case, port 22:

sudo lsof -i:22
Check if port 22 is open.

Solution: Open SSH Port

To enable port 22 to LISTEN to requests, use the iptables command:

sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT

You can also open ports through the GUI by altering the firewall settings.

SSH Debugging and Logging

To analyze SSH problems in Linux, you can turn on verbose mode or debugging mode. When you enable this mode, SSH prints out debugging messages which help troubleshoot issues with connection, configuration, and authentication.

There are three levels of verbosity:

  • level 1 (-v)
  • level 2 (-vv)
  • level 3 (-vvv)

Therefore, instead of accessing a remote server using the syntax ssh [server_ip] add the -v option and run:

ssh -v [server_ip]
SSH in verbose mode.

Alternatively, you can use:

ssh -vv [server_ip]

or

ssh -vvv [server_ip]

Conclusion

This article listed some of the most common reasons for the SSH «Connection refused» error. To troubleshoot the issue, go through the list and make sure all the settings are configured correctly.

The other common issue that you may stumble upon is SSH Failed Permission Denied. Learn what is the cause of this error and how to fix it in our article on How To Fix SSH Failed Permission Denied (Publickey,Gssapi-Keyex,Gssapi-With-Mic).

Понравилась статья? Поделить с друзьями:
  • Ssh connect from windows to linux
  • Ssd определяется как флешка windows 10
  • Ssh config windows 10 где находится
  • Ssd не определяется в windows через usb
  • Ssd накопитель не отображается в windows 10